题目:
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?
思路:
将0~n和数组中的数字都进行异或,得到的结果即缺失的数字
具体代码如下:
public class Solution {
public int missingNumber(int[] nums) {
int result = 0;
int n = nums.length;
int j = 0;
for(int i: nums){
result = result^i^j;
j++;
}
return result^n;
}
}