原题链接:268. Missing Number
【思路1-Python】
这种思路是利用两个数异或——相同为1,相异为0的性质。以[0,1,3,4,5]为例,每次循环都是 res ^= nums[i] & i,那么总的开来是如下一个过程,
res = 0 ^ 0 ^ 1 ^ 1 ^ 2 ^ 3 ^ 3 ^ 4 ^ 4 ^ 4 = (0 ^ 0 ) ^ (1 ^ 1) ^ 2 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5) = 2,这样就把缺失的2给“选”出来了:
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in range(len(nums)) :
res ^= nums[i] ^ i
return res ^ len(nums)
121 / 121
test cases passed. Runtime: 72 ms Your runtime beats 21.36% of pythonsubmissions.
【思路2-Java、Python】
思路2有些投机取巧,也当做是一种方法列出来给大家参考吧。例如[0,1,3,4,5],那么n=6,缺失的就是2,假设数组的和为 sum,假设数组的[1,2,3,4,5] sum1,sum1 - sum = 2,这样就可以找到缺失的数了:
public class Solution {
public int missingNumber(int[] nums) {
int sum = 0;
for (int num : nums) sum += num;
return (nums.length + 1) * nums.length / 2 - sum;
}
}
121 / 121 test cases passed. Runtime: 1 ms Your runtime beats 37.49% of javasubmissions.
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(range(len(nums)+1)) - sum(nums)
121 / 121
test cases passed. Runtime: 60 ms Your runtime beats 47.25% of pythonsubmissions.
当然,除了上述两种思路外,还可以先对 nums 进行排序,然后用二分查找找出那个缺失的数。