I. Title Description
Two. Problem solving skills
This problem is similar to the Remove duplicates from Sorted array, except that it allows duplicate numbers to be used in binary search variants, except for the process of rejecting the same elements as the first element. Another idea is to add a variable that records the number of occurrences of an element. This is because it is a sorted array, so a variable can be solved. If there is no sorted array, you need to introduce a hash table to record the number of occurrences.
Three. Sample code
Class Solution {Public:int Removeduplicatesfromstart (int* A, int n) {int numberofduplicates = 0; int Start = a[0]; for (int Index = 1; Index < n; index++) {if (Start! = A[index]) {break; } numberofduplicates++; } return numberofduplicates; } int Removeduplicatesfromend (int* A, int n) {int numberofduplicates = 0; int Start = a[0]; for (int Index = n-1; Index > 0; index--) {if (Start! = A[index]) {break; } numberofduplicates++; } return numberofduplicates; } bool Search (int a[], int n, int target) {if (n < 1) {return false; } if (n = = 1) {if (a[0] = = target) {return true; } return false; } if (n = = 2) {if (a[0] = = target) {return true; } if (a[1] = = target) {return true; } return false; } if (a[0] = = target) {return true; }//Remove the duplicates int duplicatesfromstart = Removeduplicatesfromstart (A, N); if (Duplicatesfromstart = = (n-1)) {return false; } int duplicatesfromend = Removeduplicatesfromend (A, N); if (Duplicatesfromend = = (n-1)) {return false; } n = n-duplicatesfromstart-duplicatesfromend; if (n < 2) {return false; } A = a + Duplicatesfromstart; if (A[N/2] = = target) {return true; } if (A[0] > tArget) {if (A[0] < A[N/2]) {return search ((A + N/2), (N-n/ 2), target); } if (A[N/2] < target) {return search ((A + N/2), (N-n/2), target); } return Search (A, (N/2), target); } else {if (A[0] < A[N/2]) {if (A[N/2] < target) {return Search ((A + N/2), (N-n/2), target); } return Search (A, (N/2), target); } return Search (A, (N/2), target); } } };
Four. Experience
The above algorithm uses a variant of the binary search algorithm, but is added to reject and the first element of the same element of the process, after joining the process, I used the method in the worst case (all elements are the same case) the time complexity of O (n).
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode notes: Remove duplicates from Sorted Array II