Java 15ms


  • 0
    K

    class Solution {
    // 4,3,2,7,8,2,3,1
    // 7 3 2 4 8 2 3 1
    // 3 3 2 4 8 2 7 1
    // 2 3 3 4 8 2 7 1
    // 3 2 3 4 8 2 7 1
    // 0 2 3 4 1 2 7 8
    // 1 2 3 4 0 2 7 8
    // 1 2 3 4 0 0 7 8

    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] != i + 1 && nums[i] != 0) {
                if (nums[i] == nums[nums[i] - 1]) {
                    nums[i] = 0;   
                } else {
                    swap(nums, i, nums[i] - 1);    
                }
            }
        }
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1) {
                list.add(i + 1);
            }
        }
        return list;
    }
    
    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.