268. Missing Number
2016-07-20 10:29
411 查看
题目:Missing Number
原题链接:https://leetcode.com/problems/missing-number/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?
给出一个数组含有n个唯一的元素从0,1,2。。。,n,找出丢失的那一个元素,例如数组元素为0,1,3则丢失的元素为3,要求算法必须要是线性时间复杂度,并尽量使用常数级额外的空间。
线性额外空间的算法:
开一个哈希数组,然后统计数组里面的所有元素,最后扫描一遍数组,找出缺少的那一个,代码如下:
class Solution { public: int missingNumber(vector<int>& nums) { int len = nums.size(); int hash[len + 1] = {}; for(int i = 0; i < len; ++i) { hash[nums[i]] = 1; } for(int i = 0; i < len+1; ++i) { if(!hash[i]) return i; } return -1; } };
常数空间复杂度算法:
利用位操作,以及“消除”的思想,定义ans = 0,然后去和数组里面每一个元素异或,然后在和从0到n的数字都分别异或一下,这样最终的结果就是丢失的那一个元素。代码如下:
class Solution { public: int missingNumber(vector<int>& nums) { int ans = 0, i = 0; for(auto num : nums) { ans ^= num; ans ^= i++; } return ans ^ i; //注意不要忘记和n异或一下 } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解