Java Solution With Single Loop And No Extra Space (13ms)


  • 0
    A
    class Solution
    {
        public int[] findErrorNums(int[] nums)
        {
            int fullSum = nums.length * (nums.length + 1) / 2;
            int sum = 0;
            int duplicatedNumber = - 1;
            int abs;
            
            for (int i = 0; i < nums.length; i++)
            {
                abs = Math.abs(nums[i]);
                sum += abs;
    
                if(nums[abs-1] < 0)
                    duplicatedNumber = abs;
                
                nums[abs-1] = -nums[abs-1];
            }
            
            int difference = fullSum - sum;
            int[] result = {duplicatedNumber, duplicatedNumber + difference};
            
            return result;
        }
    }
    

Log in to reply
 

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