# LeetCode算法题-Missing Number（Java实现-四种解法）

### 02 第一种解法

``````public int missingNumber(int[] nums) {
if (nums == null || nums.length < 1) {
return 0;
}
Arrays.sort(nums);
int index;
for (index = 0; index < nums.length; index++) {
if (index != nums[index]) {
return index;
}
}
return index;
}
``````

### 03 第二种解法

``````Sum = n*(A1+An)/2
``````

``````public int missingNumber2(int[] nums) {
if (nums == null || nums.length < 1) {
return 0;
}
int sum = (nums.length*(1+nums.length))/2;
for (int n : nums) {
sum -= n;
}
return sum;
}
``````

### 04 第三种解法

``````missing=4^(0^0)^(1^1)^(2^2)^(4^3)

=3^(0^0)^(1^1)^(2^2)^(4^4)

=3
``````

``````public int missingNumber3(int[] nums) {
if (nums == null || nums.length < 1) {
return 0;
}
int xor = nums.length;
for (int i = 0; i < nums.length; i ++) {
xor = xor ^ nums[i] ^ i;
}
return xor;
}
``````

### 05 第四种解法

``````public int missingNumber4(int[] nums) {
if (nums == null || nums.length < 1) {
return 0;
}
Set set = new HashSet<>();
for (int num : nums) {
}
for (int i=0; i<=nums.length; i++) {
if (!set.contains(i)) {
return i;
}
}
return -1;
}
``````