[leetcode]645. Set Mismatch

两种方法

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

 

posted @ 2018-01-25 20:21  stAr_1  阅读(165)  评论(0编辑  收藏  举报