問題:假如現在有一個序列,已知其中一個數的此書超過50%,請找出這個數。比如3、3、1、1、3、2、3中,出現次數超過50%的數是3 。
方法1:兩兩比較,分別記錄數字的出現次數,2個for循環就可以解決。時間複雜度O(N^2)。
方法2:排序後,如果這個數出現的次數大於50%的話,排序之後就應該就是位於n/2位置的那個數。
方法3:“尋找多元素問題”,我們很容易的看出來,在一個序列中如果去掉2個不同的元素,那麼原序列中的出現次數超過50%的數,在新的序列中還是超過50%,因此我們只要按照序列依次掃描,先把A[0]賦值給c,增加個計數器,count = 1;然後向右掃描,如果跟c相同,則count++,不同,那麼count --,這個真是我們從上面那個結論裏得出的,一旦count == 0了,把c賦值爲A[i+1],count = 1;,重複該過程,直到結束,這個時候,c就是那個超過50%的數。遍歷一遍,時間複雜度爲O(N)。
package candidate; public class Candidate { // 遞歸實現 public int candidateSort(int[]a, int start, int end) { int c = a[start]; int count = 1; int j; for (j=start;j<end && count>0;j++) { if (c == a[j]) { count++; } else { count--; } } if (j == end) { return c; } else { return candidateSort(a, j+1, end); } } // 循環實現 public int candidateSort(int[] a) { int c = a[0]; int count = 0; for (int i=1; i<a.length;i++) { if (c == a[i]) { count++; } else if (count < 0) { c = a[i]; count = 0; } else { count--; } } return c; }