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.
此题是Majority Element的继续,关于此题可以移步至Majority Element,关于Majority Element的解法挺多的,因为没有明确指明时间复杂度和空间复杂度,所以可以自由发挥,但是这个题就不那么随意了。可以看Majority Element的最好一个解法,基于Boyer-Moore Algorithm。
通过分析此题可以得知,满足这个条件的元素最多为两个,所以,就有个下面的代码:
public List<Integer> majorityElement(int[] nums) {
List<Integer> ret = new ArrayList<Integer>();
if (nums == null || nums.length == 0) return ret;
int num1 = 0, num2 = 0, cnt1 = 0, cnt2 = 0;
for (int i = 0; i < nums.length; i++) {
if (num1 == nums[i]) cnt1++;
else if (num2 == nums[i]) cnt2++;
else if (cnt1 == 0) {
cnt1++;
num1 = nums[i];
} else if (cnt2 == 0) {
cnt2++;
num2 = nums[i];
} else {
cnt1--;
cnt2--;
}
}
cnt1 = 0;
cnt2 = 0;
for (int i = 0; i < nums.length; i++) {
if (num1 == nums[i]) cnt1++;
else if (num2 == nums[i]) cnt2++;
}
if (cnt1 > nums.length/3) ret.add(num1);
if (cnt2 > nums.length/3) ret.add(num2);
return ret;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/my_jobs/article/details/47313321