Skip to content

[sungjinwi] Week 12 solution #1602

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 22, 2025
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
37 changes: 37 additions & 0 deletions non-overlapping-intervals/sungjinwi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
풀이 :
종료시간을 오름차순으로 정렬
intervals를 순회하면서 시간이 겹치면 현재의 interval을 삭제 (종료시간이 큰 interval이 삭제되는게 더 최소한으로 삭제할 수 있으므로)
겹치지 않으면 lastEnd를 현재 interval의 end로 업데이트

TC : O (N log N)
sort에 n log n의 시간복잡도

SC : O (1)
*/

#include <vector>
#include <algorithm>
#include <limits.h>

using namespace std;

class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {

sort(intervals.begin(), intervals.end(), [] (vector<int>& a, vector<int>& b){ return a[1] < b[1]; });

int cnt = 0;
int lastEnd = INT_MIN;

for (auto& interval : intervals) {
if (interval[0] < lastEnd)
cnt++;
else
lastEnd = interval[1];
}

return cnt;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
풀이 :
인접리스트 방식으로 그래프를 저장
visited에 방문한 노드 표시
노드를 순회하면서 방문하지 않은 노드이면 dfs를 통해 방문으로 표시함 -> 연결된 모든 노드 방문 처리
component 개수 + 1

이 로직을 노드 전체에 대해 반복

정점 개수 : V 간선 개수 : E

TC : O (V + E)

SC : O (V + E)

*/

#include <vector>
using namespace std;

class Solution {
public:
/**
* @param n: the number of vertices
* @param edges: the edges of undirected graph
* @return: the number of connected components
*/
int countComponents(int n, vector<vector<int>> &edges) {
vector<vector<int>> adjs(n);
vector<bool> visited(n, false);
int result = 0;

for (auto& edge : edges) {
adjs[edge[0]].push_back(edge[1]);
adjs[edge[1]].push_back(edge[0]);
}

for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, adjs, visited);
result++;
}
}
return result;
}

void dfs(int curr, vector<vector<int>>& adjs, vector<bool>& visited) {
if (visited[curr])
return ;
visited[curr] = true;
for (auto& adj : adjs[curr])
dfs(adj, adjs, visited);
}
};
40 changes: 40 additions & 0 deletions remove-nth-node-from-end-of-list/sungjinwi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
풀이 :
list를 vector에 저장한 뒤 끝에서 n - 1 번째 노드->next를 n번째 노드->next로 치환

노드 개수 : N

TC : O (N)

SC : O (N)
*/

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* tmp = head;
vector<ListNode*> list;

while (tmp) {
list.push_back(tmp);
tmp = tmp->next;
}
int idx = list.size() - n;
if (idx == 0)
return head->next;
else {
list[idx - 1]->next = list[idx]->next;
return head;
}
}
};
41 changes: 41 additions & 0 deletions same-tree/sungjinwi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
풀이 :
전위순회로 root 먼저 체크
둘 다 null이면 true, 둘 중 하나만 null이면 false, val이 다르면 false 리턴
left, right 노드에 재귀적으로 함수 호출하고 둘 중 false인 경우 있으면 false
정상적으로 함수 끝에 다르면 true

트리 일치하는 노드 개수 : min (P, Q) = M
M은 P, Q중 하나에 비례

TC : O (M)

SC : O (M)
재귀호출스택 메모리
*/

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p || !q)
return p == q;
if (p->val != q->val)
return false;
if (!isSameTree(p->left, q->left))
return false;
if (!isSameTree(p->right, q->right))
Copy link
Member

Choose a reason for hiding this comment

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

return isSameTree(p->left, q->left) && isSameTree(p->right, q->right)
로 표현하면 좀더 간결하게 직관적일수 있을거같아보여 코멘트 드려요

Copy link
Contributor Author

Choose a reason for hiding this comment

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

감사합니다~

return false;
return true;
}
};
115 changes: 115 additions & 0 deletions serialize-and-deserialize-binary-tree/sungjinwi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
풀이 :
- serialize
- BFS로 트리->val을 큐에 넣으면서 string (ex. [1,2,3,null,null,null,null])으로 합친다
- 노드가 없을 때는 null을 string에 넣어서 어떤 부분이 비어있는지를 표시한다

- deserialize
- string을 split 시켜서 문자열 배열로 만들고
- 원래 트리와 순서를 맞추기위해 serialize와 마찬가지로 BFS를 통해 tree를 재구성
- 문자열이 null이 아니면 해당 val을 가지는 노드를 만들어 연결

노드 개수 : N

serialize
TC : O(N)
전체 노드 순회
SC : O(N)
큐 크기는 노드 개수에 비례

deserialize
TC : O(N)
노드 단위로 다시 쪼개서 전체 노드 순회
SC : O(N)
큐 및 split된 문자열 배열 크기는 노드 개수 비례
*/


/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <string>
#include <queue>
#include <iostream>
#include <sstream>
using namespace std;
class Codec {
public:

// Encodes a tree to a single string.
string serialize(TreeNode* root) {
queue<TreeNode*> q;
ostringstream out;

out << "[";
if (root)
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
if (node == nullptr) {
out << "null";
}
else {
out << node->val;
q.push(node->left);
q.push(node->right);
}
q.pop();
out << ",";
}

string result = out.str();
if (result.back() == ',')
result.pop_back();
result += "]";

return result;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data == "[]")
return nullptr;
string s = data.substr(1, data.size() - 2);
vector<string> tokens;
string token;
stringstream ss(s);

while (getline(ss, token, ','))
tokens.push_back(token);

TreeNode* root = new TreeNode(stoi(tokens[0]));
queue<TreeNode*> q;
q.push(root);

int index = 1;

while (!q.empty() && index < tokens.size()) {
TreeNode* node = q.front();
q.pop();

if (tokens[index] != "null") {
node->left = new TreeNode(stoi(tokens[index]));
q.push(node->left);
}
index++;

if (index < tokens.size() && tokens[index] != "null") {
node->right = new TreeNode(stoi(tokens[index]));
q.push(node->right);
}
index++;
}
return root;
}
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));