-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMissingNumber.java
More file actions
58 lines (51 loc) · 1.23 KB
/
MissingNumber.java
File metadata and controls
58 lines (51 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.leetcode;
import java.util.HashSet;
import java.util.Set;
/**
* @author: yhl
* @DateTime: 2019/11/26 13:37
* @Description:
*/
public class MissingNumber {
public static void main(String[] args) {
int[] arr = {3,0,1};
MissingNumber missingNumber = new MissingNumber();
System.out.println(missingNumber.missingNumber3(arr));
}
/**
* [3,0,1]
* @param nums
* @return
*/
public int missingNumber(int[] nums) {
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
for (int i = 0; i <= nums.length; i++) {
if (!numSet.contains(i)) {
return i;
}
}
return -1;
}
public int missingNumber2(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return nums.length * (nums.length + 1) / 2 - sum;
}
/**
* XOR 相同的两个数做^运算,为0
* @param nums
* @return
*/
public int missingNumber3(int[] nums) {
int result = nums.length;
for (int i = 0; i < nums.length; i++) {
result ^= i ^ nums[i];
}
return result;
}
}