Missing Number
题目
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?
解题思路
a^b^b =a,
which means two xor operations with the same number will eliminate the number and reveal the original number.
普通方法(java-17ms)
public int missingNumber(int[] nums) {
Arrays.sort(nums);
int i;
for(i = 0;i<nums.length;i++){
if(nums[i] != i){
return i;
}
}
return i;
}
异或按位运算(java-1ms)
public int missingNumber(int[] nums) {
int xor = 0, i = 0;
for (i = 0; i < nums.length; i++) {
xor = xor ^ i ^ nums[i];
}
return xor ^ i;
}