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

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,需要两次遍历找出 一个或两个 众数

 

 

 1 public class Solution 
 2 {
 3     public List<Integer> majorityElement(int[] nums) 
 4     {
 5         ArrayList<Integer> res = new ArrayList<>();
 6         int result1 = 0, result2 = 0, count1 = 0, count2 = 0;
 7         // find out two numbers with most occurrence.
 8         for(int i=0; i<nums.length; i++)
 9         {
10             
11             if(result1 == nums[i])
12                 count1++;
13             else if(result2 == nums[i])
14                 count2++;
15             else if(count1 == 0)
16             {
17                 result1 = nums[i];
18                 count1 = 1;
19             }
20             else if(count2 == 0)
21             {
22                 result2 = nums[i];
23                 count2 = 1;
24             }
25             else
26             {
27                 count1--;
28                 count2--;
29             }
30         }
31         // set counts to 0.
32         count1 = 0;
33         count2 = 0;
34         // count the correct occurrence.
35         for(int i=0; i<nums.length; i++)
36         {
37             if(nums[i] == result1)
38                 count1++;
39             else if(nums[i] == result2)
40                 count2++;
41         }
42         
43         // check 1/3 condition.
44         if(count1 > nums.length / 3)
45             res.add(result1);
46         if(count2 > nums.length / 3)
47             res.add(result2);
48         
49         
50         
51         return res;
52     }
53 }

参考资料:

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

 

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

 

posted @ 2017-09-08 07:10  Jimmy_Cheng  阅读(219)  评论(0编辑  收藏  举报