《备战Google》Day1-169.多数元素

1.拿到这道题首先想到暴力方法,但时间是n方,肯定超时了,所以考虑哈希表的方法,这样只需要遍历2n次。

2.algorithm:hashmap,getOrDefault, keySet(), get(), put()。

3.时间复杂度:遍历数组插入哈希表为n,之后进行第二次遍历,还是n,一共是2n,所以是On。

空间复杂度:哈希表最多含有n/2个键值对,占用空间为On,因为一个长度为n的数组最多只包含n个不同的值

class Solution {
    public int majorityElement(int[] nums) {
        int max = Integer.MIN_VALUE;
        int res = 0;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i : nums){
            map.put(i, map.getOrDefault(i,0)+1);
        }
        for(int value : map.values()){
            max = Math.max(value, max);
        }
        for(int i : map.keySet()){
            if(map.get(i) == max){
                res = i;
            }
        }
        return res;
    }
}

  

posted @ 2022-07-06 20:31  曲海鑫  阅读(33)  评论(0)    收藏  举报