1. 程式人生 > >[leetcode]645. Set Mismatch

[leetcode]645. Set Mismatch

get code blog etc i+1 兩種方法 urn span find

兩種方法

public int[] findErrorNums(int[] nums) {
        int[] res = new int[2];
        Set<Integer> set = new HashSet<>();
        int sum = 0;
        int l = nums.length;
        int target = 0;
        for (int i = 0; i < nums.length; i++) {
            if (set.contains(nums[i]))
                target 
= i; set.add(nums[i]); sum+=nums[i]; } res[0] = nums[target]; res[1] = (l+1)*l/2-sum+nums[target]; return res; } public int[] findErrorNums2(int[] nums) { int[] res = new int[2]; for (int a : nums) {
if (nums[Math.abs(a)-1] >0) nums[Math.abs(a)-1] *=-1; else { res[0] = Math.abs(a); } } for (int i = 0; i < nums.length; i++) { if (nums[i]>0) { res[1] = i+1; } }
return res; }

[leetcode]645. Set Mismatch