mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-04 11:22:59 +08:00
【268. 丢失的数字】【C++】
This commit is contained in:
@ -132,4 +132,49 @@ public int missingNumber(int[] nums) {
|
||||
<img src="../pictures/qrcode.jpg" width=200 >
|
||||
</p>
|
||||
|
||||
======其他语言代码======
|
||||
======其他语言代码======
|
||||
|
||||
[happy-yuxuan](https://github.com/happy-yuxuan) 提供 三种方法的 C++ 代码:
|
||||
|
||||
```c++
|
||||
// 方法:异或元素和索引
|
||||
int missingNumber(vector<int>& nums) {
|
||||
int n = nums.size();
|
||||
int res = 0;
|
||||
// 先和新补的索引异或一下
|
||||
res ^= n;
|
||||
// 和其他的元素、索引做异或
|
||||
for (int i = 0; i < n; i++)
|
||||
res ^= i ^ nums[i];
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
```c++
|
||||
// 方法:等差数列求和
|
||||
int missingNumber(vector<int>& nums) {
|
||||
int n = nums.size();
|
||||
// 公式:(首项 + 末项) * 项数 / 2
|
||||
int expect = (0 + n) * (n + 1) / 2;
|
||||
int sum = 0;
|
||||
for (int x : nums)
|
||||
sum += x;
|
||||
return expect - sum;
|
||||
}
|
||||
```
|
||||
|
||||
```c++
|
||||
// 方法:防止整型溢出
|
||||
int missingNumber(vector<int>& nums) {
|
||||
int n = nums.size();
|
||||
int res = 0;
|
||||
// 新补的索引
|
||||
res += n - 0;
|
||||
// 剩下索引和元素的差加起来
|
||||
for (int i = 0; i < n; i++)
|
||||
res += i - nums[i];
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user