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

public class Solution {
    public List majorityElement(int[] nums) {
        List result = new ArrayList<>();
        if(nums == null || nums.length == 0) {
            return result;
        }
        int index1 = -1;
        int count1 = 0;
        int index2 = -1;
        int count2 = 0;
        for(int i = 0; i < nums.length; i++) {
            if(index1 != -1 && nums[i] == nums[index1]) {
                count1++;
            }
            else if(index2 != -1 && nums[i] == nums[index2]) {
                count2++;
            }
            else if(count1 == 0) {
                index1 = i;
                count1 = 1;
            }
            else if(count2 == 0) {
                index2 = i;
                count2 =1;
            }
            else {
                count1--;
                count2--;
            }
        }
        count1 = 0;
        count2 = 0;
        for(int num:nums) {
            if(num == nums[index1]) {
                count1++;
            }
            else if (num == nums[index2]){
                count2++;
            }
        }
        if(count1 >nums.length/3) {
            result.add(nums[index1]);
        }
        if(count2 >nums.length/3) {
            result.add(nums[index2]);
        }
        return result;
    }
}


你可能感兴趣的:(leetcode)