Java O(1) Space, O(n) Time solution.


  • 0
    J
    public class Solution {
        public int[] findErrorNums(int[] nums) {
            int[] res = new int[2];
            if(nums == null || nums.length < 2){
                return res;
            }
            for(int i = 0; i < nums.length; i++){
                int index = Math.abs(nums[i]) - 1;
                if(nums[index] < 0){
                    res[0] = index + 1;
                }
                nums[index] = -nums[index];
            }
            for(int j = 0; j < nums.length; j++){
                if(nums[j] > 0 && j + 1 != res[0]){
                    res[1] = j + 1;
                    break;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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