268-missing-number
Question
https://leetcode.com/problems/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:
Input: [3,0,1]
Output: 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Thought Process
- Sort
- Sort the array, if the number is not equal to i, we know this index is the missing number
- Time complexity O(n logn)
- Space complexity O(1)
- Hash Set
- We use hashset to store the number
- Time complexity O(n)
- Space complexity O(n)
- XOR
- We can leverage the fact that XOR of same number twice will 0
- We XOR all the numbers and the index
- The final result is the missing number
- Time complexity O(n)
- Space complexity O(1)
Solution
class Solution {
public int missingNumber(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n; i++) {
if (nums[i] != i) return i;
}
return n;
}
}
class Solution {
public int missingNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int n = nums.length;
for (int i = 0; i < n; i++) {
if (!set.contains(i)) return i;
}
return n;
}
}
class Solution {
public int missingNumber(int[] nums) {
int res = nums.length;
for (int i = 0; i < nums.length; i++) {
res ^= i ^ nums[i];
}
return res;
}
}