Very Simple - Using Array and Bit

  • 4

    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;
        return new int[]{a,bs.nextClearBit(1)};

  • 0

    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.


Log in to reply

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