Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions merge-intervals/dahyeong-yun.java

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

merge-intervals/dahyeong-yun.java
/**
 * TC : O(n log n)
 *   - 처음에 Arrays.sort() 하는데 O(n log n) 소요. 이하 for loop는 O(n)
 * SC : O(n)
 *   - intervals 배열의 크기 n 만큼 ArrayList 할당하므로 O(n)
 */
class Solution {
    // 정확히 작업 정렬 하는 거랑 비슷한데 그걸 위상정렬이라 하던가.
    // 각 0 번째 인덱스 값으로 정렬되어 있으면
    // 1번째 인덱스 값이 직전 interval[0] <= value <= interval[1] 인 경우에 합쳐진다.
    // 겹치는 값이나 중복 값이 없다는 조건이 없다. 정렬도 보장되어 있지 않다.
    // 하나씩 넣고 구간에 걸치는 경우에 합칠지 버릴지를 결정하면 될 듯 한데, 그걸 어떻게 n^2이 아닌 방식으로 하지
    public int[][] merge(int[][] intervals) {
        List<int[]> answer = new ArrayList<>();
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));

        int currentStart = intervals[0][0];
        int currentEnd = intervals[0][1];

        for (int i = 1; i < intervals.length; i++) {
            int[] pair = intervals[i];

            if (currentEnd >= pair[0]) {
                currentEnd = Math.max(currentEnd, pair[1]);
            } else {
                answer.add(new int[] { currentStart, currentEnd });
                currentStart = pair[0];
                currentEnd = pair[1];
            }
        }
        answer.add(new int[] { currentStart, currentEnd });

        return answer.toArray(new int[0][]);
    }
}
  • 패턴: Greedy, Two Pointers, Sorting
  • 설명: intervals를 시작 값 기준으로 정렬한 뒤, 현재 구간과 다음 구간의 겹침 여부를 순차적으로 확인하며 합치거나 새 구간을 시작하는 방식으로 문제를 해결하므로 Greedy 패턴과 Two Pointers의 연속 비교가 핵심이다. 또한 정렬이 선행되므로 Sorting도 함께 해당한다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(n log n) O(n log n)
Space O(n) O(n)

피드백: 정렬으로 시작해 이후 순회에서 현재 구간과 다음 구간의 교집합 여부를 검사해 합치는 형태로, 전체 시간 복잡도는 O(n log n), 추가 공간은 리스트 저장 등으로 O(n)이다.

개선 제안: 현재 구현이 적절해 보입니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* TC : O(n log n)
* - 처음에 Arrays.sort() 하는데 O(n log n) 소요. 이하 for loop는 O(n)
* SC : O(n)
* - intervals 배열의 크기 n 만큼 ArrayList 할당하므로 O(n)
*/
class Solution {
// 정확히 작업 정렬 하는 거랑 비슷한데 그걸 위상정렬이라 하던가.
// 각 0 번째 인덱스 값으로 정렬되어 있으면
// 1번째 인덱스 값이 직전 interval[0] <= value <= interval[1] 인 경우에 합쳐진다.
// 겹치는 값이나 중복 값이 없다는 조건이 없다. 정렬도 보장되어 있지 않다.
// 하나씩 넣고 구간에 걸치는 경우에 합칠지 버릴지를 결정하면 될 듯 한데, 그걸 어떻게 n^2이 아닌 방식으로 하지
public int[][] merge(int[][] intervals) {
List<int[]> answer = new ArrayList<>();
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));

int currentStart = intervals[0][0];
int currentEnd = intervals[0][1];

for (int i = 1; i < intervals.length; i++) {
int[] pair = intervals[i];

if (currentEnd >= pair[0]) {
currentEnd = Math.max(currentEnd, pair[1]);
} else {
answer.add(new int[] { currentStart, currentEnd });
currentStart = pair[0];
currentEnd = pair[1];
}
}
answer.add(new int[] { currentStart, currentEnd });

return answer.toArray(new int[0][]);
}
}
15 changes: 15 additions & 0 deletions missing-number/dahyeong-yun.java

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

