diff --git a/non-overlapping-intervals/sungjinwi.cpp b/non-overlapping-intervals/sungjinwi.cpp new file mode 100644 index 000000000..975a3a24e --- /dev/null +++ b/non-overlapping-intervals/sungjinwi.cpp @@ -0,0 +1,37 @@ +/* + 풀이 : + 종료시간을 오름차순으로 정렬 + intervals를 순회하면서 시간이 겹치면 현재의 interval을 삭제 (종료시간이 큰 interval이 삭제되는게 더 최소한으로 삭제할 수 있으므로) + 겹치지 않으면 lastEnd를 현재 interval의 end로 업데이트 + + TC : O (N log N) + sort에 n log n의 시간복잡도 + + SC : O (1) +*/ + +#include +#include +#include + +using namespace std; + +class Solution { + public: + int eraseOverlapIntervals(vector>& intervals) { + + sort(intervals.begin(), intervals.end(), [] (vector& a, vector& 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; + } + }; diff --git a/number-of-connected-components-in-an-undirected-graph/sungjinwi.cpp b/number-of-connected-components-in-an-undirected-graph/sungjinwi.cpp new file mode 100644 index 000000000..d8a6c53b1 --- /dev/null +++ b/number-of-connected-components-in-an-undirected-graph/sungjinwi.cpp @@ -0,0 +1,54 @@ +/* + 풀이 : + 인접리스트 방식으로 그래프를 저장 + visited에 방문한 노드 표시 + 노드를 순회하면서 방문하지 않은 노드이면 dfs를 통해 방문으로 표시함 -> 연결된 모든 노드 방문 처리 + component 개수 + 1 + + 이 로직을 노드 전체에 대해 반복 + + 정점 개수 : V 간선 개수 : E + + TC : O (V + E) + + SC : O (V + E) + +*/ + +#include +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> &edges) { + vector> adjs(n); + vector 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>& adjs, vector& visited) { + if (visited[curr]) + return ; + visited[curr] = true; + for (auto& adj : adjs[curr]) + dfs(adj, adjs, visited); + } + }; diff --git a/remove-nth-node-from-end-of-list/sungjinwi.cpp b/remove-nth-node-from-end-of-list/sungjinwi.cpp new file mode 100644 index 000000000..dfb0e3474 --- /dev/null +++ b/remove-nth-node-from-end-of-list/sungjinwi.cpp @@ -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 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; + } + } + }; diff --git a/same-tree/sungjinwi.cpp b/same-tree/sungjinwi.cpp new file mode 100644 index 000000000..c43144de7 --- /dev/null +++ b/same-tree/sungjinwi.cpp @@ -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)) + return false; + return true; + } + }; diff --git a/serialize-and-deserialize-binary-tree/sungjinwi.cpp b/serialize-and-deserialize-binary-tree/sungjinwi.cpp new file mode 100644 index 000000000..2164d01b7 --- /dev/null +++ b/serialize-and-deserialize-binary-tree/sungjinwi.cpp @@ -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 +#include +#include +#include +using namespace std; +class Codec { + public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + queue 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 tokens; + string token; + stringstream ss(s); + + while (getline(ss, token, ',')) + tokens.push_back(token); + + TreeNode* root = new TreeNode(stoi(tokens[0])); + queue 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));