數組中有一個數字出現的次數超過了數組長度的一半,找出這個數
這個算法的時間復雜度是O(n),另外用了兩個輔助變量。
k用於臨時存儲數組中的數據,j用於存儲某個數出現的次數。
開始時k存儲數組中的第一個數,j為0,如果數組出現的數於k相等,則j加1,否則就減1,如果j為0,就把當前數組中的數賦給k
因為指定的數出現的次數大於數組長度的一半,所有j++與j--相抵消之后,最后j的值是大於等於1的,k中存的那個數就是出現最多的那個數。
下面這個算法只適合數組中數組中某個數的出現次數超過數組長度一半的數組,符合題意。
c實現
1 #include<stdio.h> 2 #include<stdlib.h> 3 int Search(int A[],int len) 4 { 5 if(NULL==A || len<=0) 6 { 7 return -1; 8 } 9 10 int k, j=0; 11 for(int i=0;i<len;++i) 12 { 13 if(j==0) 14 { 15 k=A[i]; 16 } 17 if(k==A[i]) 18 { 19 ++j; 20 }else 21 { 22 --j; 23 } 24 } 25 26 return k; 27 } 28 void main(){ 29 int len=10; 30 int a[10]={4,5,5,2,3,5,2,5,5,5}; 31 int result=Search(a,len); 32 printf("%d\n",result); 33 }
java實現
package test; public class Search { public static void main(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 static Integer 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; } } return k; } }
參考自:http://blog.csdn.net/iefswang/article/details/7581613
感謝原作者
