Now that there is an array that is known to be more than half the number of occurrences, use an O (n) complexity algorithm to find this number.
Analysis: Set number A appears more than half times. Each time you delete two different numbers, the number a appears more than half in the remaining number. By repeating this process, the final result is obtained. This topic is the same as the beauty of programming in the search for water kings.
[CPP] View plain copy #include <iostream> using namespace std; //size the size of array a //Returns more than half of the numbers in the array int search (int *a,int size) { int count=0; int current; for (int i=0;i<size;i++) { if (count==0) { current=A[i]; count=1; } else { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp; if (a[i]==current) count++; else count--; } } return current; } int main () { int A[6]={1,2,2,1,1,1}; int B[7]={1,0,1,0,0,1,1}; int C[7]={3,4,6,3,3,3,7}; cout<<search (a,6) << " "; cout<<search (b,7) << " "; &nbSp; cout<<search (c,7) << " " <<endl; int i; cin>>i; return 0; }
[CPP] view plain copy