From cd51fcf2b62b7a242d3d21949254e1a233207d76 Mon Sep 17 00:00:00 2001 From: Victor Wu Date: Wed, 11 Nov 2020 14:02:23 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90268.=20=E4=B8=A2=E5=A4=B1=E7=9A=84?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E3=80=91=E3=80=90C++=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...61\347\232\204\345\205\203\347\264\240.md" | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\266\210\345\244\261\347\232\204\345\205\203\347\264\240.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\266\210\345\244\261\347\232\204\345\205\203\347\264\240.md" index 844b5cb..50556ba 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\266\210\345\244\261\347\232\204\345\205\203\347\264\240.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\266\210\345\244\261\347\232\204\345\205\203\347\264\240.md" @@ -132,4 +132,49 @@ public int missingNumber(int[] nums) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +[happy-yuxuan](https://github.com/happy-yuxuan) 提供 三种方法的 C++ 代码: + +```c++ +// 方法:异或元素和索引 +int missingNumber(vector& 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& 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& nums) { + int n = nums.size(); + int res = 0; + // 新补的索引 + res += n - 0; + // 剩下索引和元素的差加起来 + for (int i = 0; i < n; i++) + res += i - nums[i]; + return res; +} +``` + + -- GitLab