博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
<LeetCode OJ> 268. Missing Number
阅读量:7146 次
发布时间:2019-06-29

本文共 1218 字,大约阅读时间需要 4 分钟。

268. Missing Number

Total Accepted: 31740 
Total Submissions: 83547 
Difficulty: Medium

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?

分析:DONE

我真蛋疼。题意理解错了,我还以为是干嘛呢!

后来才明确原来是随机从0到size()选取了n个数,当中仅仅有一个丢失了(显然的)。

别人的算法:数学推出,0到size()的总和减去当前数组和sum

class Solution {public:    int missingNumber(vector
& nums) { int sum = 0; for(int num: nums) sum += num; int n = nums.size(); return (n * (n + 1))/ 2 - sum; }};

这道问题被标注为位运算问题:參考讨论区的位运算解法:

这个异或运算曾经用到过,到这道题还是想不起这种方法,我真是日了狗了!

异或运算xor。

0 ^ a = a ^ 0 =a
a ^ b = b ^ a
a ^ a = 0
0到size()间的全部数一起与数组中的数进行异或运算,
由于同则0,0异或某个未出现的数将存活下来

class Solution {public:    int missingNumber(vector
& nums) { int res = 0; for (int i = 1; i <= nums.size(); i++) res =res ^ i ^ nums[i-1]; return res; }};

注:本博文为原创,兴许可能继续更新本文。

假设转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50457902

原作者博客:http://blog.csdn.net/ebowtang

你可能感兴趣的文章
电商网站架构案例(3)
查看>>
面向对象
查看>>
python3-函数
查看>>
Microsoft SQL Server Management Studio ------------------------------ 附加数据库 对于 服务器...
查看>>
IO(Properties、序列化流、打印流、CommonsIO)
查看>>
MySQL GTID复制
查看>>
【CT】递归语言的性质
查看>>
Android 4.4 根据uri获取路径的方法
查看>>
CodeForces 508C Anya and Ghosts 贪心
查看>>
最棒的10款MySQL GUI工具
查看>>
mysql 数据类型
查看>>
爬取xml数据之R
查看>>
Xdebug及PHPUnit安装Unknown remote channel: pear.symfony.com
查看>>
网络下载文件及存到sd卡--Android学习笔记
查看>>
web制作、开发人员需知的Web缓存知识
查看>>
SQL Server2005创建新数据库时不允许创建新数据库的问题
查看>>
[推荐] - 中文读物
查看>>
五星评分效果 原生js
查看>>
vue-cli 根据不同的环境打包
查看>>
fatal: could not read Username for 'https://github.com': No such file or directo
查看>>