Monday, October 31, 2016

Find All Numbers Disappeared in an Array

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]


Using a bit mask, if the number exists in the array, sets that bit to 1. Then check from 1 to n, if any bit is 0, the number is missing.


public List findDisappearedNumbers(int[] nums) {
        List rst = new ArrayList<>();
        int mask = 0;
        for (int n : nums) {
            mask |= (1 << n);
        }
        for (int i = 1; i <= nums.length; i++) {
            if (((mask >> i) & 1) != 1) {
                rst.add(i);
            }
        }
        return rst;
    }


1 comment:

  1. will you code work if array size > max size a machine can accommodate ( 32 bit, 64 bit , 128 bit )

    ReplyDelete