/* topic: There are a number of array number that appears more than half the length of the array, find this number. For example, a length of the input array 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears five times, more than half the length of the array in the array, the output 2. If there is 0 output. */ /* Ideas: Into fast row, the first n / 2 large number. Verify that the number exceeds half of the total length. */ #include<iostream> #include<string.h> #include<stdio.h> #include<set> #include<vector> using namespace std; int core(vector<int> &numbers, int beginIndex,int endIndex,int target){ int k = endIndex; int val = numbers[endIndex]; for(int i = endIndex-1; i >= beginIndex; i--){ if(numbers[i] > val){ swap(numbers[i],numbers[k]); k--; } } if(k == target){ return numbers[k]; }else if(k > target){ return core(numbers,beginIndex,k-1,target); }else{ return core(numbers,k+1,endIndex,target); } } bool isTarget(vector<int> &numbers,int targetValue){ int times = 0; for(int i = 0; i < numbers.size(); i++){ if(numbers[i] == targetValue){ times++; } } if(times*2 > numbers.size()){ return true; }else{ return false; } } int MoreThanHalfNum_Solution(vector<int> numbers) { if(numbers.empty()) return 0; int target = numbers.size()/2; int targetValue = core(numbers,0,numbers.size()-1,target); cout<<targetValue<<endl; if(isTarget(numbers,targetValue)){ return targetValue; }else{ return 0; } } int main () { vector<int> a = {4,2,1,4,2,4}; cout<<MoreThanHalfNum_Solution(a)<<endl; }