find the missing number


Missing Number
第一种,求和,然后减掉。

1
2
3
4
5
6
7
8
9
public int (int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int n = nums.length;
int total = (0 + n) * (n + 1) / 2;
for (int i : nums)
total -= i;
return total;
}

位运算,异或nums[i]和i。

1
2
3
4
5
6
7
8
9
10
public int (int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int ans = 0, n = nums.length;
for (int i = 0; i < n; ++i) {
ans ^= i;
ans ^= nums[i];
}
return ans ^= n;
}