leetcode 448. 找到所有数组中消失的数字

leetcode 448. 找到所有数组中消失的数字_第1张图片

        用的最土的办法,将数组nums中出现过的数字用map记录下来,再遍历1~n中的所有数字,凡是未在map中出现过的即为我们要找的数字。 Java代码如下:

class Solution {
    public List findDisappearedNumbers(int[] nums) {
        int n = nums.length;
        List ans = new ArrayList<>();
        Map map = new HashMap<>();
        for(int num : nums){
            if(num >= 1 && num <= n){
                map.put(num , map.getOrDefault(num,0)+1);
            }
        }
        for(int i=1; i<=n; i++){
            if(!map.containsKey(i)){
                ans.add(i);
            }
        }
        return ans;
    }
}

 

你可能感兴趣的:(leetcode刷题记录,leetcode,算法,java)