268. Missing Number
2016-06-28 15:33
155 查看
题目
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中不重复的数字。找出缺失的那个数。
解题思路
思路1:
看到这题就想到了以前小学数学题中求1到n的和的问题,这题只要求出1到n的数的和,然后遍历以便数组,求数组中所有数字的和,然后用1到n的和,减去数组中数字的和,就是缺失的数字了。
思路2:
在讨论区谈到的,被深深的折服了。
a=a^b^b;而数组的数字是从0到n中的n个数,只需要将数字异或0-n中的每个数,并且异或数组中的每个数,最后出了数组中没出现的数,其他数字都被异或了两次,只剩下0-n中没出现的的那个数了。
代码
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中不重复的数字。找出缺失的那个数。
解题思路
思路1:
看到这题就想到了以前小学数学题中求1到n的和的问题,这题只要求出1到n的数的和,然后遍历以便数组,求数组中所有数字的和,然后用1到n的和,减去数组中数字的和,就是缺失的数字了。
思路2:
在讨论区谈到的,被深深的折服了。
a=a^b^b;而数组的数字是从0到n中的n个数,只需要将数字异或0-n中的每个数,并且异或数组中的每个数,最后出了数组中没出现的数,其他数字都被异或了两次,只剩下0-n中没出现的的那个数了。
代码
//思路1 int missingNumber(vector<int>& nums) { int nSum = 0; int nSize=nums.size(); for(int i=0;i<nSize ; ++i) nSum+=nums[i]; return nSize*(nSize+1)/2 -nSum; } //思路2 int missingNumber(vector<int>& nums) { int i=0 ,nResult=0; for( ; i<nums.size() ; ++i) nResult = nResult^i^nums[i]; return nResult^i; }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法