LeetCode知识点总结 - 645

LeetCode 645. Set Mismatch

考点 难度
Array Easy
题目

You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

思路

用map储存数字和出现的次数。次数等于2则是duplicate,没有储存到map里面的数字是missing。不难,注意细节即可。

答案
public int[] findErrorNums(int[] nums) {
        int n = nums.length;
        Map < Integer, Integer > map = new HashMap();
        for (int i = 0; i < nums.length; i++){
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        int duplicate = -1;
        int missing = -1;
        for (int i = 1; i <= n; i++){
            if (map.containsKey(i)){
                if (map.get(i) == 2){
                    duplicate = i;
                }
            }
            else{
                missing = i;
            }
        }
        return new int[]{duplicate, missing};
    }

猜你喜欢

转载自blog.csdn.net/m0_59773145/article/details/120042162