Missing Number
Description
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1:
Example 2:
Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Solutions
My solution
Idea: if nums[i] > 0
, mark its existence by subtracting n + 1
from nums[nums[i] - 1]
(so it is < 0
). Use a separate variable to mark the existence of 0
.
Optimal solution
Idea: use XOR. Becausea XOR a XOR b == b
.
Last updated