问题描述:给定一个数组,求数组中出现次数超过1/3的数字
算法描述:一个数组中,出现次数超过1/3的个数最多有俩个,任意删除数组中的三个不相同的数,其中一个为1/3众数,则1/3
众数不变。使用cm记录候选值m的出现次数,若cm为0,则重新选择候选值。
代码如下:
public static void main(String[] args) { int[] array = new int[13]; array[0] = 1; array[1] = 2; array[2] = 2; array[3] = 3; array[4] = 3; array[5] = 3; array[6] = 3; array[7] = 3; array[8] = 2; array[9] = 2; array[10] = 2 ; array[11] = 2; array[12] = 1; weightNumber(array); } public static void weightNumber(int [] array){ int temp1 = 0, temp2 = 0; int count1 = 0, count2= 0; for(int i = 0; i < array.length; i++){ if(count1 == 0){ temp1 = array[i];count1 = 1; }else if (count2 == 0) { temp2 = array[i];count2 = 1; }else if(temp1 == array[i]){ count1 ++; }else if(temp2 == array[i]){ count2 ++; }else { count1 --; count2 --; } } count1 = 0; count2 = 0; for(int i : array){ if(i == temp1){ count1++; }else if(i == temp2){ count2++; } } if(count1 > array.length/3){ System.out.println("当前数组中出现次数超过1/3的数:"+temp1); } if(count2 > array.length/3){ System.out.println("当前数组中出现次数超过1/3的数:"+temp2); } if((count1 < array.length/3) && (count2 < array.length/3)){ System.out.println("当前数字中不存在次数超过1/3的数"); } }