missing-number/dahyeong-yun.java
/**
 * TC : O(n)
 *   - 배열을 한 번 순회하면서 합을 구하기 때문에 n
 * SC : O(1)
 *  - 별도 유의미한 공간 할당이 없음
 */
class Solution {
    public int missingNumber(int[] nums) {
        int n = nums.length;
        int total = n * (n + 1) / 2;
        int sum = 0;
        for(int num : nums) sum+=num;
        return total - sum;
    }
}
  • 패턴: Greedy, Dynamic Programming, Bit Manipulation, Hash Map / Hash Set, Divide and Conquer, Two Pointers, Sliding Window, Fast & Slow Pointers, BFS, DFS, Backtracking, Union Find, Trie, Heap / Priority Queue, Monotonic Stack, Binary Search, Dynamic Programming
  • 설명: 해당 코드는 등차수열 합 공식으로 누락된 숫자를 찾는 문제 해결. 한 번의 순회로 합계를 구하고, 전체 합에서 실제 합을 빼 누락 수를 얻는 방식으로 O(n) 시간, O(1) 공간이다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(n) O(n)
Space O(1) O(1)

피드백: 배열을 한 번 순회하면서 합을 구하고, 수열의 전체 합과 비교해 누락된 값을 얻는다.

개선 제안: 현재 구현이 적절해 보입니다.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 이런 방법도 있네요! 배워갑니다!!

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* TC : O(n)
* - 배열을 한 번 순회하면서 합을 구하기 때문에 n
* SC : O(1)
* - 별도 유의미한 공간 할당이 없음
*/
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int total = n * (n + 1) / 2;
int sum = 0;
for(int num : nums) sum+=num;
return total - sum;
}
}
26 changes: 26 additions & 0 deletions reorder-list/dahyeong-yun.java

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

reorder-list/dahyeong-yun.java
/**
 * TC : O(n)
 *   - 배열을 한 번 순회하면서 합을 구하기 때문에 O(n)
 * SC : O(n)
 *   - ArrayList가 노드 전체의 길이 n만큼 할당되기 때문에 O(n)
 */
class Solution {
    public void reorderList(ListNode head) {
        List<ListNode> nodes = new ArrayList<>();
        for (ListNode cur = head; cur != null; cur = cur.next)
            nodes.add(cur);

        int i = 0;
        int j = nodes.size() - 1;

        while (i < j) {
            nodes.get(i).next = nodes.get(j);
            i++;
            if (i == j) break; 
            nodes.get(j).next = nodes.get(i);
            j--;
        }

        nodes.get(j).next = null;
    }
}
  • 패턴: Two Pointers, Greedy, Hash Map / Hash Set
  • 설명: 리스트를 배열에 저장한 후 양 끝에서 가리키며 순서를 재배치하는 방식으로 두 포인터를 교차시키는 패턴이 드러납니다. 원소 재배치를 위해 양 끝 포인터를 이동시키고, 각 포인터에 따라 연결 고리를 업데이트합니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(n) O(n)
Space O(n) O(n)

피드백: 전체를 한 번 순회하며 노드를 배열에 저장하고 다시 양 끝에서 연결하기 때문에 시간 복잡도는 선형이고, 보조 배열로 O(n) 공간이 필요하다.

개선 제안: 필요 시 추가 공간을 줄이려면 중간에 리스트를 반으로 나눠 역순으로 연결하는 방식 등으로 O(1) 추가 공간 구현을 고려해볼 수 있습니다.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SC O(1) 로 풀리는 풀이도 있으니 참고하세요 ~

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* TC : O(n)
* - 배열을 한 번 순회하면서 합을 구하기 때문에 O(n)
* SC : O(n)
* - ArrayList가 노드 전체의 길이 n만큼 할당되기 때문에 O(n)
*/
class Solution {
public void reorderList(ListNode head) {
List<ListNode> nodes = new ArrayList<>();
for (ListNode cur = head; cur != null; cur = cur.next)
nodes.add(cur);

int i = 0;
int j = nodes.size() - 1;

while (i < j) {
nodes.get(i).next = nodes.get(j);
i++;
if (i == j) break;
nodes.get(j).next = nodes.get(i);
j--;
}

nodes.get(j).next = null;
}
}
Loading