Simple O(n) time and O(1) space solution with swapping.


  • 0
    public class Solution {
        public int[] findErrorNums(int[] nums) {
            int duplicate = -1;
            int missing = -1;
    
            for (int i = 0; i < nums.length; ) {
                if (nums[i] == i + 1) {
                    i++;
                } else if (nums[i] == nums[nums[i] - 1]) {
                    duplicate = nums[i];
                    missing = i + 1;
                    i++;
                } else {
                    swap(nums, i, nums[i] - 1);
                }
            }
            
            return new int[] { duplicate, missing };
        }
        
        private void swap(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

Log in to reply
 

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