Title: There is a number in the array that exceeds half the length of the array, please find this number.
Solution One: O (N) algorithm based on partition function
1 intPartition (vector<int>&num,intLowintHigh )2 {3 intPivot =Num[low];4 while(Low <High )5 {6 while(Low < High && num[high]>=pivot)7--High ;8Num[low] =Num[high];9 while(Low < High && num[low]<=pivot)Ten++Low ; OneNum[high] =Num[low]; A } -Num[low] =pivot; - returnLow ; the } - BOOLIsinputinvalid =false; - intMorethanhalfnum (vector<int>&num) - { + intn =num.size (); - //Check that the input is valid + if(n==0) A { atIsinputinvalid =true; - return 0; - } - intleft =0; - intEnd = Num.size ()-1; - intMiddle = n/2; in intindex =partition (num,left,right); - while(index!=middle) to { + if(Index <middle) - { theleft = index+1; *index =partition (num,left,right); $ }Panax Notoginseng Else - { theright = index-1; +index =partition (num,left,right); A } the } + //confirm that the number found appears more than half of the array - inttemp =0; $ for(inti =0; I < n; ++i) $ { - if(Num[i] = =Num[index]) -++temp; the } - if(Temp <=middle)Wuyi { theIsinputinvalid =true; - return 0; Wu } - returnNum[index]; About}
PS: Using the partition function to solve the problem will change the position of the elements in the array, which requires the interviewer to ask whether the array allows modification. Second, be careful to check that the input is valid.
Solution Two: Based on the array features to find O (N) algorithm.
See Leetcode-majority Element.
Solution Three: Use hash table to solve.
1 BOOLIsinputinvalid =false;2 intMorethanhalfnum (vector<int>&num)3 {4unordered_map<int,int>m;5 intn =num.size ();6 //Check that the input is valid7 if(n==0)8 {9Isinputinvalid =true;Ten return 0; One } A for(inti =0; I < n; ++i) - { - if(M.count (Num[i])) them[num[i]]++; - Else -m[num[i]]=1; - if(M[num[i]] > n/2) + returnNum[i]; - } +Isinputinvalid =true; A return 0; at}
Interview 29: Number of occurrences in an array of more than half