Very Simple - Using Array and Bit

• Using Array Indexing:

``````public int[] findErrorNums(int[] nums) {
int[] arr = new int[nums.length+1];
int a=0,b=arr.length;
for(int i: nums) arr[i]++;

for(int j=1;j<arr.length;j++){
if(arr[j]==2) a=j;
if(arr[j]==0) b=j;
}
return new int[]{a,b};
}
``````

Using Bit:

``````public int[] findErrorNums(int[] nums) {
BitSet bs = new BitSet(nums.length+1);
int a=0;
for(int i:nums){
if(bs.get(i)) a=i;
bs.set(i);
}
return new int[]{a,bs.nextClearBit(1)};
}``````

• Just to help others:

I came up with the same logic as yours, but whenever if found `arr[j]==2` or `arr[j]==0`, I directly pushed them into the return array. This is why my code failed on tests cases like `[2,2]`. It is important to note that you just store the values in temp variables (`a` and `b`) and then construct the return array later.

Thanks.

• int[] arr = new int[nums.length+1];
int a=0,b=arr.length;
for(int i: nums) arr[i]++;

``````  for(int j=1;j<arr.length;j++){
if(arr[j]==2) a=j;
if(arr[j]==0) b=j;
}
return new int[]{a,b};
``````

}

I think this is the best solution, really simple and clever

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.