本文主要是介绍229.求众数Ⅱ,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
class Solution {public List<Integer> majorityElement(int[] nums) {// 创建返回值List<Integer> res = new ArrayList<>();if (nums == null || nums.length == 0) return res;// 初始化两个候选人candidate,和他们的计票int cand1 = nums[0], count1 = 0;int cand2 = nums[0], count2 = 0;// 摩尔投票法,分为两个阶段:配对阶段和计数阶段// 配对阶段for (int num : nums) {// 投票if (cand1 == num) {count1++;continue;}if (cand2 == num) {count2++;continue;}// 第1个候选人配对if (count1 == 0) {cand1 = num;count1++;continue;}// 第2个候选人配对if (count2 == 0) {cand2 = num;count2++;continue;}count1--;count2--;}// 计数阶段// 找到了两个候选人之后,需要确定票数是否满足大于 N/3count1 = 0;count2 = 0;for (int num : nums) {if (cand1 == num) count1++;else if (cand2 == num) count2++;}if (count1 > nums.length / 3) res.add(cand1);if (count2 > nums.length / 3) res.add(cand2);return res;}
}
这篇关于229.求众数Ⅱ的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!