Skip to content

Commit c91a559

Browse files
authored
Merge pull request #1602 from sungjinwi/main
[sungjinwi] Week 12 solution
2 parents 21d31a9 + 0e215d8 commit c91a559

File tree

5 files changed

+287
-0
lines changed

5 files changed

+287
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
풀이 :
3+
종료시간을 오름차순으로 정렬
4+
intervals를 순회하면서 시간이 겹치면 현재의 interval을 삭제 (종료시간이 큰 interval이 삭제되는게 더 최소한으로 삭제할 수 있으므로)
5+
겹치지 않으면 lastEnd를 현재 interval의 end로 업데이트
6+
7+
TC : O (N log N)
8+
sort에 n log n의 시간복잡도
9+
10+
SC : O (1)
11+
*/
12+
13+
#include <vector>
14+
#include <algorithm>
15+
#include <limits.h>
16+
17+
using namespace std;
18+
19+
class Solution {
20+
public:
21+
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
22+
23+
sort(intervals.begin(), intervals.end(), [] (vector<int>& a, vector<int>& b){ return a[1] < b[1]; });
24+
25+
int cnt = 0;
26+
int lastEnd = INT_MIN;
27+
28+
for (auto& interval : intervals) {
29+
if (interval[0] < lastEnd)
30+
cnt++;
31+
else
32+
lastEnd = interval[1];
33+
}
34+
35+
return cnt;
36+
}
37+
};
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
풀이 :
3+
인접리스트 방식으로 그래프를 저장
4+
visited에 방문한 노드 표시
5+
노드를 순회하면서 방문하지 않은 노드이면 dfs를 통해 방문으로 표시함 -> 연결된 모든 노드 방문 처리
6+
component 개수 + 1
7+
8+
이 로직을 노드 전체에 대해 반복
9+
10+
정점 개수 : V 간선 개수 : E
11+
12+
TC : O (V + E)
13+
14+
SC : O (V + E)
15+
16+
*/
17+
18+
#include <vector>
19+
using namespace std;
20+
21+
class Solution {
22+
public:
23+
/**
24+
* @param n: the number of vertices
25+
* @param edges: the edges of undirected graph
26+
* @return: the number of connected components
27+
*/
28+
int countComponents(int n, vector<vector<int>> &edges) {
29+
vector<vector<int>> adjs(n);
30+
vector<bool> visited(n, false);
31+
int result = 0;
32+
33+
for (auto& edge : edges) {
34+
adjs[edge[0]].push_back(edge[1]);
35+
adjs[edge[1]].push_back(edge[0]);
36+
}
37+
38+
for (int i = 0; i < n; i++) {
39+
if (!visited[i]) {
40+
dfs(i, adjs, visited);
41+
result++;
42+
}
43+
}
44+
return result;
45+
}
46+
47+
void dfs(int curr, vector<vector<int>>& adjs, vector<bool>& visited) {
48+
if (visited[curr])
49+
return ;
50+
visited[curr] = true;
51+
for (auto& adj : adjs[curr])
52+
dfs(adj, adjs, visited);
53+
}
54+
};
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
풀이 :
3+
list를 vector에 저장한 뒤 끝에서 n - 1 번째 노드->next를 n번째 노드->next로 치환
4+
5+
노드 개수 : N
6+
7+
TC : O (N)
8+
9+
SC : O (N)
10+
*/
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* struct ListNode {
15+
* int val;
16+
* ListNode *next;
17+
* ListNode() : val(0), next(nullptr) {}
18+
* ListNode(int x) : val(x), next(nullptr) {}
19+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
20+
* };
21+
*/
22+
class Solution {
23+
public:
24+
ListNode* removeNthFromEnd(ListNode* head, int n) {
25+
ListNode* tmp = head;
26+
vector<ListNode*> list;
27+
28+
while (tmp) {
29+
list.push_back(tmp);
30+
tmp = tmp->next;
31+
}
32+
int idx = list.size() - n;
33+
if (idx == 0)
34+
return head->next;
35+
else {
36+
list[idx - 1]->next = list[idx]->next;
37+
return head;
38+
}
39+
}
40+
};

