leetcode-645-easy

Set Mismatch

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.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]
Example 2:

Input: nums = [1,1]
Output: [1,2]
Constraints:

2 <= nums.length <= 104
1 <= nums[i] <= 104

思路一:用 set,先找重复的数字,缺少的数字用求和公式计算

    public int[] findErrorNums(int[] nums) {
        Set<Integer> set = new HashSet<>();
        int[] result = new int[2];

        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if (set.contains(nums[i])) {
                result[0] = nums[i];
            }
            set.add(nums[i]);
            sum += nums[i];
        }

        result[1] = (1 + nums.length) * nums.length / 2 - sum + result[0];

        return result;
    }

思路二:用 set 效率有点低,换了数组的方式

    public int[] findErrorNums(int[] nums) {
        int[] count = new int[nums.length];
        int[] result = new int[2];

        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if (count[nums[i] - 1] == 1) {
                result[0] = nums[i];
            }
            count[nums[i] - 1]++;
            sum += nums[i];
        }

        result[1] = (1 + nums.length) * nums.length / 2 - sum + result[0];

        return result;
    }
posted @ 2023-01-13 21:51  iyiluo  阅读(23)  评论(0)    收藏  举报