Skip to content
This repository has been archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
53 lines (37 loc) · 1.27 KB

448.md

File metadata and controls

53 lines (37 loc) · 1.27 KB

448. Find All Numbers Disappeared in an Array

Description

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

Thinking Process

  1. Walk through the array, for nums[i], mark nums[nums[i] - 1] as negative. This means, number i exists in the array
  2. Walk through the array again, whenever it sees a positive number, add index (i + 1) to the output

Code

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> res = new LinkedList<>();
        int n = nums.length;
        
        for(int i = 0; i < n; i++){
            nums[Math.abs(nums[i]) - 1] = 
              - Math.abs(nums[Math.abs(nums[i]) - 1]);
        }
        
        for(int i = 1; i <= n; i++){
            if (nums[i - 1] > 0){
                res.add(i);
            }
        }
        
        return res;
    }
}

Complexity

  1. Time is O(n)
  2. Space is O(1) excluding the space needed for output