Java Accepted - A different approach ( in - place )


  • 0
    T
    1. Go through the array
    2. For each val at index i: int val = nums[i]
    3. Go to the index of val, zero it: nums[val] = 0
    4. In the end, the index whose value is not 0 is the result
        public List<Integer> findDisappearedNumbers(int[] nums) {
            if (null == nums || nums.length == 0){
                return new ArrayList<>();
            }
    
            for (int i= 0; i < nums.length; i++){
                int val = nums[i];
                if (val != 0) {
                    while (nums[val - 1] != 0) {
                        int t = nums[val - 1];
                        nums[val - 1] = 0;
                        val = t;
                    }
                }
            }
    
            List<Integer> r = new ArrayList<>();
    
            for (int k = 0; k < nums.length; k++){
                if (nums[k] != 0){
                    r.add(k+1);
                }
            }
            return r;
        }
    
    
    

  • 0
    L

    the complexity is O(n)?


Log in to reply
 

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