您的位置:首页 > 其它

Majority Element II——LeetCode

2015-06-30 00:34 387 查看
Given an integer array of size n, find all elements that appear more than
⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.

题目大意:给定一个大小为n的数组,找出Majority元素,满足出现次数大于
⌊ n/3 ⌋
次。

解题思路:大于
⌊ n/3 ⌋
次,那么应该最多有两个Majority元素,之前有道题是找出 大于
⌊ n/2 ⌋
次Majority元素,这道题有点类似,稍微复杂一点,还是利用投票算法,count作为对元素的计数,候选元素等于当前元素则count+1,否则减1,count等于0则更换候选元素。

public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
int can1 = nums[0], can2 = nums[0], cnt1 = 1, cnt2 = 0;
for (int i = 1; i < nums.length; i++) {
int num = nums[i];
if ((cnt1 == 0 && num != can2)) {
can1 = num;
} else if (cnt2 == 0 && num != can1) {
can2 = num;
}
if (num == can1) {
cnt1++;
} else if (num == can2) {
cnt2++;
} else {
cnt1--;
cnt2--;
}
cnt1 = cnt1 < 0 ? 0 : cnt1;
cnt2 = cnt2 < 0 ? 0 : cnt2;
}
cnt1 = 0;
cnt2 = 0;
for (int num : nums) {
if (num == can1) {
cnt1++;
} else if (num == can2) {
cnt2++;
}
}
if (cnt1 > nums.length / 3)
res.add(can1);
if (cnt2 > nums.length / 3)
res.add(can2);
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: