Leetcode 268. Missing Number

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Missing Number

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
1
2
3
4
5
6
7
8
9
10
11
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
1
2
3
4
5
6
7
8
9
10
11
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;
}
};

Reference

  1. https://leetcode.com/problems/missing-number/description/
如果有收获,可以请我喝杯咖啡!