LeetCode 229. Majority Element II

原题链接在这里:https://leetcode.com/problems/majority-element-ii/

题目:

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

题解:

因为个数超过n/3的值最多有两个, 现在改成维护两个candidate.

最后再扫一遍数组,查看这两个最常出现值的实际出现次数,看看是否大于n/3, 大于的都加入返回res中.

Note: two candidate can't be equal, thus before adding candidate2, need to check if it is equal to candidate1, if yes, then skip.

Time Complexity: O(n). n = nums.length.

Space O(1).

AC Java:

 1 class Solution {
 2     public List<Integer> majorityElement(int[] nums) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         
 8         //最多有两个数字大于n/3
 9         int major1 = 1;
10         int major2 = 2;
11         int count1 = 0;
12         int count2 = 0;
13         for(int i = 0; i<nums.length; i++){
14             if(nums[i] == major1){
15                 count1++;
16             }else if(nums[i] == major2){
17                 count2++;
18             }else if(count1 == 0){
19                 major1 = nums[i];
20                 count1 = 1;
21             }else if(count2 == 0){
22                 major2 = nums[i];
23                 count2 = 1;
24             }else{
25                 count1--;
26                 count2--;
27             }
28         }
29         
30         count1 = 0;
31         count2 = 0;
32         for(int num : nums){
33             if(num == major1){
34                 count1++;
35             }
36             if(num == major2){
37                 count2++;
38             }
39         }
40         
41         if(count1 > nums.length/3){
42             res.add(major1);
43         }
44         if(count2 > nums.length/3){
45             res.add(major2);
46         }
47         return res;
48     }
49 }

类似Majority Element I

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6268085.html