题目
类型:Array
解题思路
这道题用 map 方法去做很简单,但是题目描述要求要达到线性的时间复杂度,还有常量级的空间复杂度。
这个就变得有点难了,不过有更好的算法可以达到题目的要求——摩尔投票法。
https://leetcode-cn.com/problems/majority-element-ii/solution/liang-fu-dong-hua-yan-shi-mo-er-tou-piao-fa-zui-zh/
看视频会理解的快点
代码
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;}}
