1. 程式人生 > >645. Set Mismatch - LeetCode

645. Set Mismatch - LeetCode

HR math 分享圖片 break pre lB finder solution com

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; }

645. Set Mismatch - LeetCode