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

Thought process:
A follow-up to "169. Majority Element". Again, use the Boyer-Moore majority vote algorithm. There are at most 2 elements that appear more than n / 3 times. Thus, we can use two pairs of variables to achieve constant space complexity.

Solution:

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

Time complexity: O(n).
Space complexity: O(1).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula