Skip to content

Commit

Permalink
feat: Solve Missing Number by sorting and comparing indices
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
river20s authored Dec 29, 2024
1 parent 1c42189 commit 0914b69
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions missing-number/river20s.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import java.util.Arrays;
class Solution {
/* [ํ’€์ด]
* 1) ๋ฐฐ์—ด nums์„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค.
* 2) ๋ฐฐ์—ด ์š”์†Œ์˜ ์ธ๋ฑ์Šค์™€ ๊ฐ’์„ ๋น„๊ตํ•œ๋‹ค.
* 2-1) ์ธ๋ฑ์Šค์™€ ๊ฐ’์ด ๊ฐ™๋‹ค๋ฉด ํ•ด๋‹น ๊ฐ’์€ ๋ฐฐ์—ด์— ์žˆ๋‹ค.
* 2-2) ์ธ๋ฑ์Šค์™€ ๊ฐ’์ด ๋‹ค๋ฅด๋‹ค๋ฉด, ํ•ด๋‹น ๊ฐ’์€ ๋ฐฐ์—ด์— ์—†๋‹ค.
* 3) ๋‹ค๋ฅธ ๊ฐ’์˜ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
* [T.C]
* ๋‚ด์žฅ๋œ Arrays.sort()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n log n)์ด ๋œ๋‹ค.
* [S.C]
* ์ตœ์•…์˜ ๊ฒฝ์šฐ Arrays.sort()๋Š” ์ถ”๊ฐ€์ ์œผ๋กœ O(n) ๋งŒํผ์˜ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•œ๋‹ค.
*/

public int missingNumber(int[] nums) {
// nums ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
Arrays.sort(nums);
// ์ธ๋ฑ์Šค์™€ ์š”์†Œ ๋น„๊ต
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i) {
return i;
}
}
// ๋ฐฐ์—ด์— ์—†๋Š” ๊ฐ’ ๋ฐ˜ํ™˜
return nums.length
}
}

0 comments on commit 0914b69

Please sign in to comment.