Leetcode[268] Missing Number
01 Dec 2015###Task1 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?
###Python
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret = 0
for i, num in enumerate(nums):
ret ^= i
ret ^= num
return ret ^ len(nums)
###Java
public class Solution {
public int missingNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int retval = 0;
for (int i = 0; i < nums.length; i++) {
retval ^= i;
retval ^= nums[i];
}
retval ^= nums.length;
return retval;
}
}
###Points
- Another form of ‘single number’