268. Missing Number
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
tag: array, math, bit manipulation
method 1
因为数组内是连续的0~n,所以立马想到可以先求出0~n的和,减去数组所有数的和,剩下的就是缺失的数
public int missingNumber(int[] nums) {
int n = nums.length + 1;
int sum = n*(n-1)/2;
for (int num:nums) {
sum -= num;
}
return sum;
}
method 2
位操作法:使用此法的关键在于发现了数组位置i及其存储的值nums[i] 之间的关系,因为一个数异或它本身为0,而数组位置0-(n-1),数组存储的值包含0-n,又因为异或具有交换律,所以将数组位置i与nums[i]异或,最后的结果便是确实的数
public int missingNumber4(int[] nums) {
int missing = nums.length;
for (int i = 0; i < nums.length; i++) {
missing ^= i^nums[i];
}
return missing;
}
summary:
- 使用位操作的一种场景,数组位置i与数组值nums[i] 存在间接相等的关系,而一个数异或其本身为0