Skip to content

Commit a31c5f6

Browse files
committed
Missing Number
Reduced time complexity reflecting code review from Dale
1 parent 03bcdeb commit a31c5f6

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

missing-number/TonyKim9401.java

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1-
// TC: O(n log n)
1+
// TC: O(n)
2+
// -> add all nums into set
23
// SC: O(n)
4+
// -> set contains all nums' elements
35
class Solution {
46
public int missingNumber(int[] nums) {
5-
Arrays.sort(nums);
6-
int idx = 1;
7-
int n = nums.length;
8-
for (; idx < n; idx++) {
9-
if (nums[idx] - 1 != nums[idx-1]) return nums[idx] - 1;
10-
}
11-
return nums[idx-1] == n ? 0 : n;
7+
Set<Integer> set = new HashSet<>();
8+
for (int num : nums) set.add(num);
9+
10+
int output = 0;
11+
while (set.contains(output)) output += 1;
12+
13+
return output;
1214
}
1315
}

0 commit comments

Comments
 (0)