文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Version 1
class Solution {
public:
int missingNumber(vector<int>& nums) {
int flag[nums.size() + 1] = {0};
for(int i = 0; i < nums.size(); i++) {
flag[nums[i]] = 1;
}
for(int i = 0; i <= nums.size(); i++) {
if(flag[i] == 0) {
return i;
}
}
}
};
- Version 2
class Solution {
public:
int missingNumber(vector<int>& nums) {
int x = 0;
for(int i = 0; i < nums.size(); i++) {
x = x ^ i ^ nums[i];
}
x ^= nums.size();
return x;
}
};
- Version 3
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int result = n * (n + 1) / 2;
for(int i = 0; i < nums.size(); i++) {
result -= nums[i];
}
return result;
}
};