Missing Number LeetCode solution in Java

1
// Approach 1: Find diff
2

3
class Solution {
4
public int missingNumber(int[] nums) {
5
int n = nums.length;
6
int expectedSum = (n * (n + 1)) / 2;
7
for (int num : nums) expectedSum -= num;
8
return expectedSum;
9
}
10
}
11

12
// Approach 2: XOR
13
class Solution {
14
public int missingNumber(int[] nums) {
15
int xor1 = 0;
16
for (int i = 1; i <= nums.length; i++) xor1 = xor1 ^ i;
17

18
int xor2 = 0;
19
for (int num : nums) xor2 = xor2 ^ num;
20
return xor1 ^ xor2;
21
}
22
}
23

24
// Approach 3: Cyclic sort
25
class Solution {
26
public int missingNumber(int[] nums) {
27

28
int i = 0;
29
while (i < nums.length) {
30

31
if (nums[i] != i && nums[i] < nums.length) swap(i, nums[i], nums);
32
else i += 1;
33
}
34

35
for (int j = 0; j < nums.length; j++) {
36
if (nums[j] != j) return j;
37
}
38
return nums.length;
39
}
40

41
private void swap(int i, int j, int[] nums) {
42
int temp = nums[i];
43
nums[i] = nums[j];
44
nums[j] = temp;
45
}
46
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0