There is a number in the array that appears more than half the length of the array to find the number
The time complexity of this algorithm is O (n), and two additional variables are used.
K is used to temporarily store the data in an array, and J is used to store the number of occurrences.
At the beginning, K stores the first number in the array, J is 0, if the array appears in the number of equal to K, then J plus 1, otherwise minus 1, if J is 0, the current array of the number of assigned to K
Since the specified number of occurrences is greater than half the length of the array, and all J + + and j--are offset, the value of the last J is greater than or equal to 1, and the number stored in K is the number that appears most.
The following algorithm is only suitable for arrays where the number of occurrences of an array exceeds half the length of the array, in accordance with test instructions.
C implementation
1#include <stdio.h>2#include <stdlib.h>3 intSearch (intA[],intlen)4 {5 if(Null==a | | len<=0)6 {7 return-1;8 }9 Ten intK, j=0; One for(intI=0; i<len;++i) A { - if(j==0) - { thek=A[i]; - } - if(k==A[i]) - { +++J; -}Else + { A--J; at } - } - - returnK; - } - voidMain () { in intlen=Ten; - inta[Ten]={4,5,5,2,3,5,2,5,5,5}; to intresult=Search (A,len); +printf"%d\n", result); -}
Java implementation
Packagetest; Public classSearch { Public Static voidMain (string[] args) {//System.out.println ("Hello world!");Integer []a={4,5,5,2,3,5,2,5,5,5}; Integer Len=a.length; Integer result=search (A,len); SYSTEM.OUT.PRINTLN (result); } Public Staticinteger Search (integer A[],integer len) {if(a==NULL|| Len<=0) { return-1; } Integer k=NULL, j=0; for(Integer i=0;i<len;++i) {if(j==0) {k=A[i]; } if(k==A[i]) { ++J; }Else { --J; } } returnK; }}
Reference from: http://blog.csdn.net/iefswang/article/details/7581613
Thanks to the original author
There is a number in the array that appears more than half the length of the array to find the number