same-tree/sungjinwi.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
풀이 :
3+
전위순회로 root 먼저 체크
4+
둘 다 null이면 true, 둘 중 하나만 null이면 false, val이 다르면 false 리턴
5+
left, right 노드에 재귀적으로 함수 호출하고 둘 중 false인 경우 있으면 false
6+
정상적으로 함수 끝에 다르면 true
7+
8+
트리 일치하는 노드 개수 : min (P, Q) = M
9+
M은 P, Q중 하나에 비례
10+
11+
TC : O (M)
12+
13+
SC : O (M)
14+
재귀호출스택 메모리
15+
*/
16+
17+
/**
18+
* Definition for a binary tree node.
19+
* struct TreeNode {
20+
* int val;
21+
* TreeNode *left;
22+
* TreeNode *right;
23+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
24+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
25+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
26+
* };
27+
*/
28+
class Solution {
29+
public:
30+
bool isSameTree(TreeNode* p, TreeNode* q) {
31+
if (!p || !q)
32+
return p == q;
33+
if (p->val != q->val)
34+
return false;
35+
if (!isSameTree(p->left, q->left))
36+
return false;
37+
if (!isSameTree(p->right, q->right))
38+
return false;
39+
return true;
40+
}
41+
};
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/*
2+
풀이 :
3+
- serialize
4+
- BFS로 트리->val을 큐에 넣으면서 string (ex. [1,2,3,null,null,null,null])으로 합친다
5+
- 노드가 없을 때는 null을 string에 넣어서 어떤 부분이 비어있는지를 표시한다
6+
7+
- deserialize
8+
- string을 split 시켜서 문자열 배열로 만들고
9+
- 원래 트리와 순서를 맞추기위해 serialize와 마찬가지로 BFS를 통해 tree를 재구성
10+
- 문자열이 null이 아니면 해당 val을 가지는 노드를 만들어 연결
11+
12+
노드 개수 : N
13+
14+
serialize
15+
TC : O(N)
16+
전체 노드 순회
17+
SC : O(N)
18+
큐 크기는 노드 개수에 비례
19+
20+
deserialize
21+
TC : O(N)
22+
노드 단위로 다시 쪼개서 전체 노드 순회
23+
SC : O(N)
24+
큐 및 split된 문자열 배열 크기는 노드 개수 비례
25+
*/
26+
27+
28+
/**
29+
* Definition for a binary tree node.
30+
* struct TreeNode {
31+
* int val;
32+
* TreeNode *left;
33+
* TreeNode *right;
34+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
35+
* };
36+
*/
37+
#include <string>
38+
#include <queue>
39+
#include <iostream>
40+
#include <sstream>
41+
using namespace std;
42+
class Codec {
43+
public:
44+
45+
// Encodes a tree to a single string.
46+
string serialize(TreeNode* root) {
47+
queue<TreeNode*> q;
48+
ostringstream out;
49+
50+
out << "[";
51+
if (root)
52+
q.push(root);
53+
while (!q.empty()) {
54+
TreeNode* node = q.front();
55+
if (node == nullptr) {
56+
out << "null";
57+
}
58+
else {
59+
out << node->val;
60+
q.push(node->left);
61+
q.push(node->right);
62+
}
63+
q.pop();
64+
out << ",";
65+
}
66+
67+
string result = out.str();
68+
if (result.back() == ',')
69+
result.pop_back();
70+
result += "]";
71+
72+
return result;
73+
}
74+
75+
// Decodes your encoded data to tree.
76+
TreeNode* deserialize(string data) {
77+
if (data == "[]")
78+
return nullptr;
79+
string s = data.substr(1, data.size() - 2);
80+
vector<string> tokens;
81+
string token;
82+
stringstream ss(s);
83+
84+
while (getline(ss, token, ','))
85+
tokens.push_back(token);
86+
87+
TreeNode* root = new TreeNode(stoi(tokens[0]));
88+
queue<TreeNode*> q;
89+
q.push(root);
90+
91+
int index = 1;
92+
93+
while (!q.empty() && index < tokens.size()) {
94+
TreeNode* node = q.front();
95+
q.pop();
96+
97+
if (tokens[index] != "null") {
98+
node->left = new TreeNode(stoi(tokens[index]));
99+
q.push(node->left);
100+
}
101+
index++;
102+
103+
if (index < tokens.size() && tokens[index] != "null") {
104+
node->right = new TreeNode(stoi(tokens[index]));
105+
q.push(node->right);
106+
}
107+
index++;
108+
}
109+
return root;
110+
}
111+
};
112+
113+
// Your Codec object will be instantiated and called as such:
114+
// Codec ser, deser;
115+
// TreeNode* ans = deser.deserialize(ser.serialize(root));

0 commit comments

Comments
 (0)