Back
Featured image of post FindErrorNum

FindErrorNum

Where is the error?

Leetcode 645 FindErrorNum

645. 错误的集合

第一种方法,用数组模拟哈希表,获取出现次数

public int[] findErrorNums(int[] nums) {
        int n = nums.length;
        int[] res = new int[2];//导致集合丢失了一个数字 并且有一个数字重复。
        int[] tmp = new int[n + 1];

        for (int num : nums){
            //统计次数
            tmp[num]++;
        }

        for (int i = 1; i < tmp.length; i++) {
            if (tmp[i] == 1){
                //有效
                continue;
            }

            if (tmp[i] == 2){
                //duplicated
                res[0] = i;
            }else {
                //lost
                res[1] = i;
            }
        }
        return res;
    }

第二种方法 , 数学

//第一个元素:重复元素 = 当前数组和 - 去重后的数组和
//第二个元素:缺失元素 = 数学1~n求和 - 去重后的数组和
public int[] findErrorNums2(int[] nums){
    return new int[]{Arrays.stream(nums).sum() - Arrays.stream(nums).distinct().sum() ,
            (1 + nums.length) * nums.length / 2 - Arrays.stream(nums).distinct().sum()};
}
Welcome to the world of Minezeratul