Skip to content

Commit 7995015

Browse files
committed
upload 1 answer, Aug 24th
1 parent eafdc4b commit 7995015

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Medium/MissingNumber.java

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
3+
4+
For example,
5+
Given nums = [0, 1, 3] return 2.
6+
7+
Note:
8+
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
9+
*/
10+
11+
// version 1, add up all numbers, O(N) time, O(1) space
12+
public class MissingNumber {
13+
public int missingNumber(int[] nums) {
14+
int sum = 0;
15+
for(int num: nums)
16+
sum += num;
17+
return (nums.length * (nums.length + 1) )/ 2 - sum;
18+
}
19+
}
20+
21+
// version 2, XOR, O(1) space
22+
// n^n = 0 and n^0 = n
23+
public class MissingNumber {
24+
public int missingNumber(int[] nums) {
25+
int result = 0;
26+
for (int i = 1; i <= nums.length; i++) {
27+
result ^= nums[i - 1];
28+
result ^= i;
29+
}
30+
return result;
31+
}
32+
}
33+
34+
/*
35+
Reference:
36+
https://leetcode.com/discuss/53778/java-solution-o-1-space-and-o-n-in-time
37+
https://leetcode.com/discuss/53794/simple-java-solution-with-explanation-time-o-n-space-o-1
38+
https://leetcode.com/discuss/53871/java-simplest-solution-o-1-space
39+
*/

0 commit comments

Comments
 (0)