同类题: LeetCode 287. Find the Duplicate Number(和index+1异或,相比这道题)
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
如果没有linear和constant extra space的限制,这道题并不难,在此限制下的两种解决方法:
//求和
public int missingNumber(int[] nums) {
int n = nums.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
}
return n*(n+1) / 2 - sum;
}
//位运算
public int missingNumber(int[] nums) {
//bit manipulation
int missing = nums.length;
for (int i = 0; i < nums.length; i++) {
missing = missing ^ nums[i] ^ i;
}
return missing;
}