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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
题意:在数组中有0-n的整数,但是缺少一个,求缺少的
分类:数组
解法1:我能想到最直观的思路就是等差数列求和,总数=(1+n)*n/2
所以我们求出全齐情况下的和,然后将数组中的所有数都减去
那么剩下的就是缺少的那个数了
解法2:使用异或。因为数组中缺少一个,如果这个数组,和全的数组异或,那么异或得到的结果就是缺少的数。
两个相同的数异或会变成0。而缺少的数,没有和它相同的,所以就只剩下它了。
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/48138477