LeetCode *** 268. Missing Number
2016-04-07 08:28
393 查看
题目:
Given an array containing n distinct numbers taken from
For example,
Given nums =
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
分析:
嗯,这道题是从一堆数字里找到失去的那个,那么可以用到位操作中的异或,先得到0~n所有数字的异或,然后将该结果分别与nums[i]进行异或。这样最后剩下的数字就是丢失的那个。
代码:
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?
分析:
嗯,这道题是从一堆数字里找到失去的那个,那么可以用到位操作中的异或,先得到0~n所有数字的异或,然后将该结果分别与nums[i]进行异或。这样最后剩下的数字就是丢失的那个。
代码:
class Solution { public: int missingNumber(vector<int>& nums) { int res=0,n=nums.size(); for(int i=1;i<=n;++i){ res^=i; } for(int i=0;i<n;++i){ res^=nums[i]; } return res; } };
相关文章推荐
- 三角形问题(3)
- iOS学习资源(一)
- 第六周项目一 分数类的雏形
- c++第三次上机实验项目四
- Caffe学习系列(14):初识数据可视化
- 第五周项目训练4 长方柱类
- hadoop 编译失败 报错 No plugin descriptor found at META-INF
- 三角形问题(4)
- 2.1.8 dovecot的简单配置和使用
- 2.1.7 虚用户配置
- algorithm@ Strongly Connected Component
- 三角形问题(5)
- 在ipython notebook 上测试caffe的一些例子报错ImportError: No module named caffe
- 2.1.6 外域给本域发信
- 使用JavaCV/OpenCV抓取并存储摄像头图像
- 第五周项目训练3 时间类
- 第5周项目3(2)时间类
- 2.1.5 从其他主机使用postfix服务器
- WCF 新手教程二
- Codeforces Round #346 (Div. 2)C. Tanya and Toys