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?
solution:
1. XOR from 1 to n
2. use that result XOR each element in array, to find different one.
XOR can used to store different information between two things
public int missingNumber(int[] nums) {
int sum = 0;
int len = nums.length;
while(len>0) {
sum = sum^len;
len--;
}
for(int i=0;i<nums.length;i++){
sum = sum^nums[i];
}
return sum;
}

337

被折叠的 条评论
为什么被折叠?



