7 ms Java Solution, Beats 100% Java Submission.(No sorting required)


  • 0
    D

    Create an array to track the times a specific number has appeared.

    • First pass, go over nums and populate arr.
    • Second pass, found elements showed up 0 times or twice, those are the ones we are looking for.

    Thanks,
    .

    public class Solution {
        public int[] findErrorNums(int[] nums) {
            int len = nums.length;
            
            int[] arr = new int[len+1];
            
            for(int num: nums){
                arr[num]++;
            }
            
            int[] res = new int[2];
            
            for(int i=1;i<arr.length;i++){
                if(arr[i]==2)
                    res[0] = i;
                else if(arr[i]==0)
                    res[1]=i;
            }
            
            return res;
        }
    }
    

Log in to reply
 

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