數組A是具有n個元素的數組,x是A中的一個元素,若A中有一半以上的元素與A相同,則稱x是數組A的主元素。例如 ,數組A={1,3,2,3,3,4,3},元素3就是該數組的主元素。
1、移去數組中的兩個不同元素后,如果原來數組中有主元素,那么該主元素依然是新數組的主元素。
2、如果數組2k個元素中有k個元素相同(k<n/2),移去這2k個元素以后,如果原來數組中有主元素,那么該主元素依然是新數組的主元素。
如果新數組只剩下一個元素,該元素可作為主元素的候選者。新數組是若干個相同元素,該元素可作為主元素的候選者。沒有剩下元素時,則原來數組沒有主元素。
count為一個初值為0的計數器,當掃描元素時,如果當前元素和num表示的元素相等,則計數器加1,否則計數器減1.當所有元素掃面以后,如果計數器大於0,說明數組還有若干個與num相等的元素未移除,則num為主元素候選者。
1 public class Demo<T> { 2 3 public T num; 4 public T A[]; 5 6 public Demo(T A[]) { 7 this.A = A; 8 } 9 10 public boolean candidate(int m) { 11 int count = 1; 12 int i = m; 13 int n = A.length; 14 num = A[i]; 15 while (i < n - 1 && count > 0) { 16 if (A[++i].equals(num)) 17 count++; 18 else 19 count--; 20 } 21 if (i == n - 1 && count > 0) 22 return true; 23 else if (i == n - 1 && count == 0) { 24 return false; 25 } else 26 return candidate(i + 1); 27 } 28 29 public boolean majority() { 30 int count = 0; 31 boolean flag = candidate(0); 32 33 if (flag) { 34 for (T a : A) { 35 if (num.equals(a)) 36 count++; 37 } 38 if (count < A.length / 2) 39 return false; 40 } 41 return flag; 42 } 43 44 public T getNum() { 45 return num; 46 } 47 48 public static void main(String[] args) { 49 50 String A[] = {"a", "c", "a", "b", "a" }; 51 Demo<String> d1 = new Demo<>(A); 52 boolean sign = d1.majority(); 53 if (sign) { 54 System.out.println(d1.getNum()); 55 } else 56 System.out.println("主元素不存在"); 57 } 58 }