LeetCode-【数组】-求众数 II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zw159357/article/details/82154375

给定一个大小为 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。

示例 1:

输入: [3,2,3]
输出: [3]

示例 2:

输入: [1,1,1,3,3,2,2,2]
输出: [1,2]

题解:题目中的数据有负数出现,这时就不能使用数组来计算某一个数的数量了,所以本题采用map存储每个数的及其对应的数量。

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res=new ArrayList<>();
        int n=nums.length;
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<n;i++){
            if(map.containsKey(nums[i])){
                int t=map.get(nums[i])+1;
                map.put(nums[i],t);
            }else{
                map.put(nums[i],1);
            }
        }
        for(int i=0;i<n;i++){
            if(map.get(nums[i])>n/3){
                res.add(nums[i]);
                map.put(nums[i],-1);
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/zw159357/article/details/82154375
今日推荐