Leetcode之Missing Number 问题
问题描述:
Given an array containing n distinct numbers taken from0, 1, 2, ..., n
, find the one that is missing from the array.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
示例:
For example,
Given nums = [0, 1, 3]
return 2
.
问题来源:Missing Number (详细地址:https://leetcode.com/problems/missing-number/description/)
思路分析:这道题的解法实在太多了,在这介绍三种方法:
解法一:从0~n的整数的和应该是s=(n+1)*n/2,然后我们遍历整个数组求出它们的和sum,最后s-sum不就是最后的结果了吗?
解法二:其实和解法一的意思是一样的,在这我们采用索引减去对应的元素,累加起来就得到我们丢失的数字了,即sum += i - nums[i];
解法三:这种接法还是很有意思的,我们不采用求和,在这采用的是位运算(异或操作),因为a^b^b=a,你会发现对同一个元素两次异或之后居然得到原数了。那我们就把索引和数组中的元素都异或上,最后剩下的肯定是一个索引一个元素,最后的结果我们再来异或一次,把索引异或掉就得到元素值了啊。
代码: