Skip to content

Commit 32197f2

Browse files
Merge pull request #187 from dev-jonghoonpark/main
[박종훈] 12주차 답안 제출
2 parents b3b9556 + e0cdd7a commit 32197f2

File tree

5 files changed

+310
-0
lines changed

5 files changed

+310
-0
lines changed

jump-game/dev-jonghoonpark.md

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
- 문제: https://leetcode.com/problems/jump-game/
2+
- 풀이: https://algorithm.jonghoonpark.com/2024/07/17/leetcode-55
3+
4+
## dfs로 풀기
5+
6+
```java
7+
class Solution {
8+
boolean canJump = false; // 마지막 위치에 도착 할 수 있으면 true 로 변경
9+
10+
public boolean canJump(int[] nums) {
11+
dfs(nums, 0);
12+
13+
return canJump;
14+
}
15+
16+
private void dfs(int[] nums, int pointer) {
17+
// 위치가 범위를 벗어났을 경우
18+
// 이미 방문한 위치일 경우
19+
// 이미 마지막에 도달 가능하다는 것을 확인했을 경우
20+
if (pointer >= nums.length || nums[pointer] == -1 || canJump) {
21+
return;
22+
}
23+
24+
int maxHeight = nums[pointer];
25+
nums[pointer] = -1;
26+
27+
// 마지막이 아닌데 0 이 나왔을 경우 이동 불가능
28+
if (maxHeight == 0 && pointer != nums.length - 1) {
29+
return;
30+
}
31+
32+
if (pointer == nums.length - 1) {
33+
canJump = true;
34+
} else {
35+
while (maxHeight > 0) {
36+
dfs(nums, pointer + maxHeight);
37+
maxHeight--;
38+
}
39+
}
40+
}
41+
}
42+
```
43+
44+
### TC, SC
45+
46+
시간복잡도는 `O(n^2)`, 공간복잡도는 `O(n)` 이다.
47+
48+
## dp로 풀기
49+
50+
중간에 도달하지 못하는 위치가 있을 경우 false를 반환한다. dp 라고 해도 되려나 애매한 것 같다.
51+
52+
```java
53+
class Solution {
54+
public boolean canJump(int[] nums) {
55+
int[] dp = new int[nums.length];
56+
int lastIndex = nums.length - 1;
57+
dp[0] = 1;
58+
59+
for (int i = 0; i < nums.length; i++) {
60+
if (dp[i] == 0) {
61+
return false;
62+
}
63+
64+
int current = nums[i];
65+
int toIndex = i + current + 1;
66+
if(toIndex > lastIndex) {
67+
toIndex = nums.length;
68+
}
69+
Arrays.fill(dp, i, toIndex, 1);
70+
if (dp[lastIndex] > 0) {
71+
return true;
72+
}
73+
}
74+
75+
return dp[lastIndex] != 0;
76+
}
77+
}
78+
```
79+
80+
### TC, SC
81+
82+
시간복잡도는 `O(n^2)`, 공간복잡도는 `O(n)` 이다.
83+
84+
## greedy 방식으로 풀기
85+
86+
greedy 문제는 항상 어떻게 증명할 수 있는지를 고민을 많이 해봐야 하는 것 같다.
87+
88+
```java
89+
class Solution {
90+
public boolean canJump(int[] nums) {
91+
int maxReach = 0; // 현재까지 도달할 수 있는 가장 먼 인덱스
92+
93+
for (int i = 0; i < nums.length; i++) {
94+
if (i > maxReach) {
95+
return false; // 현재 인덱스에 도달할 수 없는 경우
96+
}
97+
maxReach = Math.max(maxReach, i + nums[i]);
98+
if (maxReach >= nums.length - 1) {
99+
return true; // 마지막 인덱스에 도달하거나 그 이상일 경우
100+
}
101+
}
102+
103+
return false;
104+
}
105+
}
106+
```
107+
108+
### TC, SC
109+
110+
시간복잡도는 `O(n)`, 공간복잡도는 `O(1)` 이다.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
- 문제: https://leetcode.com/problems/longest-common-subsequence/
2+
- 풀이: https://algorithm.jonghoonpark.com/2024/07/17/leetcode-1143
3+
4+
```java
5+
class Solution {
6+
public int longestCommonSubsequence(String text1, String text2) {
7+
int[][] dp = new int[text1.length() + 1][text2.length() + 1];
8+
9+
for (int i = 1; i < dp.length; i++) {
10+
for (int j = 1; j < dp[0].length; j++) {
11+
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
12+
dp[i][j] = dp[i - 1][j - 1] + 1;
13+
} else {
14+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
15+
}
16+
}
17+
}
18+
19+
return dp[text1.length()][text2.length()];
20+
}
21+
}
22+
```
23+
24+
### TC, SC
25+
26+
시간 복잡도는 `O(m * n)` 공간 복잡도는 `O(m * n)` 이다.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
- 문제: https://leetcode.com/problems/longest-increasing-subsequence/
2+
- 풀이: https://algorithm.jonghoonpark.com/2024/02/27/leetcode-300
3+
4+
Beats 62.23%
5+
6+
```java
7+
class Solution {
8+
public int lengthOfLIS(int[] nums) {
9+
int[] dp = new int[nums.length];
10+
Arrays.fill(dp, 1);
11+
12+
int max = 1;
13+
for (int i = 1; i < nums.length; i++) {
14+
for (int j = 0; j < i; j++) {
15+
if (nums[j] < nums[i]) {
16+
dp[i] = Math.max(dp[j] + 1, dp[i]);
17+
}
18+
}
19+
max = Math.max(max, dp[i]);
20+
}
21+
return max;
22+
}
23+
}
24+
```
25+
26+
### TC, SC
27+
28+
시간복잡도는 O(n^2), 공간복잡도는 O(n)이다.
29+
30+
## Follow up 문제
31+
32+
> Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
33+
34+
파이썬 에서는 bisect_left 를 쓰면 된다고 하지만 자바에는 존재하지 않는다. 하지만 방법을 찾아보자.
35+
36+
### dp 를 사용하지 않은 풀이 (Beats 82.20%)
37+
38+
우선은 ArrayList를 이용하여 비슷하게 모방해보았다.
39+
40+
```java
41+
public int lengthOfLIS(int[] nums) {
42+
ArrayList<Integer> subsequence = new ArrayList<>();
43+
subsequence.add(nums[0]);
44+
45+
for (int i = 1; i < nums.length; i++) {
46+
int current = nums[i];
47+
48+
if(current > subsequence.get(subsequence.size() - 1)) {
49+
subsequence.addLast(current);
50+
} else if (current < subsequence.get(0)) {
51+
subsequence.set(0, current);
52+
} else {
53+
for (int j = 1; j < subsequence.size(); j++) {
54+
if(current > subsequence.get(j - 1) && current < subsequence.get(j)) {
55+
subsequence.set(j, current);
56+
}
57+
}
58+
}
59+
}
60+
61+
return subsequence.size();
62+
}
63+
```
64+
65+
#### TC, SC
66+
67+
아직은 여전히 시간복잡도는 O(n^2), 공간복잡도는 O(n)이다.
68+
빅오 표기법 상으로는 동일하나 실제 동작 시간은 감소하였다.
69+
70+
### 진짜 binary search를 도입해보기 (Beats 92.57%)
71+
72+
자바 Collections 에서는 binarySearch 메소드를 제공해준다.
73+
적용해보면 다음과 같다.
74+
75+
```java
76+
public int lengthOfLIS(int[] nums) {
77+
ArrayList<Integer> subsequence = new ArrayList<>();
78+
79+
for (int current : nums) {
80+
// Collections.binarySearch : 목록에 포함된 경우 검색 키의 인덱스, 그렇지 않으면 (-(삽입점) - 1) 을 반환함.
81+
int pos = Collections.binarySearch(subsequence, current);
82+
if (pos < 0) pos = -(pos + 1);
83+
if (pos >= subsequence.size()) {
84+
subsequence.add(current);
85+
} else {
86+
subsequence.set(pos, current);
87+
}
88+
}
89+
90+
return subsequence.size();
91+
}
92+
```
93+
94+
#### Collections.binarySearch
95+
96+
해당 메소드의 리턴값은 다음과 같다.
97+
98+
> 목록에 포함된 경우 검색 키의 인덱스, 그렇지 않으면 (-(삽입점) - 1).
99+
> 삽입 지점은 키가 목록에 삽입되는 지점, 즉 키보다 큰 첫 번째 요소의 인덱스 또는 목록의 모든 요소가 지정된 키보다 작은 경우 list.size()로 정의됩니다.
100+
> 키가 발견되는 경우에만 반환값이 >= 0이 되도록 보장합니다.
101+
102+
#### TC, SC
103+
104+
시간복잡도는 `O(n * logn)`, 공간복잡도는 `O(n)`이다.

