645. Set Mismatch - LeetCode

Question

645. Set Mismatch

Solution

思路:

遍历每个数字,然后将其应该出现的位置上的数字变为其相反数,这样如果我们再变为其相反数之前已经成负数了,说明该数字是重复数,将其将入结果res中,然后再遍历原数组,如果某个位置上的数字为正数,说明该位置对应的数字没有出现过,加入res中即可

Java实现:

public int[] findErrorNums(int[] nums) {
    /*
        int a = 0;
        for (int i : nums) {
            if (nums[i-1] < 0) a = nums[i-1] * -1;
            nums[i-1] *= -1;
        }

        int b = 0;
        for (int i : nums) {
            if (nums[i-1] > 0 && nums[i-1] != a) {
                b = nums[i-1];
                break;
            }
        }
        return new int[]{a, b};
        */
    int[] res = new int[2];
    for (int i : nums) {
        if (nums[Math.abs(i) - 1] < 0) res[0] = Math.abs(i);
        else nums[Math.abs(i) - 1] *= -1;
    }
    for (int i=0;i<nums.length;i++) {
        if (nums[i] > 0) res[1] = i+1;
    }
    return res;
}

猜你喜欢

转载自www.cnblogs.com/okokabcd/p/9215859.html
今日推荐