标签:
/* * 229. Majority Element II * 12.7 by Mingyang * 观察可知,数组中至多可能会有2个出现次数超过 ⌊ n/3 ⌋ * 的众数记变量n1, n2为候选众数; c1, c2为它们对应的出现次数遍历数组,记当前数字为num若num与n1或n2相同, * 则将其对应的出现次数加1否则,若c1或c2为0,则将其置为1,对应的候选众数置为num否则, * 将c1与c2分别减1最后,再统计一次候选众数在数组中出现的次数,若满足要求,则返回之。 */ public List<Integer> majorityElement2(int[] nums) { if (nums == null || nums.length == 0) return new ArrayList<Integer>(); List<Integer> result = new ArrayList<Integer>(); int number1 = nums[0], number2 = nums[0], count1 = 0, count2 = 0, len = nums.length; for (int i = 0; i < len; i++) { if (nums[i] == number1) count1++; else if (nums[i] == number2) count2++; else if (count1 == 0) { number1 = nums[i]; count1 = 1; } else if (count2 == 0) { number2 = nums[i]; count2 = 1; } else {
//左边右边同时减减哦!!!!!!!
//这个是我自己做的时候没有料到的!!!!!!!!!!!!!! count1--; count2--; } } count1 = 0; count2 = 0; for (int i = 0; i < len; i++) { if (nums[i] == number1) count1++; else if (nums[i] == number2) count2++; } if (count1 > len / 3) result.add(number1); if (count2 > len / 3) result.add(number2); return result; }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5586377.html