Simple Java o(n) time o(1) space


  • 0
    F
        public int[] findErrorNums(int[] nums) {
            int len = nums.length;
            int sum = len * (len + 1) / 2; 
            int dup = 0;
            for(int i = 0; i < len; i++) {
                int n = Math.abs(nums[i]);
                if(nums[n - 1] < 0) dup = n;
                else {
                    nums[n - 1] = -nums[n - 1];
                    sum -= n;
                }
            }
            return new int[] {dup, sum};
        }
    

Log in to reply
 

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