Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
求0~n哪个数没有出现过。
开个map存一下,扫一遍就知道了。时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int missingNumber(vector<int>& nums) {
vector<bool> vis(nums.size() + 1, false);
for (auto x: nums) {
vis[x] = true;
}
for (int i = 0; i <= nums.size(); ++i) {
if (!vis[i]) return i;
}
}
};
评论区看到一种方法还挺巧的,异或和剩下的那个数就是答案,空间复杂度O(1)
public int missingNumber(int[] nums) {
int xor = 0, i = 0;
for (i = 0; i < nums.length; i++) {
xor = xor ^ i ^ nums[i];
}
return xor ^ i;
}