My solution in O(n) runtime without extra space


  • 1
    L
    public class Solution {
        public List<Integer> findDisappearedNumbers(int[] nums) {
            List<Integer> res = new ArrayList<Integer>();
            for(int i = 0; i<nums.length;i++){
                if(nums[i] != -1){
                    if(nums[i]-1 == i){
                        nums[i]=-1;
                    }else if(nums[nums[i]-1] != -1){
                        int temp = nums[nums[i]-1];
                        nums[nums[i]-1] = -1;
                        nums[i]=temp;
                        i--;
                    }
                }
            }
            for(int i = 0; i<nums.length;i++){
                if(nums[i] != -1){
                    res.add(i+1);
                }
            }
            return res;
        }
    }

Log in to reply
 

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