描述
给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。
dalao思路是,如果出现3个不一样的数,就抵消掉。记录两个candidate和每个candidate分别的出现次数。如果遍历到的数和两个candidate都不等,就count都减1。最后可能会剩下两个candidate,再遍历一次整个数组验证一下谁是主元素。
public int majorityNumber(List<Integer> nums) {// write your code hereint candidate1 = 0, candidate2 = 0, count1 = 0, count2 = 0;for (int num : nums) {if (num == candidate1) {++count1;} else if (num == candidate2) {++count2;} else if (count1 == 0) {candidate1 = num;count1 = 1;} else if (count2 == 0) {candidate2 = num;count2 = 1;} else {--count1;--count2;}}count1 = 0;count2 = 0;for (int num : nums) {if (num == candidate1) {++count1;} else if (num == candidate2) {++count2;}}return count1 > count2 ? candidate1 : candidate2;}
summary: 抵消的思想