Skip to content

Commit 0914b69

Browse files
authored
feat: Solve Missing Number by sorting and comparing indices
After sorting the array in ascending order, we compare each index `i` with `nums[i]` to find the missing number. The time complexity is O(n log n) due to the sorting step. We might revisit this problem later to explore a more optimal O(n) solution with constant extra space.
1 parent 1c42189 commit 0914b69

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.Arrays;
2+
class Solution {
3+
/* [ํ’€์ด]
4+
* 1) ๋ฐฐ์—ด nums์„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค.
5+
* 2) ๋ฐฐ์—ด ์š”์†Œ์˜ ์ธ๋ฑ์Šค์™€ ๊ฐ’์„ ๋น„๊ตํ•œ๋‹ค.
6+
* 2-1) ์ธ๋ฑ์Šค์™€ ๊ฐ’์ด ๊ฐ™๋‹ค๋ฉด ํ•ด๋‹น ๊ฐ’์€ ๋ฐฐ์—ด์— ์žˆ๋‹ค.
7+
* 2-2) ์ธ๋ฑ์Šค์™€ ๊ฐ’์ด ๋‹ค๋ฅด๋‹ค๋ฉด, ํ•ด๋‹น ๊ฐ’์€ ๋ฐฐ์—ด์— ์—†๋‹ค.
8+
* 3) ๋‹ค๋ฅธ ๊ฐ’์˜ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
9+
* [T.C]
10+
* ๋‚ด์žฅ๋œ Arrays.sort()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n log n)์ด ๋œ๋‹ค.
11+
* [S.C]
12+
* ์ตœ์•…์˜ ๊ฒฝ์šฐ Arrays.sort()๋Š” ์ถ”๊ฐ€์ ์œผ๋กœ O(n) ๋งŒํผ์˜ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•œ๋‹ค.
13+
*/
14+
15+
public int missingNumber(int[] nums) {
16+
// nums ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
17+
Arrays.sort(nums);
18+
// ์ธ๋ฑ์Šค์™€ ์š”์†Œ ๋น„๊ต
19+
for (int i = 0; i < nums.length; i++) {
20+
if (nums[i] != i) {
21+
return i;
22+
}
23+
}
24+
// ๋ฐฐ์—ด์— ์—†๋Š” ๊ฐ’ ๋ฐ˜ํ™˜
25+
return nums.length
26+
}
27+
}
28+

0 commit comments

Comments
ย (0)