229. Majority Element II

題目:html

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.java

連接: http://leetcode.com/problems/majority-element-ii/python

7/24/2017數組

本身不會作,參考別人的app

步驟,由於找more than n/3,因此最多有2個答案。spa

1. 先找到candidate1, candidate2,經過2個count來找,目標是找到出現頻率最高的2個數,或者是最高頻和次高頻出現的第一個數。這裏的count實際上是相對的出現次數。code

2. 從新找到這2個candidate的實際出現次數htm

3. 與n/3來比較,看是否加入到結果中去。blog

Boyer-Morrer Voting Algorithm,看別人的總結:element

假如給定一個數組,要求majority elements,這些elements出現 > 數組的theta (好比theta = 0.3, 0.4,0.5)。方法應該是以下:  Time Complexity - O(n), Space Complexity - O(1 / theta)。

1) 創建一個k個數的map, 好比more than [1/2]則 k = 1, more than [1/3]則 k  = 2, more than [1/4]則 k = 3。

2) 當map.size() > k時,對map中每一個元素進行count--,移除 = 0元素

3) 對map中剩餘元素進行count++

4)最後輸出map中count > theta * n的元素。

 1 public class Solution {
 2     public List<Integer> majorityElement(int[] nums) {
 3         List<Integer> result = new ArrayList<Integer>();
 4         if (nums == null || nums.length == 0) {
 5             return result;
 6         }
 7         int candidate1 = 0, candidate2 = 0, count1 = 0, count2 = 0;
 8         for (int num: nums) {
 9             if (num == candidate1) {
10                 count1++;
11             } else if (num == candidate2) {
12                 count2++;
13             } else if (count1 == 0) {
14                 candidate1 = num;
15                 count1++;
16             } else if (count2 == 0) {
17                 candidate2 = num;
18                 count2++;
19             } else {
20                 count1--;
21                 count2--;
22             }
23         }
24         count1 = 0;
25         count2 = 0;
26         
27         for (int num: nums) {
28             if (num == candidate1) {
29                 count1++;
30             } else if (num == candidate2) {
31                 count2++;
32             }
33         }
34         if (count1 > nums.length / 3) {
35             result.add(candidate1);
36         }
37         if (count2 > nums.length / 3) {
38             result.add(candidate2);
39         }        
40         return result;
41     }
42 }

參考

https://gregable.com/2013/10/majority-vote-algorithm-find-majority.html

http://www.cnblogs.com/yrbbest/p/4997354.html

http://www.cnblogs.com/yrbbest/p/4491637.html

別人的答案

https://discuss.leetcode.com/topic/17564/boyer-moore-majority-vote-algorithm-and-my-elaboration

https://discuss.leetcode.com/topic/32510/java-easy-version-to-understand

更加通常化,python

https://discuss.leetcode.com/topic/17409/6-lines-general-case-o-n-time-and-o-k-space

更多討論

https://discuss.leetcode.com/category/237/majority-element-ii

相關文章
相關標籤/搜索