LeetCode 229. Majority Element II (众数之二)

时间:2023-03-08 16:27:48

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.


题目标签:Array

  题目给了我们一个 nums array, 让我们找出所有 数量超过 n/3 的众数。这一题与 众数之一 的区别在于,众数之一 只要找到一个 众数大于 n/2 的就可以。这一题要找到所有的数量 大于n/3的众数,其实,最多也就会有两个 大于n/3 的众数。因为可能会出现两个众数,而且是要数量 大于n/3 的,所以我们需要遍历两次nums array。

  第一次遍历 需要找出数量出现最多的 两个数字;

  第二次遍历 需要找出准确的出现次数,因为第一次遍历可能会漏掉一些次数;

  最后,要检查次数大于 n/3 的 才算众数。

Java Solution:

Runtime beats 65.76%

完成日期:04/06/2017

关键词:Array

关键点:Moore Voting,需要两次遍历找出 一个或两个 众数

 public class Solution
{
public List<Integer> majorityElement(int[] nums)
{
ArrayList<Integer> res = new ArrayList<>();
int result1 = 0, result2 = 0, count1 = 0, count2 = 0;
// find out two numbers with most occurrence.
for(int i=0; i<nums.length; i++)
{ if(result1 == nums[i])
count1++;
else if(result2 == nums[i])
count2++;
else if(count1 == 0)
{
result1 = nums[i];
count1 = 1;
}
else if(count2 == 0)
{
result2 = nums[i];
count2 = 1;
}
else
{
count1--;
count2--;
}
}
// set counts to 0.
count1 = 0;
count2 = 0;
// count the correct occurrence.
for(int i=0; i<nums.length; i++)
{
if(nums[i] == result1)
count1++;
else if(nums[i] == result2)
count2++;
} // check 1/3 condition.
if(count1 > nums.length / 3)
res.add(result1);
if(count2 > nums.length / 3)
res.add(result2); return res;
}
}

参考资料:

http://www.cnblogs.com/grandyang/p/4606822.html

LeetCode 算法题目列表 - LeetCode Algorithms Questions List