본문 바로가기

알고리즘62

437. Path Sum III /** * 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: int ans; void f(TreeNode* root, int targetSum, lon.. 2022. 8. 14.
1706. Where Will the Ball Fall class Solution { public: vector findBall(vector& grid) { int n = grid.size(); int m = grid[0].size(); vector ans(m); for (int i = 0; i < m; ++i) ans[i] = i; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { int cur = ans[j]; if (cur == -1) continue; int next = cur + grid[i][cur]; if (next < 0 || m == next || grid[i][next] != grid[i][cur]) { ans[j] = -1; continue; } ans[j] = next; } } r.. 2022. 7. 31.
234. Palindrome Linked List /** * 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 *reverse(ListNode *cur) { ListNode *prev = nullptr; while (cur) { ListNode *next = cur->next; cur->next = prev; prev = cur;.. 2022. 7. 30.
14. Longest Common Prefix class Solution { public: string longestCommonPrefix(vector& strs) { sort(strs.begin(), strs.end()); int n = strs.size(); int m = min(strs[0].size(), strs[n - 1].size()); int len = m; for (int i = 0; i < m; ++i) { if (strs[0][i] == strs[n - 1][i]) continue; len = i; break; } return strs[0].substr(0, len); } }; 2022. 7. 30.