Majority Element II

本文介绍了一种算法,用于在一个整数数组中找出所有出现次数超过数组长度的1/3的元素,算法运行时间线性,空间复杂度为常数。
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.

这道题目是[url=http://kickcode.iteye.com/blog/2276572]Majority Element[/url]的变形,这里要求找出出现次数多余n/3次。我们通过分析可以知道这样的元素可能有两个,我们同样可以采用Moore算法,与上一题目不同的的是三个元素一组,这样在线性的时间复杂度下可以解决。代码如下:

public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
int result1 = 0;
int result2 = 0;
int count1 = 0, count2 = 0;
for(int i : nums) {
if(count1 == 0 && i != result2) {
result1 = i;
} else if(count2 == 0 && i != result1) {
result2 = i;
}
if(i == result1) {
count1 ++;
} else if(i == result2) {
count2 ++;
} else {
count1 --;
count2 --;
}
}
count1 = 0;
count2 = 0;
for(int i : nums) {
if(i == result1)
count1 ++;
else if(i == result2)
count2 ++;
}
if(count1 > nums.length / 3) list.add(result1);
if(count2 > nums.length / 3) list.add(result2);
return list;
}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值