Skip to content

Commit a96e7ee

Browse files
add post '(Leetcode) 268 - Missing Number'
1 parent 4ee3aed commit a96e7ee

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

_posts/2024-05-25-leetcode-268.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 268 - Missing Number
4+
categories: [스터디-알고리즘]
5+
tags: [자바, java, 리트코드, Leetcode, 알고리즘, algorithm, bit, array]
6+
date: 2024-05-25 23:00:00 +0900
7+
toc: true
8+
---
9+
10+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
11+
12+
[https://neetcode.io/practice](https://neetcode.io/practice)
13+
14+
---
15+
16+
[https://leetcode.com/problems/missing-number/description/](https://leetcode.com/problems/missing-number/description/)
17+
18+
Bit Manipulation 문제에 속해있는데 Array 문제로 봐야하지 않나 싶다.
19+
20+
## 내가 작성한 풀이
21+
22+
```java
23+
public int missingNumber(int[] nums) {
24+
int[] counts = new int[nums.length + 1];
25+
26+
for(int num : nums) {
27+
counts[num] = 1;
28+
}
29+
30+
for(int i = 0; i < counts.length; i ++){
31+
if(counts[i] == 0) {
32+
return i;
33+
}
34+
}
35+
36+
return -1;
37+
}
38+
```
39+
40+
### TC, SC
41+
42+
시간 복잡도는 O(n)이고, 공간 복잡도는 O(n)이다.
43+
44+
## 등차수열로 풀기
45+
46+
예전에 1부터 100까지 더해보라고 하면 개발자들은 반복문부터 돌린다는 이야기를 들어본 적이 있다.
47+
당시의 발표자는 '등차수열의 합'에 대한 언급을 하였다.
48+
49+
이 풀이에서는 등차수열의 합을 이용해서 모든 수가 있을 때의 예상 합(max)을 계산한다.
50+
array를 돌면서 sum을 계산한다.
51+
그리고 max와 sum의 차를 구하면 빠진 숫자가 무엇인지를 알 수 있다.
52+
53+
```java
54+
public int missingNumber(int[] arr) {
55+
int sum = 0;
56+
int max = (arr.length * (arr.length + 1)) / 2;
57+
for (int i = 0; i < arr.length; i++) {
58+
sum += arr[i];
59+
}
60+
return max - sum;
61+
}
62+
```
63+
64+
### TC, SC
65+
66+
시간 복잡도는 O(n)이고, 공간 복잡도는 O(1)이다.

_posts/2024-05-25-leetcode-49.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public List<List<String>> groupAnagrams(String[] strs) {
4545
}
4646
```
4747

48-
## TC, SC
48+
### TC, SC
4949

5050
시간 복잡도는 O(n \* m log m)이고, 공간 복잡도는 O(n + m)이다.
5151
여기서 m은 str 배열(strs)의 각 str의 평균이다.

0 commit comments

Comments
 (0)