方法一,求和相减
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int sum = (1+n)*n/2;
int sum2 = 0;
for (int num:nums){
sum2+=num;
}
return sum-sum2;
}
}
方法二,异或
1^1^2^2^3=3
class Solution {
public int missingNumber(int[] nums) {
int len = nums.length;
int res = len;
for (int i = 0; i < len; i++) {
res^=i;
res^=nums[i];
}
return res;
}
}