maximum-subarray/dev-jonghoonpark.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
- 문제: https://leetcode.com/problems/maximum-subarray/
2+
- 풀이: https://algorithm.jonghoonpark.com/2024/05/07/leetcode-53
3+
4+
```java
5+
class Solution {
6+
public int maxSubArray(int[] nums) {
7+
int maxSum = Integer.MIN_VALUE;
8+
int currentSum = 0;
9+
10+
for (int i = 0; i < nums.length; i++) {
11+
currentSum += nums[i];
12+
maxSum = Math.max(maxSum, currentSum);
13+
currentSum = Math.max(currentSum, 0);
14+
}
15+
16+
return maxSum;
17+
}
18+
}
19+
```
20+
21+
- currentSum이 maxSum보다 클 경우 maxSum을 갱신한다.
22+
- currentSum은 음수일 경우 (0보다 작을 경우) 0으로 초기화 한다.
23+
24+
### TC, SC
25+
26+
시간 복잡도는 O(n), 공간 복잡도는 O(1) 이다.

unique-paths/dev-jonghoonpark.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
- 문제: https://leetcode.com/problems/unique-paths/
2+
- 풀이: https://algorithm.jonghoonpark.com/2024/07/16/leetcode-62
3+
4+
```java
5+
class Solution {
6+
public int uniquePaths(int m, int n) {
7+
int[][] matrix = new int[m][n];
8+
matrix[0][0] = 1;
9+
10+
Deque<Coordinate> deque = new ArrayDeque<>();
11+
deque.addLast(new Coordinate(1, 0));
12+
deque.addLast(new Coordinate(0, 1));
13+
while (!deque.isEmpty()) {
14+
Coordinate coordinate = deque.removeFirst();
15+
if (coordinate.x >= m || coordinate.y >= n || matrix[coordinate.x][coordinate.y] != 0) {
16+
continue;
17+
}
18+
19+
int top = coordinate.y > 0 ? matrix[coordinate.x][coordinate.y - 1] : 0;
20+
int left = coordinate.x > 0 ? matrix[coordinate.x - 1][coordinate.y] : 0;
21+
matrix[coordinate.x][coordinate.y] = top + left;
22+
23+
deque.addLast(new Coordinate(coordinate.x + 1, coordinate.y));
24+
deque.addLast(new Coordinate(coordinate.x, coordinate.y + 1));
25+
}
26+
27+
return matrix[m - 1][n - 1];
28+
}
29+
}
30+
31+
class Coordinate {
32+
int x;
33+
int y;
34+
35+
public Coordinate(int x, int y) {
36+
this.x = x;
37+
this.y = y;
38+
}
39+
}
40+
```
41+
42+
### TC, SC
43+
44+
시간 복잡도는 `O(m * n)` 공간 복잡도는 `O(m * n)` 이다.

0 commit comments

Comments
 (0)