LeetCode刷题229. 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]

思路解析:

你是否还记得LeetCode的第169题Majority Element,本题是169题的拓展题,⌊ n/2⌋ 变成了⌊ n/3 ⌋ ,在时间复杂度(线性时间复杂度)和空间复杂度(O(1))上提出了更高的要求。

在Majority Element中提出了一种摩尔投票算法,本题也可以用摩尔投票算法进行处理,只是稍微有点变化。

有同学不理解为什么代码中只定义了两个num和两个count,因为既然题目中已经说了“more than ⌊ n/3 ⌋ times”,那么就只能有0个,1个或者2个。如果说一个数组为[1,1,1,3,3,3,2,2,2],共有9个元素,1,2,3各有三个,这不是有3个num吗?并不是这样的,仔细一看这个数组,你会发现是找不到任何一个元素使它的个数大于9/3=3个的,它是上面所说的0个的情况。

代码如下:

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
        int num1=0,num2=0;
        int count1=0,count2=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==num1){
                count1++;
            }else if(nums[i]==num2){
                count2++;
            }else if(count1==0){
                num1=nums[i];
                count1=1;
            }else if(count2==0){
                num2=nums[i];
                count2=1;
            }else{
                count1--;
                count2--;
            }
        }
        count1=0;
        count2=0;
        for(int i =0;i<nums.length;i++){
            if(num1==nums[i]){
                count1++;
            }
            else if(num2==nums[i]){
                count2++;
            }
        }
        if(3*count1 > nums.length){
            res.add(num1);
        }
        if(3*count2 > nums.length){
            res.add(num2);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/u014116780/article/details/82958103