Java O(n) Time O(1) Space


  • 27
    public static int[] findErrorNums(int[] nums) {
        int[] res = new int[2];
        for (int i : nums) {
            if (nums[Math.abs(i) - 1] < 0) res[0] = Math.abs(i);
    	else nums[Math.abs(i) - 1] *= -1;
        }
        for (int i=0;i<nums.length;i++) {
            if (nums[i] > 0) res[1] = i+1;
        }
        return res;
    }
    

  • 9

    Similar Solution. But maybe it's better to restore the input values.

    public class Solution {
        public int[] findErrorNums(int[] nums) {
            int[] res = new int[2]; // duplicate, missing
            //For each number we found, set nums[number-1] to its negative value (<0)
            for(int i=0; i<nums.length; i++) {
                int idx = Math.abs(nums[i])-1; //since index starts from 0, and the set starts from 1
                if(nums[idx]> 0) nums[idx] = -nums[idx];
                else res[0] = idx+1; //have already been found
            }
            // At this point, only nums[missingNumber-1] > 0
            for(int i=0; i<nums.length; i++) {
                if(nums[i] <0) nums[i] = -nums[i]; //restore the original values
                else res[1]=i+1;//since index starts from 0, and the set starts from 1
            }
            return res;
        }
    }
    

  • 0

  • 0
    D

    smart idea! thanks!


  • 1
    S

    Great idea!
    Little modification with only one loop. We can get sum of arithmetic progression by the formula and calculate actual sum.

    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            int correctSum = (nums.size()*(2 + nums.size()-1))/2;
            int actualSum = 0;
            int badNum = 0;        
            for (auto n : nums) {
                nums[abs(n)-1] *= -1;
                if (nums[abs(n)-1] > 0) {
                    badNum = abs(n);
                }
                actualSum += abs(n);
            }
            return {badNum, correctSum - (actualSum - badNum)};
        }
    };
    

Log in to reply
 

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