Skip to content

Latest commit

 

History

History
71 lines (62 loc) · 2.07 KB

448. Find All Numbers Disappeared in an Array.md

File metadata and controls

71 lines (62 loc) · 2.07 KB

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]

Solution

  • mine
class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for(int i = 0; i< nums.length; i++){
            //获取数组 每一个元素值表示的位置 
            int index = Math.abs(nums[i]) - 1;
            //判断当前位置是否大于0  小于0说明当前值重复出现
            if(nums[index] > 0){
                nums[index] = -nums[index];
            }
        }
        
        for(int i = 0; i< nums.length; i++){
            //还大于0的值 表示 当前位置没有出现在数组中
            if(nums[i] > 0){
                //值为 位置+1
                res.add(i + 1);
            }    
        }
        return res;
    }
}
  • the most votes

The basic idea is that we iterate through the input array and mark elements as negative using nums[nums[i] -1] = -nums[nums[i]-1]. In this way all the numbers that we have seen will be marked as negative. In the second iteration, if a value is not marked as negative, it implies we have never seen that index before, so just add it to the return list.

public List<Integer> findDisappearedNumbers(int[] nums) {
    List<Integer> ret = new ArrayList<Integer>();

    for(int i = 0; i < nums.length; i++) {
        int val = Math.abs(nums[i]) - 1;
        if(nums[val] > 0) {
            nums[val] = -nums[val];
        }
    }

    for(int i = 0; i < nums.length; i++) {
        if(nums[i] > 0) {
            ret.add(i+1);
        }
    }
    return ret;
}