Swap to corresponding position [ java O(N) Time O(1) Space]


  • 0
    public class Solution {
        public List<Integer> findDisappearedNumbers(int[] nums) {
            List<Integer> res = new ArrayList<Integer>();
            int index = 0;
            while (index < nums.length) {
                int goingTo = nums[index] - 1;
                if(nums[goingTo] == nums[index]) {
                    index++;
                    continue;
                } else {
                    int temp = nums[index];
                    nums[index] = nums[goingTo];
                    nums[goingTo] = temp;
                }
            }
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != 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.