Java/645. Set Mismatch 错误的集合

  • Post author:
  • Post category:java


题目


代码部分一(6ms 100%)

class Solution {
    public int[] findErrorNums(int[] nums) {
        int[] res = new int[2];
        int[] index = new int[nums.length + 1];
        for(int i = 0; i < nums.length; i++){
            index[nums[i]]++;
        }
        for(int i = 1; i < index.length; i++){
            if(res[0] != 0 && res[1] != 0) break;
            if(index[i] > 1) res[0] =  i;
            if(index[i] == 0) res[1] = i;
        }
        
        return res;
    }
}

代码部分二(7ms 99.98%)

class Solution {
    public int[] findErrorNums(int[] nums) {
        int[] res=new int[2];
        for(int i=0;i<nums.length;i++){
            int index=Math.abs(nums[i])-1;
            if(nums[index]<0){
                res[0]=index+1;
            }else{
                nums[index]=-nums[index];
            }
        }
        for(int i=0;i<nums.length;i++){
            if(nums[i]>0){
                res[1]=i+1;
            }
        }
            return res;
    }
}