repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
ooooo-youwillsee/leetcode
1865-Finding Pairs With a Certain Sum/cpp_1865/Solution1.h
<gh_stars>10-100 /** * @author ooooo * @date 2021/5/25 22:18 */ #ifndef CPP_1865__SOLUTION1_H_ #define CPP_1865__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class FindSumPairs { public: unordered_map<int, int> m; vector<int> nums1, nums2; FindSumPairs(vector<int> &nums1, vector<int> &nums2) { this->nums1 = nums1; this->nums2 = nums2; for (auto num: nums2) { m[num]++; } sort(this->nums1.begin(), this->nums1.end()); } void add(int index, int val) { m[nums2[index]]--; nums2[index] += val; m[nums2[index]]++; } int count(int tot) { int ans = 0; for (auto num1 : nums1) { if (num1 > tot) break; int t = tot - num1; ans += m[t]; } return ans; } }; #endif //CPP_1865__SOLUTION1_H_
ooooo-youwillsee/leetcode
1332-Remove-Palindromic-Subsequences/cpp_1332/Solution1.h
// // Created by ooooo on 2020/2/4. // #ifndef CPP_1332__SOLUTION1_H_ #define CPP_1332__SOLUTION1_H_ #include <iostream> using namespace std; /** * 做多为两次。 因为n个a本身就是子序列,所以先删除所有的a,再删除所有的b */ class Solution { public: int removePalindromeSub(string s) { for (int left = 0, right = s.size() - 1; left < right; ++left, --right) { if (s[left] != s[right]) return 2; } return s.size() == 0 ? 0 : 1; } }; #endif //CPP_1332__SOLUTION1_H_
ooooo-youwillsee/leetcode
0925-Long-Pressed-Name/cpp_0925/Solution2.h
<reponame>ooooo-youwillsee/leetcode // // Created by ooooo on 2020/1/8. // #ifndef CPP_0925_SOLUTION2_H #define CPP_0925_SOLUTION2_H #include <iostream> #include <vector> using namespace std; /** * 分组 */ class Solution { private: struct Group { char c; int count; Group(char c) { this->c = c; this->count = 1; } bool operator<(const Group &other) { return this->count < other.count; } }; public: vector<Group> group(string s) { vector<Group> res; for (int i = 0; i < s.size(); ++i) { if (i == 0 || s[i] != s[i - 1]) { res.push_back(Group(s[i])); } else { res[res.size() - 1].count += 1; } } return res; } bool isLongPressedName(string name, string typed) { if (name.empty()) return typed.empty(); if (typed.size() < name.size()) return false; vector<Group> nameGroup = group(name); vector<Group> typedGroup = group(typed); if (nameGroup.size() == typedGroup.size()) { for (int i = 0; i < nameGroup.size(); ++i) { if (typedGroup[i] < nameGroup[i]) { return false; } } return true; } return false; } }; #endif //CPP_0925_SOLUTION2_H
ooooo-youwillsee/leetcode
1792-Maximum Average Pass Ratio/cpp_1792/Solution1.h
/** * @author ooooo * @date 2021/3/28 12:13 */ #ifndef CPP_1792__SOLUTION1_H_ #define CPP_1792__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> #include <set> #include <stack> #include <numeric> #include <queue> using namespace std; class Solution { public: double maxAverageRatio(vector<vector<int>> &classes, int extraStudents) { // 按照通过率排序 auto diff = [&](const int i) { double x = (double) classes[i][0], y = (double) classes[i][1]; return (x + 1) / (y + 1) - x / y; }; priority_queue<pair<double, int>> pq; int n = classes.size(); for (int i = 0; i < n; ++i) { pq.emplace(diff(i), i); } while (extraStudents) { int x = pq.top().second; pq.pop(); classes[x][0]++; classes[x][1]++; extraStudents--; pq.emplace(diff(x), x); } double ans = 0; for (int i = 0; i < n; ++i) { ans += (classes[i][0]) * 1.0 / classes[i][1]; } return ans / n; } }; #endif //CPP_1792__SOLUTION1_H_
ooooo-youwillsee/leetcode
1626-Best Team With No Conflicts/cpp_1626/Solution1.h
/** * @author ooooo * @date 2020/11/15 09:03 */ #ifndef CPP_1626__SOLUTION1_H_ #define CPP_1626__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_set> #include <unordered_map> #include <queue> #include <stack> #include <numeric> using namespace std; /** * dp[i] 表示有第i个球员的最大得分 */ class Solution { public: int bestTeamScore(vector<int> &scores, vector<int> &ages) { int n = scores.size(); vector<pair<int, int >> p; for (int i = 0; i < n; ++i) { p.push_back(make_pair(ages[i], scores[i])); } sort(p.begin(), p.end()); vector<int> dp(n); dp[0] = p[0].second; int ans = dp[0]; for (int i = 1; i < p.size(); ++i) { int age = p[i].first, score = p[i].second; dp[i] = score; // 尝试每一个人和i组成球队 for (int j = 0; j < i; ++j) { int prev_age = p[j].first, prev_score = p[j].second; if (!(prev_age < age && prev_score > score)) { // 无矛盾的,可以组队 dp[i] = max(dp[j] + score, dp[i]); } } ans = max(ans, dp[i]); } return ans; } }; #endif //CPP_1626__SOLUTION1_H_
ooooo-youwillsee/leetcode
0117-Populating-Next-Right-Pointers-in-Each-Node-II/cpp_0117/Solution2.h
/** * @author ooooo * @date 2020/9/28 09:27 */ #ifndef CPP_0117__SOLUTION2_H_ #define CPP_0117__SOLUTION2_H_ #include "Node.h" /** * recursion */ class Solution { public: Node *getNextNode(Node *p_node) { while (p_node) { if (p_node->left) return p_node->left; if (p_node->right) return p_node->right; p_node = p_node->next; } return nullptr; } Node *connect(Node *root) { if (!root) return root; if (root->left) { if (root->right) { root->left->next = root->right; } else { root->left->next = getNextNode(root->next); } } if (root->right) { root->right->next = getNextNode(root->next); } connect(root->right); connect(root->left); return root; } }; #endif //CPP_0117__SOLUTION2_H_
ooooo-youwillsee/leetcode
1237-Find-Positive-Integer-Solution-for-a-Given-Equation/cpp_1237/Solution1.h
// // Created by ooooo on 2020/1/22. // #ifndef CPP_1237__SOLUTION1_H_ #define CPP_1237__SOLUTION1_H_ #include "CustomFunction.h" /** * 暴力破解 */ class Solution { public: vector<vector<int>> findSolution(CustomFunction &customfunction, int z) { vector<vector<int>> ans; for (int x = 1; x <= 1000; ++x) { for (int y = 1; y <= 1000; ++y) { if (customfunction.f(x, y) == z) { ans.push_back({x, y}); } } } return ans; } }; #endif //CPP_1237__SOLUTION1_H_
ooooo-youwillsee/leetcode
0278-First-Bad-Version/cpp_0278/Solution1.h
<reponame>ooooo-youwillsee/leetcode<filename>0278-First-Bad-Version/cpp_0278/Solution1.h<gh_stars>10-100 // // Created by ooooo on 2020/1/17. // #ifndef CPP_0278__SOLUTION1_H_ #define CPP_0278__SOLUTION1_H_ #include <iostream> using namespace std; bool isBadVersion(int version) { return version >= 4; } class Solution { public: int firstBadVersion(int n) { int left = 1, right = n; while (left <= right) { int mid = left + ((right - left) / 2); if (isBadVersion(mid)) { if (mid == 1 || (!isBadVersion(mid - 1) && mid > 0)) return mid; right = mid - 1; } else { left = mid + 1; } } return -1; } }; #endif //CPP_0278__SOLUTION1_H_
ooooo-youwillsee/leetcode
0925-Long-Pressed-Name/cpp_0925/Solution1.h
// // Created by ooooo on 2020/1/8. // #ifndef CPP_0925_SOLUTION1_H #define CPP_0925_SOLUTION1_H #include <iostream> using namespace std; class Solution { public: bool isLongPressedName(string name, string typed) { if (name.empty()) return typed.empty(); if (typed.size() < name.size()) return false; int i = 0, j = 0; if (name[i++] != typed[j++]) return false; while (i < name.size() && j < typed.size()) { if (name[i] == typed[j]) { i++; j++; } else { if (typed[j] == typed[j - 1]) { j++; continue; } return false; } } // name没有遍历完 if (i != name.size()) return false; // typed没有遍历完,检查后面元素是否一致 if (j != typed.size()) { for (int k = j; k < typed.size(); ++k) { if (typed[k] != typed[k - 1]) return false; } } return true; } }; #endif //CPP_0925_SOLUTION1_H
ooooo-youwillsee/leetcode
lcof_039/cpp_039/Solution3.h
<filename>lcof_039/cpp_039/Solution3.h<gh_stars>10-100 // // Created by ooooo on 2020/3/24. // #ifndef CPP_039__SOLUTION3_H_ #define CPP_039__SOLUTION3_H_ #include <iostream> #include <vector> using namespace std; /** * */ class Solution { public: int majorityElement(vector<int> &nums) { int num = nums[0]; int count = 1; for (int i = 1, len = nums.size(); i < len; ++i) { if (count == 0) { num = nums[i]; count = 1; } else if (nums[i] == num) { count += 1; } else { count--; } } return num; } }; #endif //CPP_039__SOLUTION3_H_
ooooo-youwillsee/leetcode
0637-Average-of-Levels-in-Binary-Tree/cpp_0637/Solution3.h
/** * @author ooooo * @date 2020/9/12 10:44 */ #ifndef CPP_0637__SOLUTION3_H_ #define CPP_0637__SOLUTION3_H_ #include "TreeNode.h" class Solution3 { public: vector<double> averageOfLevels(TreeNode *root) { vector<double> ans; if (!root) return ans; queue<TreeNode *> q; q.push(root); while (!q.empty()) { double sum = 0, len = q.size(); for (int i = 0; i < len; ++i) { auto node = q.front(); sum += node->val; q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } ans.push_back(sum / len); } return ans; } }; #endif //CPP_0637__SOLUTION3_H_
ooooo-youwillsee/leetcode
0804-Unique-Morse-Code-Words/cpp_0804/Solution1.h
// // Created by ooooo on 2019/12/14. // #ifndef CPP_0804_SOLUTION1_H #define CPP_0804_SOLUTION1_H #include <iostream> #include <vector> #include <unordered_set> using namespace std; class Solution { public: int uniqueMorseRepresentations(vector<string> &words) { string arr[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; unordered_set<string> set; for (const auto &word : words) { string s; for (const auto &c : word) { s += arr[c - 'a']; } set.insert(s); } return set.size(); } }; #endif //CPP_0804_SOLUTION1_H
ooooo-youwillsee/leetcode
0416-Partition-Equal-Subset-Sum/cpp_0416/Solution1.h
<gh_stars>10-100 // // Created by ooooo on 2020/2/29. // #ifndef CPP_0416__SOLUTION1_H_ #define CPP_0416__SOLUTION1_H_ #include <iostream> #include <vector> #include <numeric> using namespace std; /** * dfs timeout */ class Solution { public: bool dfs(int i, int left_remains, int right_remains) { if (left_remains == 0 || right_remains == 0) return true; if (left_remains < 0 || right_remains < 0) return false; return dfs(i + 1, left_remains - nums[i], right_remains) || dfs(i + 1, left_remains, right_remains - nums[i]); } vector<int> nums; bool canPartition(vector<int> &nums) { this->nums = nums; int sum = accumulate(nums.begin(), nums.end(), 0); if (sum % 2 == 1) return false; sort(nums.begin(), nums.end(), greater<int>()); return dfs(0, sum / 2, sum / 2); } }; #endif //CPP_0416__SOLUTION1_H_
ooooo-youwillsee/leetcode
0701-Insert-into-a-Binary-Search-Tree/cpp_0701/Solution1.h
/** * @author ooooo * @date 2020/9/30 09:17 */ #ifndef CPP_0701__SOLUTION1_H_ #define CPP_0701__SOLUTION1_H_ #include "TreeNode.h" class Solution { public: TreeNode *insertIntoBST(TreeNode *root, int val) { if (!root) return new TreeNode(val); if (root->val < val) { root->right = insertIntoBST(root->right, val); } else if (root->val > val) { root->left = insertIntoBST(root->left, val); } return root; } }; #endif //CPP_0701__SOLUTION1_H_
ooooo-youwillsee/leetcode
0148-Sort-List/cpp_0148/ListNode.h
// // Created by ooooo on 2020/2/18. // #ifndef CPP_0148__LISTNODE_H_ #define CPP_0148__LISTNODE_H_ #include <iostream> #include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(vector<int> nums) : val(nums[0]), next(NULL) { ListNode *cur = this; for (int i = 1; i < nums.size(); ++i) { cur->next = new ListNode(nums[i]); cur = cur->next; } } }; #endif //CPP_0148__LISTNODE_H_
ooooo-youwillsee/leetcode
0234-Palindrome-Linked-List/cpp_0234/ListNode.h
<gh_stars>10-100 // // Created by ooooo on 2020/1/8. // #ifndef CPP_0234_LISTNODE_H #define CPP_0234_LISTNODE_H #include <iostream> #include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(vector<int> vec) { if (vec.empty()) return; this->val = vec[0]; this->next = nullptr; ListNode *head = this; for (int i = 1; i < vec.size(); ++i) { head->next = new ListNode(vec[i]); head = head->next; } } }; #endif //CPP_0234_LISTNODE_H
ooooo-youwillsee/leetcode
0474-Ones and Zeroes/cpp_0474/Solution1.h
/** * @author ooooo * @date 2021/6/6 10:23 */ #ifndef CPP_0474__SOLUTION1_H_ #define CPP_0474__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: int findMaxForm(vector<string> &strs, int m, int n) { int k = strs.size(); int dp[k + 1][m + 1][n + 1]; memset(dp, 0, sizeof(dp)); for (int i = 0; i < k; i++) { int cnt0 = 0, cnt1 = 0; for (auto c: strs[i]) { if (c == '0') cnt0++; else cnt1++; } for (int j = 0; j <= m; j++) { for (int p = 0; p <= n; p++) { dp[i + 1][j][p] = dp[i][j][p]; if (j >= cnt0 && p >= cnt1) { dp[i + 1][j][p] = max(dp[i + 1][j][p], 1 + dp[i][j - cnt0][p - cnt1]); } } } } return dp[k][m][n]; } }; #endif //CPP_0474__SOLUTION1_H_
ooooo-youwillsee/leetcode
1814-Count Nice Pairs in an Array/cpp_1814/Solution1.h
<reponame>ooooo-youwillsee/leetcode /** * @author ooooo * @date 2021/4/11 15:48 */ #ifndef CPP_1814__SOLUTION1_H_ #define CPP_1814__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution1 { long long rev(long long num) { long long sum = 0; while (num) { sum = sum * 10 + num % 10; num /= 10; } return sum; } int countNicePairs(vector<int> &nums) { unordered_map<long long, long long> m; for (auto num : nums) { m[rev(num) - num]++; } long long ans = 0; int mod = 1e9 + 7; for (auto &e: m) { if (e.second >= 2) { ans = (ans + e.second * (e.second - 1) / 2) % mod; } } return ans; } }; #endif //CPP_1814__SOLUTION1_H_
ooooo-youwillsee/leetcode
0541-Reverse-String-II/cpp_0541/Solution1.h
<filename>0541-Reverse-String-II/cpp_0541/Solution1.h // // Created by ooooo on 2020/1/26. // #ifndef CPP_0541__SOLUTION1_H_ #define CPP_0541__SOLUTION1_H_ #include <iostream> using namespace std; class Solution { public: string reverseStr(string s, int k) { bool flag = true; int i = 0; // -k => 预留k个空间。 for (; k <= s.size() && i < s.size() - k; i += k) { if (flag) { reverse(s.begin() + i, s.begin() + i + k); } flag = !flag; } // 最后一个区间,是否需要变换 if (flag) { reverse(s.begin() + i, s.end()); } return s; } }; #endif //CPP_0541__SOLUTION1_H_
ooooo-youwillsee/leetcode
0101-Symmetric-Tree/cpp_0101/Solution1.h
<filename>0101-Symmetric-Tree/cpp_0101/Solution1.h // // Created by ooooo on 2019/12/6. // #ifndef CPP_0101_SOLUTION1_H #define CPP_0101_SOLUTION1_H #include "TreeNode.h" #include <vector> class Solution { private: bool dfs(TreeNode *node1, TreeNode *node2) { if (!node1 && !node2) return true; if (!node1 || !node2) return false; return node1->val == node2->val && dfs(node1->left, node2->right) && dfs(node1->right, node2->left); } public: bool isSymmetric(TreeNode *root) { if (!root) return true; return dfs(root->left, root->right); } }; #endif //CPP_0101_SOLUTION1_H
ooooo-youwillsee/leetcode
0189-Rotate-Array/cpp_0189/Solution3.h
// // Created by ooooo on 2019/12/5. // #ifndef CPP_0189_SOLUTION3_H #define CPP_0189_SOLUTION3_H #include <iostream> #include <vector> using namespace std; class Solution { private: void reverse(vector<int> &nums, int start, int end) { if (nums.size() == 0) return; while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } public: void rotate(vector<int> &nums, int k) { if (nums.size() == 0) return; k %= nums.size(); reverse(nums, 0, nums.size() - 1); reverse(nums, 0, k - 1); reverse(nums, k, nums.size() - 1); } }; #endif //CPP_0189_SOLUTION3_H
ooooo-youwillsee/leetcode
1046-Last-Stone-Weight/cpp_1046/Solution1.h
// // Created by ooooo on 2019/12/30. // #ifndef CPP_1046_SOLUTION1_H #define CPP_1046_SOLUTION1_H #include <iostream> #include <vector> #include <functional> #include <queue> using namespace std; class Solution { public: int lastStoneWeight(vector<int> &stones) { priority_queue<int> pq(less<int>(), stones); while (pq.size() > 1) { int x = pq.top(); pq.pop(); int y = pq.top(); pq.pop(); if (x != y) { pq.push(x - y); } } return pq.empty() ? 0 : pq.top(); } }; #endif //CPP_1046_SOLUTION1_H
ooooo-youwillsee/leetcode
0637-Average-of-Levels-in-Binary-Tree/cpp_0637/Solution2.h
<reponame>ooooo-youwillsee/leetcode<filename>0637-Average-of-Levels-in-Binary-Tree/cpp_0637/Solution2.h // // Created by ooooo on 2020/1/3. // #ifndef CPP_0637_SOLUTION2_H #define CPP_0637_SOLUTION2_H #include "TreeNode.h" #include <vector> class Solution { public: /** * * @param node * @param level * @param sums 每一层的和 * @param counts 每一层的个数 */ void dfs(TreeNode *node, int level, vector<double> &sums, vector<int> &counts) { if (!node) return; if (sums.size() < level) { sums.push_back(0); counts.push_back(0); } sums[level - 1] += node->val; counts[level - 1] += 1; dfs(node->left, level + 1, sums, counts); dfs(node->right, level + 1, sums, counts); } vector<double> averageOfLevels(TreeNode *root) { vector<double> sums; vector<int> counts; dfs(root, 1, sums, counts); for (int i = 0; i < sums.size(); ++i) { sums[i] = sums[i] / counts[i]; } return sums; } }; #endif //CPP_0637_SOLUTION2_H
ooooo-youwillsee/leetcode
0617-Merge-Two-Binary-Trees/cpp_0617/Solution2.h
<gh_stars>10-100 /** * @author ooooo * @date 2020/9/23 10:12 */ #ifndef CPP_0617__SOLUTION2_H_ #define CPP_0617__SOLUTION2_H_ #include "TreeNode.h" class Solution { public: TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) { if (!t1) return t2; if (!t2) return t1; t1->val += t2->val; t1->left = mergeTrees(t1->left, t2->left); t1->right = mergeTrees(t1->right, t2->right); return t1; } }; #endif //CPP_0617__SOLUTION2_H_
ooooo-youwillsee/leetcode
0102-Binary-Tree-Level-Order-Traversal/cpp_0102/Solution2.h
// // Created by ooooo on 2019/11/4. // #ifndef CPP_0102_SOLUTION2_H #define CPP_0102_SOLUTION2_H #include <iostream> #include "TreeNode.h" #include <queue> #include <vector> using namespace std; class Solution { private: vector<vector<int>> res; void dfs(int level, TreeNode *node) { if (!node) return; if (res.size() < level) res.push_back({}); res[level - 1].push_back(node->val); dfs(level + 1, node->left); dfs(level + 1, node->right); } public: vector<vector<int>> levelOrder(TreeNode *root) { if (!root) { return res; } dfs(1, root); return res; } }; #endif //CPP_0102_SOLUTION2_H
ooooo-youwillsee/leetcode
0039-Combination-Sum/cpp_0039/Solution2.h
/** * @author ooooo * @date 2020/9/9 22:25 */ #ifndef CPP_0039__SOLUTION2_H_ #define CPP_0039__SOLUTION2_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int>> ans; vector<int> candidates; void dfs(vector<int> &vec, int i, int sum) { if (sum < 0) return; if (sum == 0) { ans.push_back(vec); return; } while (i < candidates.size()) { if (sum < candidates[i]) return; vec.push_back(candidates[i]); dfs(vec, i, sum - candidates[i]); vec.pop_back(); i++; } } vector<vector<int>> combinationSum(vector<int> &candidates, int target) { vector<int> vec; sort(candidates.begin(), candidates.end()); this->candidates = candidates; dfs(vec, 0, target); return ans; } }; #endif //CPP_0039__SOLUTION2_H_
ooooo-youwillsee/leetcode
1030-Matrix-Cells-in-Distance-Order/cpp_1030/Solution1.h
/** * @author ooooo * @date 2020/11/17 17:35 */ #ifndef CPP_1030__SOLUTION1_H_ #define CPP_1030__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; /** * sort */ class Solution { public: vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) { vector<vector<int>> ans; for (int r = 0; r < R; ++r) { for (int c = 0; c < C; ++c) { ans.push_back({r, c}); } } sort(ans.begin(), ans.end(), [&](vector<int> x, vector<int> y) { int p1 = abs(x[0] - r0) + abs(x[1] - c0); int p2 = abs(y[0] - r0) + abs(y[1] - c0); return p1 < p2; }); return ans; } }; #endif //CPP_1030__SOLUTION1_H_
ooooo-youwillsee/leetcode
0606-Construct-String-from-Binary-Tree/cpp_0606/Solution1.h
<reponame>ooooo-youwillsee/leetcode // // Created by ooooo on 2020/1/3. // #ifndef CPP_0606_SOLUTION1_H #define CPP_0606_SOLUTION1_H #include "TreeNode.h" /** * 字符串拼接有点低效, 后序遍历 */ class Solution { public: string tree2str(TreeNode *t) { if (!t) return ""; string leftStr = tree2str(t->left); string rightStr = tree2str(t->right); if (leftStr == "" && rightStr == "") return to_string(t->val); if (rightStr == "") return to_string(t->val) + "(" + leftStr + ")"; return to_string(t->val) + "(" + leftStr + ")" + "(" + rightStr + ")"; } }; #endif //CPP_0606_SOLUTION1_H
ooooo-youwillsee/leetcode
0893-Groups-of-Special-Equivalent-Strings/cpp_0893/Solution1.h
<reponame>ooooo-youwillsee/leetcode // // Created by ooooo on 2020/2/1. // #ifndef CPP_0893__SOLUTION1_H_ #define CPP_0893__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_set> using namespace std; /** * */ class Solution { public: int numSpecialEquivGroups(vector<string> &A) { unordered_set<string> set; for (auto &s:A) { string odd = "", even = ""; for (int i = 0; i < s.size(); ++i) { if (i % 2 == 0) even.push_back(s[i]); else odd.push_back(s[i]); } sort(odd.begin(), odd.end()); sort(even.begin(), even.end()); set.insert(odd + even); } return set.size(); } }; #endif //CPP_0893__SOLUTION1_H_
ooooo-youwillsee/leetcode
0941-Valid-Mountain-Array/cpp_0941/Solution1.h
<reponame>ooooo-youwillsee/leetcode<gh_stars>10-100 /** * @author ooooo * @date 2020/9/30 16:54 */ #ifndef CPP_0941__SOLUTION1_H_ #define CPP_0941__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: bool validMountainArray(vector<int> &A) { if (A.size() < 3) return false; bool incr = false, decr = false; for (int i = 1; i < A.size(); ++i) { if (A[i] == A[i - 1]) return false; if (A[i] > A[i - 1]) { if (decr) return false; incr = true; } else { if (!incr) return false; decr = true; } } return incr && decr; } }; #endif //CPP_0941__SOLUTION1_H_
ooooo-youwillsee/leetcode
lcof_037/cpp_037/Solution1.h
// // Created by ooooo on 2020/3/23. // #ifndef CPP_037__SOLUTION1_H_ #define CPP_037__SOLUTION1_H_ #include "TreeNode.h" #include <queue> #include <sstream> class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode *root) { if (!root) return "[]"; stringstream ss; ss << "["; queue<TreeNode *> q; q.push(root); while (!q.empty()) { // 判断一层元素是否全为 null int c = 0, len = q.size(); stringstream level_ss; for (int i = 0; i < len; ++i) { auto node = q.front(); q.pop(); if (!node) { c++; level_ss << "null,"; } else { level_ss << node->val << ","; q.push(node->left); q.push(node->right); } } if (c != len) ss << level_ss.str(); } auto ans = ss.str(); ans[ans.size() - 1] = ']'; return ans; } // Decodes your encoded data to tree. TreeNode *deserialize(string data) { auto nums = splitData(data); if (nums.empty()) return nullptr; auto root = new TreeNode(stoi(nums[0])); queue<TreeNode *> q; q.push(root); for (int i = 1, len = nums.size(); i < len; i += 2) { auto node = q.front(); q.pop(); if (nums[i] != "null") node->left = new TreeNode(stoi(nums[i])); if (i + 1 >= len) break; if (nums[i + 1] != "null") node->right = new TreeNode(stoi(nums[i + 1])); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } return root; } vector<string> splitData(string &data) { if (data == "[]") return {}; vector<string> ans; int i = 1; auto pos = data.find(",", i); while (pos != -1) { ans.emplace_back(data.substr(i, pos - i)); i = pos + 1; pos = data.find(",", i); } ans.emplace_back(data.substr(i, data.size() - 1 - i)); return ans; } }; #endif //CPP_037__SOLUTION1_H_
ooooo-youwillsee/leetcode
0480-Sliding Window Median/cpp_0480/Solution1.h
<filename>0480-Sliding Window Median/cpp_0480/Solution1.h /** * @author ooooo * @date 2021/3/30 17:06 */ #ifndef CPP_0480__SOLUTION1_H_ #define CPP_0480__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_map> #include <queue> class Solution { public: class Median { public: int minSize = 0, maxSize = 0; priority_queue<int> left; priority_queue<int, vector<int>, greater<int>> right; unordered_map<int,int> deleteMap; double getMedian() { if (minSize == maxSize) { return ((long long) left.top() + (long long)right.top()) /2.0; } return left.top() * 1.0; } void insert(int x) { if (left.empty() || x <= left.top()) { left.push(x); minSize++; }else { right.push(x); maxSize ++; } rebalance(); } void rebalance() { if (maxSize > minSize) { int x = right.top(); right.pop(); maxSize--; minSize++; left.push(x); prune(right); }else if (minSize -1 > maxSize) { int x = left.top(); left.pop(); minSize--; maxSize++; right.push(x); prune(left); } } template<class T> void prune(T &pq) { while(!pq.empty()) { int x = pq.top(); if (deleteMap[x]) { deleteMap[x]--; pq.pop(); }else { break; } } } void erese(int x) { deleteMap[x] ++; if (x <= left.top()) { minSize--; prune(left); }else { maxSize--; prune(right); } rebalance(); } }; vector<double> medianSlidingWindow(vector<int>& nums, int k) { vector<double> ans; Median m; int n = nums.size(); for(int i = 0; i < k; i++) { m.insert(nums[i]); } ans.push_back(m.getMedian()); for(int i = k ; i < n; i++) { m.erese(nums[i-k]); m.insert(nums[i]); ans.push_back(m.getMedian()); } return ans; } }; #endif //CPP_0480__SOLUTION1_H_
ooooo-youwillsee/leetcode
0268-Missing-Number/cpp_0268/Solution2.h
// // Created by ooooo on 2020/1/6. // #ifndef CPP_0268_SOLUTION2_H #define CPP_0268_SOLUTION2_H #include <iostream> #include <vector> using namespace std; class Solution { public: int missingNumber(vector<int> &nums) { int sum = 0; for (int i = 0, len = nums.size(); i < len; ++i) { sum += (i - nums[i]); } return sum + nums.size(); } }; #endif //CPP_0268_SOLUTION2_H
ooooo-youwillsee/leetcode
1203-Sort Items by Groups Respecting Dependencies/cpp_1203/Solution1.h
/** * @author ooooo * @date 2021/1/12 13:17 */ #ifndef CPP_1203__SOLUTION1_H_ #define CPP_1203__SOLUTION1_H_ #include <iostream> #include <vector> #include <queue> #include <unordered_map> #include <unordered_set> using namespace std; class Solution { public: vector<int> sortItems(int n, int m, vector<int> &groups, vector<vector<int>> &beforeItems) { // 对没有分组的项目,自己分组 int curGroup = m; for (int i = 0; i < groups.size(); ++i) { if (groups[i] == -1) { groups[i] = curGroup; curGroup++; } } m = curGroup; vector<int> groupDegree(m), itemDegree(n); unordered_map<int, vector<int>> groupAdj, itemAdj; for (int i = 0; i < n; ++i) { for (auto &beforeItem: beforeItems[i]) { itemDegree[i]++; itemAdj[beforeItem].push_back(i); int beforeGroup = groups[beforeItem]; int currentGroup = groups[i]; if (beforeGroup != currentGroup) { groupAdj[beforeGroup].push_back(currentGroup); groupDegree[currentGroup]++; } } } vector<int> itemList = topologicalSort(itemDegree, itemAdj, n); if (itemList.empty()) { return {}; } vector<int> groupList = topologicalSort(groupDegree, groupAdj, m); if (groupList.empty()) { return {}; } unordered_map<int, vector<int>> groupMap; for (int i = 0; i < itemList.size(); ++i) { auto curItem = itemList[i]; groupMap[groups[curItem]].push_back(curItem); } vector<int> ans; for (auto group: groupList) { ans.insert(ans.end(), groupMap[group].begin(), groupMap[group].end()); } return ans; } vector<int> topologicalSort(vector<int> &degree, unordered_map<int, vector<int>> &adj, int n) { queue<int> q; vector<int> ans; for (int i = 0; i < n; ++i) { if (degree[i] == 0) { q.push(i); } } while (!q.empty()) { auto item = q.front(); ans.push_back(item); q.pop(); for (auto otherItem: adj[item]) { degree[otherItem]--; if (degree[otherItem] == 0) { q.push(otherItem); } } } // 存在环就返回空 if (ans.size() != n) { return {}; } return ans; } }; #endif //CPP_1203__SOLUTION1_H_
ooooo-youwillsee/leetcode
1579-Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/cpp_1579/Solution1.h
/** * @author ooooo * @date 2020/9/26 00:41 */ #ifndef CPP_1579__SOLUTION1_H_ #define CPP_1579__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: // union find ( path zipå) int find(vector<int> &p, int i) { int t = i; while (i != p[i]) { i = p[i]; } while (t != p[t]) { int tmp = p[t]; p[t] = i; t = tmp; } return i; } bool merge(vector<int> &p, int u, int v) { int pu = find(p, u); int pv = find(p, v); if (pu == pv) return true; p[pu] = pv; return false; } int maxNumEdgesToRemove(int n, vector<vector<int>> &edges) { int del = 0, cnt1 = n, cnt2 = n; vector<int> p1(n + 1), p2; for (int i = 0; i < n + 1; ++i) { p1[i] = i; } for (int i = 0; i < edges.size(); ++i) { int type = edges[i][0], u = edges[i][1], v = edges[i][2]; if (type == 3) { if (merge(p1, u, v)) { del++; } else { cnt1--; } } } // 赋相同值 p2 = p1; cnt2 = cnt1; for (int i = 0; i < edges.size(); ++i) { int type = edges[i][0], u = edges[i][1], v = edges[i][2]; if (type == 1) { if (merge(p1, u, v)) { del++; } else { cnt1--; } } else if (type == 2) { if (merge(p2, u, v)) { del++; } else { cnt2--; } } } if (cnt1 != 1 || cnt2 != 1) return -1; return del; } }; #endif //CPP_1579__SOLUTION1_H_
ooooo-youwillsee/leetcode
lcof_032-2/cpp_032-2/Solution1.h
// // Created by ooooo on 2020/3/20. // #ifndef CPP_032_2__SOLUTION1_H_ #define CPP_032_2__SOLUTION1_H_ #include "TreeNode.h" #include <queue> /** * level order */ class Solution { public: vector<vector<int>> levelOrder(TreeNode *root) { if(!root) return {}; vector<vector<int>> ans; queue<TreeNode *> q; q.push(root); while (!q.empty()) { vector<int> level; for (int i = 0,len = q.size(); i < len; ++i) { auto node = q.front(); q.pop(); level.emplace_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } ans.emplace_back(level); } return ans; } }; #endif //CPP_032_2__SOLUTION1_H_
ooooo-youwillsee/leetcode
lcof_019/cpp_019/Solution1.h
<filename>lcof_019/cpp_019/Solution1.h // // Created by ooooo on 2020/3/14. // #ifndef CPP_019__SOLUTION1_H_ #define CPP_019__SOLUTION1_H_ #include <iostream> #include <vector> #include <iostream> #include <vector> using namespace std; class Solution { public: bool dfs(int i, int j) { if (i >= s.size() && j >= p.size()) return true; if (i < s.size() && j == p.size()) return false; // 后面的字符要么存在 '*',要么不存在 if (j + 1 < p.size() && p[j + 1] == '*') { if (p[j] == s[i] || (p[j] == '.' && i < s.size())) { return dfs(i, j + 2) || dfs(i + 1, j) || dfs(i + 1, j + 2); } else { // 直接忽略 '*' return dfs(i, j + 2); } } if (p[j] == s[i] || (p[j] == '.' && i < s.size())) { return dfs(i + 1, j + 1); } return false; } string s, p; bool isMatch(string s, string p) { if (s.empty() && p.empty()) return true; this->s = s; this->p = p; return dfs(0, 0); } }; #endif //CPP_019__SOLUTION1_H_
ooooo-youwillsee/leetcode
0659-Split Array into Consecutive Subsequences/cpp_0659/Solution1.h
/** * @author ooooo * @date 2020/12/4 20:18 */ #ifndef CPP_0659__SOLUTION1_H_ #define CPP_0659__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: bool isPossible1(vector<int> &nums) { vector<pair<int, int>> groups; groups.push_back({nums[0], nums[0]}); vector<int> indexes; indexes.push_back(nums[0]); int n = nums.size(); for (int i = 1; i < n; ++i) { int num = nums[i]; bool added = false; auto it = upper_bound(indexes.begin(), indexes.end(), num - 1); int j = it - indexes.begin() - 1; if (j >= 0 && indexes[j] + 1 == num) { indexes[j] = num; groups[j].second = num; added = true; } if (!added) { groups.push_back({num, num}); indexes.push_back(num); } } for (auto &group: groups) { if (group.second - group.first + 1 < 3) return false; } return true; } bool isPossible(vector<int> &nums) { vector<pair<int, int>> groups; groups.push_back({nums[0], nums[0]}); vector<int> indexes; indexes.push_back(nums[0]); int n = nums.size(); for (int i = 1; i < n; ++i) { int num = nums[i]; bool added = false; auto it = upper_bound(groups.begin(), groups.end(), make_pair(num - 1, num - 1), [](pair<int, int> v1, pair<int, int> v2) { return v1.second < v2.second; }); int j = it - groups.begin() - 1; if (j >= 0 && indexes[j] + 1 == num) { indexes[j] = num; groups[j].second = num; added = true; } if (!added) { groups.push_back({num, num}); indexes.push_back(num); } } for (auto &group: groups) { if (group.second - group.first + 1 < 3) return false; } return true; } }; #endif //CPP_0659__SOLUTION1_H_
ooooo-youwillsee/leetcode
1670-Design Front Middle Back Queue/cpp_1670/Solution1.h
<reponame>ooooo-youwillsee/leetcode /** * @author ooooo * @date 2021/1/24 17:55 */ #ifndef CPP_1670__SOLUTION1_H_ #define CPP_1670__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> #include <queue> #include <stack> using namespace std; // https://leetcode-cn.com/contest/biweekly-contest-40/problems/design-front-middle-back-queue/ class FrontMiddleBackQueue { public: deque<int> nums; stack<int> help_stack; FrontMiddleBackQueue() { } void pushFront(int val) { nums.push_front(val); } void pushMiddle(int val) { int count = nums.size() / 2; while (count > 0) { help_stack.push(nums.front()); nums.pop_front(); count--; } nums.push_front(val); while (!help_stack.empty()) { nums.push_front(help_stack.top()); help_stack.pop(); } } void pushBack(int val) { nums.push_back(val); } int popFront() { if (nums.empty()) return -1; int ret = nums.front(); nums.pop_front(); return ret; } int popMiddle() { if (nums.empty()) return -1; int count = (nums.size() - 1) / 2; while (count > 0) { help_stack.push(nums.front()); nums.pop_front(); count--; } int ret = nums.front(); nums.pop_front(); while (!help_stack.empty()) { nums.push_front(help_stack.top()); help_stack.pop(); } return ret; } int popBack() { if (nums.empty()) return -1; int ret = nums.back(); nums.pop_back(); return ret; } }; #endif //CPP_1670__SOLUTION1_H_
ooooo-youwillsee/leetcode
0435-Non-overlapping Intervals/cpp_0435/Solution1.h
/** * @author ooooo * @date 2020/12/31 15:00 */ #ifndef CPP_0435__SOLUTION1_H_ #define CPP_0435__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: int eraseOverlapIntervals(vector<vector<int>> &intervals) { if (intervals.size() <= 1) return 0; sort(intervals.begin(), intervals.end(), [](const auto &x, const auto &y) { return x[1] < y[1]; }); int n = intervals.size(); int ans = 1; int right = intervals[0][1]; for (int i = 1; i < n; ++i) { if (intervals[i][0] >= right) { ans++; right = intervals[i][1]; } } return n - ans; } }; #endif //CPP_0435__SOLUTION1_H_
ooooo-youwillsee/leetcode
0121-Best-Time-to-Buy-and-Sell-Stock/cpp_0121/Solution1.h
// // Created by ooooo on 2020/2/4. // #ifndef CPP_0121__SOLUTION1_H_ #define CPP_0121__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; /** * 找到最小值 */ class Solution { public: int maxProfit(vector<int> &prices) { int ans = 0, min_price = INT_MAX; for (auto price: prices) { if (price < min_price) { min_price = price; } else { ans = max(price - min_price, ans); } } return ans; } }; #endif //CPP_0121__SOLUTION1_H_
ooooo-youwillsee/leetcode
0191-Number-of-1-Bits/cpp_0191/Solution1.h
// // Created by ooooo on 2019/12/5. // #ifndef CPP_0191_SOLUTION1_H #define CPP_0191_SOLUTION1_H #include <iostream> using namespace std; class Solution { public: int hammingWeight(uint32_t n) { int res = 0; while (n) { res +=1; n &= n-1; } return res; } }; #endif //CPP_0191_SOLUTION1_H
ooooo-youwillsee/leetcode
0202-Happy-Number/cpp_0202/Solution2.h
// // Created by ooooo on 2020/1/8. // #ifndef CPP_0202_SOLUTION2_H #define CPP_0202_SOLUTION2_H #include <iostream> #include <cmath> #include <unordered_set> using namespace std; /** * * 哈希表 (先insert,计算之后如果还存在, 就是false) */ class Solution { public: int help(int num) { int sum = 0; while (num) { sum += pow(num % 10, 2); num /= 10; } return sum; } bool isHappy(int n) { unordered_set<int> s; while (true) { if (n == 1) return true; s.insert(n); n = help(n); if (s.count(n)) return false; } } }; #endif //CPP_0202_SOLUTION2_H
ooooo-youwillsee/leetcode
lcof_003/cpp_003/Solution3.h
<filename>lcof_003/cpp_003/Solution3.h // // Created by ooooo on 2020/3/5. // #ifndef CPP_003__SOLUTION3_H_ #define CPP_003__SOLUTION3_H_ #include <iostream> #include <vector> using namespace std; /** * 抽屉原理 */ class Solution { public: int findRepeatNumber(vector<int> &nums) { for (int i = 0, len = nums.size(); i < len;) { if (nums[i] == i) { i += 1; } else { if (nums[i] == nums[nums[i]]) return nums[i]; swap(nums[i], nums[nums[i]]); } } return -1; } }; #endif //CPP_003__SOLUTION3_H_
ooooo-youwillsee/leetcode
0965-Univalued-Binary-Tree/cpp_0965/Solution1.h
<filename>0965-Univalued-Binary-Tree/cpp_0965/Solution1.h // // Created by ooooo on 2019/12/31. // #ifndef CPP_0965_SOLUTION1_H #define CPP_0965_SOLUTION1_H #include "TreeNode.h" class Solution { public: bool dfs(TreeNode *node, int x) { if (!node) return true; return node->val == x && dfs(node->left, x) && dfs(node->right, x); } bool isUnivalTree(TreeNode *root) { if (!root) return true; return dfs(root, root->val); } }; #endif //CPP_0965_SOLUTION1_H
ooooo-youwillsee/leetcode
1442-Count Triplets That Can Form Two Arrays of Equal XOR/cpp_1442/Solution3.h
/** * @author ooooo * @date 2021/5/22 11:38 */ #ifndef CPP_1442__SOLUTION3_H_ #define CPP_1442__SOLUTION3_H_ #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: int countTriplets(vector<int>& arr) { int n = arr.size(); vector<int> pre(n+1); for (int i = 0; i < n; i++) { pre[i+1] = pre[i] ^ arr[i]; } // pre[j] ^ pre[i] = pre[k+1] ^ pre[j] int ans = 0; unordered_map<int, int> m, len; for (int i = 0; i < n; i++) { if (m.count(pre[i+1])) { ans += (i * m[pre[i+1]] - len[pre[i+1]]); } // 可能存在异或值为0的情况 len[pre[i]] += i; m[pre[i]] ++; } return ans; } }; #endif //CPP_1442__SOLUTION3_H_
ooooo-youwillsee/leetcode
1370-Increasing-Decreasing-String/cpp_1370/Solution1.h
/** * @author ooooo * @date 2020/11/25 09:13 */ #ifndef CPP_1370__SOLUTION1_H_ #define CPP_1370__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: string sortString(string s) { vector<int> count(26); for (auto &c :s) { count[c - 'a']++; } int n = s.size(), i = 0, step = 1; string ans = ""; while (n > 0) { if (count[i] > 0) { ans.push_back(i + 'a'); n--; count[i]--; } i += step; if (i >= count.size() || i < 0) { step = -step; i += step; } } return ans; } }; #endif //CPP_1370__SOLUTION1_H_
ooooo-youwillsee/leetcode
0202-Happy-Number/cpp_0202/Solution3.h
// // Created by ooooo on 2020/1/8. // #ifndef CPP_0202_SOLUTION3_H #define CPP_0202_SOLUTION3_H #include <iostream> #include <cmath> using namespace std; /** * * 快慢指针 */ class Solution { public: int help(int num) { int sum = 0; while (num) { sum += pow(num % 10, 2); num /= 10; } return sum; } bool isHappy(int n) { int low = n, fast = n; while (true) { // 慢指针 low = help(low); // 快指针 fast = help(help(fast)); if (low == 1) return true; if (low == fast) return false; } } }; #endif //CPP_0202_SOLUTION3_H
ooooo-youwillsee/leetcode
0144-Binary-Tree-Preorder-Traversal/cpp_0144/TreeNode.h
<filename>0144-Binary-Tree-Preorder-Traversal/cpp_0144/TreeNode.h /** * @author ooooo * @date 2020/9/25 23:15 */ #ifndef CPP_0144__TREENODE_H_ #define CPP_0144__TREENODE_H_ #include <iostream> #include <vector> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; #endif //CPP_0144__TREENODE_H_
ooooo-youwillsee/leetcode
lcof_030/cpp_030/Solution1.h
<gh_stars>10-100 // // Created by ooooo on 2020/3/19. // #ifndef CPP_030__SOLUTION1_H_ #define CPP_030__SOLUTION1_H_ #include <iostream> using namespace std; class MinStack { private: struct Node { Node *next; int val; Node(Node *next, int val) : next(next), val(val) {} Node(int val) : val(val), next(nullptr) {} }; Node *dummyHead; int size; public: /** initialize your data structure here. */ MinStack() { dummyHead = new Node(0); size = 0; } void push(int x) { dummyHead->next = new Node(dummyHead->next, x); size += 1; } void pop() { if (size == 0) return; dummyHead->next = dummyHead->next->next; size--; } int top() { if (size == 0) return -1; return dummyHead->next->val; } int min() { Node *cur = dummyHead->next; int min_value = INT_MAX; while (cur) { min_value = std::min(min_value, cur->val); cur = cur->next; } return min_value; } }; #endif //CPP_030__SOLUTION1_H_
ooooo-youwillsee/leetcode
0696-Count-Binary-Substrings/cpp_0696/Solution2.h
// // Created by ooooo on 2020/1/30. // #ifndef CPP_0696__SOLUTION2_H_ #define CPP_0696__SOLUTION2_H_ #include <iostream> using namespace std; /** * 上一个连续字符的个数和当前连续字符的个数 */ class Solution { public: int countBinarySubstrings(string s) { int ans = 0, prev = 0, cur = 1; for (int i = 0; i < s.size(); ++i) { if (i != s.size() - 1 && s[i] == s[i + 1]) { cur++; } else { ans += min(prev, cur); prev = cur; cur = 1; } } return ans; } }; #endif //CPP_0696__SOLUTION2_H_
ooooo-youwillsee/leetcode
1881-Maximum Value after Insertion/cpp_1881/Solution1.h
<gh_stars>10-100 /** * @author ooooo * @date 2021/5/31 10:17 */ #ifndef CPP_1881__SOLUTION1_H_ #define CPP_1881__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: string maxValue(string n, int x) { string ans = ""; int i = 0; bool inserted = false; if (n[i] == '-') { i = 1; ans += n[0]; while (i < n.size()) { if (!inserted && (n[i] - '0') > x) { ans += to_string(x); inserted = true; } else { ans += n[i]; i++; } } } else { while (i < n.size()) { if (!inserted && (n[i] - '0') < x) { ans += to_string(x); inserted = true; } else { ans += n[i]; i++; } } } if (!inserted) { ans += to_string(x); } return ans; } }; #endif //CPP_1881__SOLUTION1_H_
ooooo-youwillsee/leetcode
0080-Remove Duplicates from Sorted Array II/cpp_0080/Solution1.h
/** * @author ooooo * @date 2021/4/6 11:19 */ #ifndef CPP_0080__SOLUTION1_H_ #define CPP_0080__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: int removeDuplicates(vector<int> &nums) { int i = 0; for (auto num : nums) { if (i < 2 || num != nums[i - 2]) { nums[i++] = num; } } return i; } }; #endif //CPP_0080__SOLUTION1_H_
ooooo-youwillsee/leetcode
0811-Subdomain-Visit-Count/cpp_0811/Solution1.h
// // Created by ooooo on 2020/1/15. // #ifndef CPP_0811__SOLUTION1_H_ #define CPP_0811__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: vector<string> split(string s, string sep) { vector<string> ans; int i = s.find_first_of(" ") + 1; ans.push_back(s.substr(i, s.size() - i)); int j = s.find_first_of(sep, i + 1); while (j != -1) { ans.push_back(s.substr(j + 1, s.size() - j - 1)); j = s.find_first_of(sep, j + 1); } return ans; } vector<string> subdomainVisits(vector<string> &cpdomains) { unordered_map<string, int> m; for (const auto &domain: cpdomains) { int times = stoi(domain.substr(0, domain.find_first_of(" "))); for (const auto &item: split(domain, ".")) { m[item] += times; } } vector<string> ans; for(const auto &entry: m) { ans.push_back(to_string(entry.second) + " " + entry.first); } return ans; } }; #endif //CPP_0811__SOLUTION1_H_
ooooo-youwillsee/leetcode
1584-Min Cost to Connect All Points/cpp_1584/Solution1.h
<gh_stars>10-100 /** * @author ooooo * @date 2021/1/19 20:12 */ #ifndef CPP_1584__SOLUTION1_H_ #define CPP_1584__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_set> using namespace std; class Solution { public: vector<int> p; struct Edge { int len, u, v; Edge(int len, int u, int v) : len(len), u(u), v(v) {} }; int minCostConnectPoints(vector<vector<int>> &points) { int n = points.size(); p.resize(n, 0); for (int i = 0; i < p.size(); ++i) { p[i] = i; } vector<Edge> edges; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int dist = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]); edges.emplace_back(dist, i, j); } } sort(edges.begin(), edges.end(), [](auto &x, auto &y) { return x.len < y.len; }); int ans = 0; int num = 0; for (auto &[len, u, v]:edges) { if (!connected(u, v)) { ans += len; num++; if (num == n - 1) { break; } } } return ans; } int find(int i) { if (p[i] == i) return i; return p[i] = find(p[i]); } bool connected(int i, int j) { int pi = find(i), pj = find(j); if (pi == pj) { return true; } p[pi] = pj; return false; } }; #endif //CPP_1584__SOLUTION1_H_
ooooo-youwillsee/leetcode
0206-Reverse-Linked-List/cpp_0206/ListNode.h
// // Created by ooooo on 2019/10/29. // #ifndef CPP_0206_LISTNODE_H #define CPP_0206_LISTNODE_H struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; #endif //CPP_0206_LISTNODE_H
ooooo-youwillsee/leetcode
0147-Insertion Sort List/cpp_0147/Solution1.h
<filename>0147-Insertion Sort List/cpp_0147/Solution1.h /** * @author ooooo * @date 2020/11/20 09:11 */ #ifndef CPP_0147__SOLUTION1_H_ #define CPP_0147__SOLUTION1_H_ #include "ListNode.h" class Solution { public: void insert(ListNode *dummyHead, ListNode *node) { ListNode *cur = dummyHead; while (cur->next) { if (node->val <= cur->next->val) { ListNode *next = cur->next; cur->next = node; node->next = next; return; } cur = cur->next; } cur->next = node; } ListNode *insertionSortList(ListNode *head) { ListNode *dummyHead = new ListNode(-1); ListNode *cur = head; while (cur) { ListNode *next = cur->next; cur->next = nullptr; insert(dummyHead, cur); cur = next; } return dummyHead->next; } }; #endif //CPP_0147__SOLUTION1_H_
ooooo-youwillsee/leetcode
0744-Find-Smallest-Letter-Greater-Than-Target/cpp_0744/Solution1.h
// // Created by ooooo on 2020/1/20. // #ifndef CPP_0744__SOLUTION1_H_ #define CPP_0744__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; /** * binary search */ class Solution { public: char nextGreatestLetter(vector<char> &letters, char target) { if (target < letters[0] || target >= letters[letters.size() - 1]) return letters[0]; int left = 0, right = letters.size() - 1, mid = 0; while (left < right) { mid = left + (right - left) / 2; // 思考不存在的情况再缩小搜索空间 if (letters[mid] <= target) { left = mid + 1; } else { right = mid; } } return letters[left]; } }; #endif //CPP_0744__SOLUTION1_H_
ooooo-youwillsee/leetcode
0018-4Sum/cpp_0018/Solution2.h
// // Created by ooooo on 2019/11/1. // #ifndef CPP_0018_SOLUTION2_H #define CPP_0018_SOLUTION2_H #include <iostream> #include <vector> #include <algorithm> #include <map> #include <set> using namespace std; class Solution { public: vector<vector<int>> fourSum(vector<int> &nums, int target) { vector<vector<int>> res; if (nums.size() < 4) { return res; } sort(nums.begin(), nums.end()); set<vector<int>> set; map<int, vector<vector<int>>> m; for (int i = 0; i < nums.size() - 1; ++i) { for (int j = i + 1; j < nums.size(); ++j) { int mid = nums[i] + nums[j]; map<int, vector<vector<int>>>::iterator it = m.find(mid); if (it == m.end()) { vector<vector<int>> vec; vector<int> v = {i, j}; vec.push_back(v); m[mid] = vec; } else { vector<vector<int>> vec = it->second; vector<int> v = {i, j}; vec.push_back(v); m[mid] = vec; } } } for (auto mapIterator = m.begin(); mapIterator != m.end(); ++mapIterator) { int first = mapIterator->first; vector<vector<int>> second = mapIterator->second; int i = 0; int j = nums.size() - 1; while (i < j) { int n = nums[i] + nums[j] + first; if (n < target) { i += 1; } else if (n > target) { j -= 1; } else { for (auto item : second) { if (item[0] != i && item[0] != j && item[1] != i && item[1] != j) { vector<int> vec = {nums[i], nums[j], nums[item[0]], nums[item[1]]}; sort(vec.begin(), vec.end()); set.insert(vec); } } i += 1; j -= 1; } } } for (auto item: set) { res.push_back(item); } return res; } }; #endif //CPP_0018_SOLUTION2_H
ooooo-youwillsee/leetcode
0088-Merge-Sorted-Array/cpp_0088/Solution2.h
// // Created by ooooo on 2019/12/5. // #ifndef CPP_0088_SOLUTION2_H #define CPP_0088_SOLUTION2_H #include <vector> #include <iostream> using namespace std; class Solution { public: void merge(vector<int> &nums1, int m, vector<int> &nums2, int n) { vector<int> vec(nums1.begin(), nums1.begin() + m); int i = 0, j = 0, k = 0; while (i < m && j < n) nums1[k++] = vec[i] <= nums2[j] ? vec[i++] : nums2[j++]; while (i < m) nums1[k++] = vec[i++]; while (j < n) nums1[k++] = nums2[j++]; } }; #endif //CPP_0088_SOLUTION2_H
ooooo-youwillsee/leetcode
0132-Palindrome Partitioning II/cpp_0132/Solution1.h
/** * @author ooooo * @date 2021/3/8 12:05 */ #ifndef CPP_0132__SOLUTION1_H_ #define CPP_0132__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: int minCut(string s) { int n = s.size(); vector<vector<bool>> dp(n, vector<bool>(n, 0)); for (int i = n - 1; i >= 0; --i) { for (int j = i; j < n; ++j) { if (i == j) { dp[i][j] = true; } else if (j == i + 1) { dp[i][j] = s[i] == s[j]; } else { dp[i][j] = s[i] == s[j] && dp[i + 1][j - 1]; } } } vector<int> cnt(n, n); for (int i = 0; i < n; ++i) { if (dp[0][i]) { cnt[i] = 0; continue; } for (int k = i; k >= 0; --k) { if (dp[k][i]) { cnt[i] = min(cnt[i], cnt[k - 1] + 1); } } } return cnt[n - 1]; } }; #endif //CPP_0132__SOLUTION1_H_
ooooo-youwillsee/leetcode
0094-Binary-Tree-Inorder-Traversal/cpp_0094/Solution1.h
<filename>0094-Binary-Tree-Inorder-Traversal/cpp_0094/Solution1.h<gh_stars>10-100 // // Created by ooooo on 2020/2/15. // #ifndef CPP_0094__SOLUTION1_H_ #define CPP_0094__SOLUTION1_H_ #include "TreeNode.h" /** * recursion */ class Solution { public: void dfs(TreeNode *node) { if (!node) return; dfs(node->left); ans.push_back(node->val); dfs(node->right); } vector<int> ans; vector<int> inorderTraversal(TreeNode *root) { dfs(root); return ans; } }; #endif //CPP_0094__SOLUTION1_H_
ooooo-youwillsee/leetcode
0101-Symmetric-Tree/cpp_0101/Solution2.h
<filename>0101-Symmetric-Tree/cpp_0101/Solution2.h<gh_stars>10-100 // // Created by ooooo on 2019/12/6. // #ifndef CPP_0101_SOLUTION2_H #define CPP_0101_SOLUTION2_H #include "TreeNode.h" #include <queue> class Solution { public: bool isSymmetric(TreeNode *root) { queue<TreeNode *> q; q.push(root); q.push(root); while (!q.empty()) { TreeNode *node1 = q.front(); q.pop(); TreeNode *node2 = q.front(); q.pop(); if (!node1 && !node2) continue; if (!node1 || !node2) return false; if (node1->val != node2->val) return false; q.push(node1->left); q.push(node2->right); q.push(node1->right); q.push(node2->left); } return true; } }; #endif //CPP_0101_SOLUTION2_H
ooooo-youwillsee/leetcode
1011-Capacity To Ship Packages Within D Days/cpp_1011/Solution1.h
<gh_stars>10-100 /** * @author ooooo * @date 2021/4/26 19:42 */ #ifndef CPP_1011__SOLUTION1_H_ #define CPP_1011__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: bool check(vector<int> &weights, int k, int D) { int d = 0; int cur = 0; for (int i = 0; i < weights.size(); i++) { if (weights[i] > k) return false; if (cur + weights[i] > k) { d++; cur = 0; } cur += weights[i]; } d++; return d <= D; } int shipWithinDays(vector<int> &weights, int D) { int l = 0; int r = 0; int n = weights.size(); for (int i = 0; i < n; i++) { r += weights[i]; l = max(l, weights[i]); } int ans = 0; while (l <= r) { int mid = l + (r - l) / 2; if (check(weights, mid, D)) { ans = mid; r = mid - 1; } else { l = mid + 1; } } return ans; } }; #endif //CPP_1011__SOLUTION1_H_
ooooo-youwillsee/leetcode
0494-Target-Sum/cpp_0494/Solution1.h
<reponame>ooooo-youwillsee/leetcode<filename>0494-Target-Sum/cpp_0494/Solution1.h // // Created by ooooo on 2020/3/3. // #ifndef CPP_0494__SOLUTION1_H_ #define CPP_0494__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; /** * dfs */ class Solution { public: void dfs(int i, int sum) { if (i == nums.size()) { if (sum == S) { count++; } return; } dfs(i + 1, sum - nums[i]); dfs(i + 1, sum + nums[i]); } vector<int> nums; int S, count = 0; int findTargetSumWays(vector<int> &nums, int S) { this->nums = nums; this->S = S; dfs(0, 0); return count; } }; #endif //CPP_0494__SOLUTION1_H_
ooooo-youwillsee/leetcode
0509-Fibonacci-Number/cpp_0509/Solution1.h
// // Created by ooooo on 2020/1/6. // #ifndef CPP_0509_SOLUTION1_H #define CPP_0509_SOLUTION1_H #include <iostream> using namespace std; /** * recursion */ class Solution { public: int fib(int N) { if (N == 0 || N == 1) return N; return fib(N - 1) + fib(N - 2); } }; #endif //CPP_0509_SOLUTION1_H
ooooo-youwillsee/leetcode
0532-K-diff-Pairs-in-an-Array/cpp_0532/Solution3.h
// // Created by ooooo on 2020/1/8. // #ifndef CPP_0532_SOLUTION3_H #define CPP_0532_SOLUTION3_H #include <iostream> #include <vector> #include <unordered_set> #include <unordered_map> using namespace std; /** * */ class Solution { public: int findPairs(vector<int> &nums, int k) { if (nums.empty() || k < 0) return 0; int ans = 0; if (k == 0) { unordered_map<int, int> m; for (auto &num: nums) { if (m.count(num)) m[num] += 1; else m[num] = 1; } for (auto &entry: m) { if (entry.second >= 2) ans++; } return ans; } else { unordered_set<string> set; unordered_set<int> s; for (auto &num: nums) { if (s.count(num + k)) set.insert(to_string(num) + "#" + to_string(num + k)); if (s.count(num - k)) set.insert(to_string(num - k) + "#" + to_string(num)); s.insert(num); } ans = set.size(); } return ans; } }; #endif //CPP_0532_SOLUTION3_H
ooooo-youwillsee/leetcode
0268-Missing-Number/cpp_0268/Solution3.h
<reponame>ooooo-youwillsee/leetcode // // Created by ooooo on 2020/1/6. // #ifndef CPP_0268_SOLUTION3_H #define CPP_0268_SOLUTION3_H #include <iostream> #include <vector> using namespace std; /** * a ^ 0 = a * a ^ a = 0 */ class Solution { public: int missingNumber(vector<int> &nums) { int num = nums.size(); for (int i = 0, len = nums.size(); i < len; ++i) { num ^= i ^ nums[i]; } return num; } }; #endif //CPP_0268_SOLUTION3_H
ooooo-youwillsee/leetcode
0037-Sudoku-Solver/cpp_0037/Solution1.h
<filename>0037-Sudoku-Solver/cpp_0037/Solution1.h // // Created by ooooo on 2019/11/21. // #ifndef CPP_0037_SOLUTION1_H #define CPP_0037_SOLUTION1_H #include <iostream> #include <vector> #include <set> using namespace std; class Solution { private: bool check(vector<vector<char>> &board, int i, int j, char k) { for (int row = 0; row < 9; ++row) if (board[row][j] == k) return false; for (int col = 0; col < 9; ++col) if (board[i][col] == k) return false; int x = i / 3 * 3, y = j / 3 * 3; for (int row = x; row < x + 3; ++row) for (int col = y; col < y + 3; ++col) if (board[row][col] == k) return false; return true; } bool resolve(vector<vector<char>> &board, int n) { if (n >= 81) return true; int row = n / 9, col = n % 9; if (board[row][col] != '.') return resolve(board, n + 1); for (char k = '1'; k <= '9'; k++) { if (check(board, row, col, k)) { char c = board[row][col]; board[row][col] = k; if (resolve(board, n + 1)) return true; board[row][col] = c; } } return false; } public: void solveSudoku(vector<vector<char>> &board) { resolve(board, 0); } }; #endif //CPP_0037_SOLUTION1_H
ooooo-youwillsee/leetcode
1718-Construct the Lexicographically Largest Valid Sequence/cpp_1718/Solution1.h
/** * @author ooooo * @date 2021/1/24 09:28 */ #ifndef CPP_1718__SOLUTION1_H_ #define CPP_1718__SOLUTION1_H_ #include <iostream> #include <vector> #include <set> using namespace std; class Solution { public: vector<int> nums; vector<int> ans; bool dfs(int i) { if (i >= ans.size()) return true; if (ans[i] != -1) return dfs(i + 1); // 从最大的数字开始选择 for (int k = 0; k < nums.size(); k++) { int num = nums[k]; // 这个数字已经被选中 if (num == -1) continue; if (num != 1) { if (i + num >= ans.size() || ans[i + num] != -1) { continue; } ans[i + num] = num; } ans[i] = num; nums[k] = -1; if (dfs(i + 1)) return true; ans[i] = -1; nums[k] = num; if (num != 1 && i + num < ans.size()) { ans[i + num] = -1; } } return false; } vector<int> constructDistancedSequence(int n) { for (int i = 1; i <= n; ++i) { nums.push_back(i); } sort(nums.begin(), nums.end(), greater<int>()); ans.assign(2 * n - 1, -1); dfs(0); return ans; } }; #endif //CPP_1718__SOLUTION1_H_
ooooo-youwillsee/leetcode
lcp-028/cpp_028/Solution1.h
<reponame>ooooo-youwillsee/leetcode<filename>lcp-028/cpp_028/Solution1.h /** * @author ooooo * @date 2021/4/10 20:27 */ #ifndef CPP_028__SOLUTION1_H_ #define CPP_028__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: int purchasePlans(vector<int> &nums, int target) { sort(nums.begin(), nums.end()); int n = nums.size(); int l = 0, r = n - 1; long long ans = 0; while (l < r) { if (nums[l] + nums[r] > target) r--; else { ans += r - l; l++; } } return ans % 1000000007; } }; #endif //CPP_028__SOLUTION1_H_
ooooo-youwillsee/leetcode
0454-4Sum II/cpp_0454/Solution1.h
<reponame>ooooo-youwillsee/leetcode<filename>0454-4Sum II/cpp_0454/Solution1.h /** * @author ooooo * @date 2020/11/27 10:05 */ #ifndef CPP_0454__SOLUTION1_H_ #define CPP_0454__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: int fourSumCount(vector<int> &A, vector<int> &B, vector<int> &C, vector<int> &D) { unordered_map<int, int> m1; for (int i = 0; i < A.size(); ++i) { for (int j = 0; j < B.size(); ++j) { m1[A[i] + B[j]]++; } } int ans = 0; for (int i = 0; i < C.size(); ++i) { for (int j = 0; j < D.size(); ++j) { int x = C[i] + D[j]; ans += m1[-x]; } } return ans; } }; #endif //CPP_0454__SOLUTION1_H_
ooooo-youwillsee/leetcode
0680-Valid-Palindrome-II/cpp_0680/Solution3.h
// // Created by ooooo on 2020/1/28. // #ifndef CPP_0680__SOLUTION3_H_ #define CPP_0680__SOLUTION3_H_ #include <iostream> using namespace std; /** * 双指针, 有一个不相等的字符, 就比较 【left-1, right】和 【left, right-1】 */ class Solution { public: bool validPalindrome(string s) { for (int left = 0, right = s.size() - 1; left <= right; ++left, --right) { if (s[left] != s[right]) { return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1); } } return true; } bool isPalindrome(string s, int left, int right) { while (left < right) { if (s[left++] != s[right--]) { return false; } } return true; } }; #endif //CPP_0680__SOLUTION3_H_
ooooo-youwillsee/leetcode
0503-Next Greater Element II/cpp_0503/Solution1.h
<reponame>ooooo-youwillsee/leetcode /** * @author ooooo * @date 2021/3/6 13:05 */ #ifndef CPP_0503__SOLUTION1_H_ #define CPP_0503__SOLUTION1_H_ #include <iostream> #include <vector> #include <stack> using namespace std; // 单调栈 ,底部元素最大 class Solution { public: vector<int> nextGreaterElements(vector<int> &nums) { stack<int> s; int n = nums.size(); vector<int> ans(n, -1); // 对最后一个元素特殊处理 for (int i = n - 2; i >= 0; --i) { while (!s.empty() && nums[i] >= s.top()) { s.pop(); } s.push(nums[i]); } for (int i = n - 1; i >= 0; --i) { while (!s.empty() && nums[i] >= s.top()) { s.pop(); } if (!s.empty()) { ans[i] = s.top(); } s.push(nums[i]); } return ans; } }; #endif //CPP_0503__SOLUTION1_H_
ooooo-youwillsee/leetcode
1269-Number of Ways to Stay in the Same Place After Some Steps/cpp_1269/Solution1.h
<filename>1269-Number of Ways to Stay in the Same Place After Some Steps/cpp_1269/Solution1.h /** * @author ooooo * @date 2021/5/13 21:19 */ #ifndef CPP_1269__SOLUTION1_H_ #define CPP_1269__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: int mod = 1e9 + 7; unordered_map<int, unordered_map<int, long long>> memo; long long dfs(int cur, int restStep, int arrLen) { if (cur < 0 || cur >= arrLen || restStep < 0) { return 0; } if (memo.find(cur) != memo.end()) { if (memo[cur].find(restStep) != memo[cur].end()) { return memo[cur][restStep]; } } if (cur == 0 && restStep == 0) { return memo[cur][restStep] = 1; } long long sum = 0; restStep--; sum = (sum + dfs(cur, restStep, arrLen)) % mod; sum = (sum + dfs(cur + 1, restStep, arrLen)) % mod; sum = (sum + dfs(cur - 1, restStep, arrLen)) % mod; return memo[cur][restStep + 1] = sum; } int numWays(int steps, int arrLen) { return dfs(0, steps, arrLen); } }; #endif //CPP_1269__SOLUTION1_H_
ooooo-youwillsee/leetcode
0671-Second-Minimum-Node-In-a-Binary-Tree/cpp_0671/Solution1.h
// // Created by ooooo on 2020/1/4. // #ifndef CPP_0671_SOLUTION1_H #define CPP_0671_SOLUTION1_H #include "TreeNode.h" class Solution { public: int dfs(TreeNode *node, int min) { if (!node) return -1; if (node->val > min) return node->val; int left = dfs(node->left, min); int right = dfs(node->right, min); if (left == -1) return right; if (right == -1) return left; return std::min(left, right); } int findSecondMinimumValue(TreeNode *root) { if (!root) return -1; return dfs(root, root->val); } }; #endif //CPP_0671_SOLUTION1_H
ooooo-youwillsee/leetcode
0669-Trim-a-Binary-Search-Tree/cpp_0669/TreeNode.h
// // Created by ooooo on 2020/1/3. // #ifndef CPP_0669_TREENODE_H #define CPP_0669_TREENODE_H #include <iostream> #include <vector> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} TreeNode(vector<int> nums) { this->val = nums[0]; this->left = this->right = nullptr; queue<TreeNode *> q; q.push(this); for (int i = 1; i < nums.size();) { TreeNode *node = q.front(); q.pop(); if (!node) { i += 2; continue; } int leftNum = nums[i++]; if (leftNum != INT_MIN) { node->left = new TreeNode(leftNum); } int rightNum = nums[i++]; if (rightNum != INT_MIN) { node->right = new TreeNode(rightNum); } q.push(node->left); q.push(node->right); } } void inOrder() { inOrder(this); cout << endl; } void inOrder(TreeNode *node) { if (!node) return; inOrder(node->left); cout << node->val << " "; inOrder(node->right); } }; #endif //CPP_0669_TREENODE_H
ooooo-youwillsee/leetcode
1727-Largest Submatrix With Rearrangements/cpp_1727/Solution1.h
<gh_stars>10-100 /** * @author ooooo * @date 2021/1/24 17:10 */ #ifndef CPP_1727__SOLUTION1_H_ #define CPP_1727__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_map> #include <queue> #include <unordered_set> #include <set> using namespace std; class Solution { public: int largestSubmatrix(vector<vector<int>> &matrix) { int m = matrix.size(), n = matrix[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); // 计算每一个方块,向上的直连的个数 for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i == 0) { dp[i][j] = matrix[i][j]; continue; } if (matrix[i][j] == 1) { dp[i][j] = 1 + dp[i - 1][j]; } } } int ans = 0; // 从最后一层开始向上 for (int i = m - 1; i >= 0; --i) { // 先形成矩阵数组 vector<int> row; for (int j = 0; j < n; ++j) { if (dp[i][j]) { row.push_back(dp[i][j]); } } // 最大的放在前面 sort(row.begin(), row.end(), greater<int>()); // 计算每一层的最大矩形个数 int curMinHeight = INT_MAX; for (int j = 0; j < row.size(); ++j) { curMinHeight = min(curMinHeight, row[j]); ans = max(ans, curMinHeight * (j + 1)); } } return ans; } }; #endif //CPP_1727__SOLUTION1_H_
ooooo-youwillsee/leetcode
lcof_004/cpp_004/Solution2.h
// // Created by ooooo on 2020/3/6. // #ifndef CPP_004__SOLUTION2_H_ #define CPP_004__SOLUTION2_H_ #include <iostream> #include <vector> using namespace std; /** * O(n^2) */ class Solution { public: bool findNumberIn2DArray(vector<vector<int>> &matrix, int target) { for (int i = 0, rows = matrix.size(); i < rows; ++i) { for (int j = 0, cols = matrix[0].size(); j < cols; ++j) { if (matrix[i][j] == target) return true; } } return false; } }; #endif //CPP_004__SOLUTION2_H_
ooooo-youwillsee/leetcode
0621-Task Scheduler/cpp_0621/Solution1.h
<reponame>ooooo-youwillsee/leetcode /** * @author ooooo * @date 2020/12/5 11:39 */ #ifndef CPP_0621__SOLUTION1_H_ #define CPP_0621__SOLUTION1_H_ #include <iostream> #include <vector> #include <queue> using namespace std; /** * timeout */ class Solution { public: int leastInterval(vector<char> &tasks, int n) { // 每个任务的个数 vector<int> task_counts(26, 0); for (auto &t: tasks) { task_counts[t - 'A']++; } // 每个任务的冷却时间 vector<int> down_times(26, 0); auto f = [&](const int &i, const int &j) { if (down_times[i] == down_times[j]) { return task_counts[i] < task_counts[j]; } return down_times[i] > down_times[j]; }; // 冷却时间最小堆 priority_queue<int, vector<int>, decltype(f)> q(f); for (int i = 0; i < task_counts.size(); ++i) { // 任务个数大于0 if (task_counts[i] > 0) { q.push(i); } } int ans = 0; while (!q.empty()) { int i = q.top(); int down_time = down_times[i]; if (down_time <= 0) { // 冷却时间为0,可以直接执行 // 当前任务删除掉,当前任务冷却时间为n,任务减一 q.pop(); task_counts[i]--; down_times[i] = n; // 其他任务的冷却时间减一 while (!q.empty()) { int j = q.top(); q.pop(); down_times[j] = max(0, down_times[j] - 1); } for (int k = 0; k < task_counts.size(); ++k) { // 任务个数大于0 if (task_counts[k] > 0) { q.push(k); } } } else { // down_time 大于0,必须要等待 while (!q.empty()) { int j = q.top(); q.pop(); down_times[j]--; } for (int k = 0; k < task_counts.size(); ++k) { // 任务个数大于0 if (task_counts[k] > 0) { q.push(k); } } } ans++; } return ans; } }; #endif //CPP_0621__SOLUTION1_H_
ooooo-youwillsee/leetcode
0106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/cpp_0106/TreeNode.h
/** * @author ooooo * @date 2020/9/25 09:24 */ #ifndef CPP_0106__TREENODE_H_ #define CPP_0106__TREENODE_H_ #include <iostream> #include <vector> #include <unordered_map> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; #endif //CPP_0106__TREENODE_H_
ooooo-youwillsee/leetcode
0606-Construct-String-from-Binary-Tree/cpp_0606/Solution2.h
// // Created by ooooo on 2020/1/3. // #ifndef CPP_0606_SOLUTION2_H #define CPP_0606_SOLUTION2_H #include "TreeNode.h" /** * 无返回值快。 前序遍历 */ class Solution { public: void dfs(TreeNode *node, string &s) { if (!node) return; s += to_string(node->val); if (node->left || node->right) { s += "("; dfs(node->left, s); s += ")"; } if (node->right) { s += "("; dfs(node->right, s); s += ")"; } } string tree2str(TreeNode *t) { string s = ""; dfs(t, s); return s; } }; #endif //CPP_0606_SOLUTION2_H
ooooo-youwillsee/leetcode
0463-Island-Perimeter/cpp_0463/Solution1.h
// // Created by ooooo on 2020/1/11. // #ifndef CPP_0463__SOLUTION1_H_ #define CPP_0463__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; /** * 分别计算每一个节点的边数 */ class Solution { public: int help(vector<vector<int>> &grid, int i, int j) { if (grid[i][j] == 0) return 0; int ans = 0; if (i == 0 || grid[i - 1][j] == 0) ans++; if (j == 0 || grid[i][j - 1] == 0) ans++; if (j == grid[i].size() - 1 || grid[i][j + 1] == 0) ans++; if (i == grid.size() - 1 || grid[i + 1][j] == 0) ans++; return ans; } int islandPerimeter(vector<vector<int>> &grid) { int ans = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[i].size(); ++j) { ans += help(grid, i, j); } } return ans; } }; #endif //CPP_0463__SOLUTION1_H_
ooooo-youwillsee/leetcode
1722-Minimize Hamming Distance After Swap Operations/cpp_1722/Solution1.h
<reponame>ooooo-youwillsee/leetcode /** * @author ooooo * @date 2021/3/9 18:18 */ #ifndef CPP_1722__SOLUTION1_H_ #define CPP_1722__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; class Solution { public: struct UF { int n; vector<int> p; UF(int n) : n(n), p(n) { for (int i = 0; i < p.size(); ++i) { p[i] = i; } } int find(int i) { if (i == p[i]) return i; return p[i] = find(p[i]); } bool connect(int i, int j) { int pi = find(i), pj = find(j); if (pi == pj) return true; p[pi] = pj; return false; } }; int minimumHammingDistance(vector<int> &source, vector<int> &target, vector<vector<int>> &allowedSwaps) { int n = source.size(); UF uf(n); for (auto &swap: allowedSwaps) { int u = swap[0], v = swap[1]; uf.connect(u, v); } unordered_map<int, unordered_set<int>> m; for (int i = 0; i < n; ++i) { int root = uf.find(i); m[root].insert(i); } int ans = 0; for (auto &[k, v]: m) { unordered_map<int, int> cnt; for (auto j: v) { cnt[source[j]]++; } for (auto j: v) { if (cnt[target[j]] > 0) { cnt[target[j]]--; }else { ans++; } } } return ans; } }; #endif //CPP_1722__SOLUTION1_H_
ooooo-youwillsee/leetcode
lcp-030/cpp_030/Solution1.h
/** * @author ooooo * @date 2021/4/10 20:21 */ #ifndef CPP_030__SOLUTION1_H_ #define CPP_030__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: int magicTower(vector<int> &nums) { long long sum = 1; int n = nums.size(); for (int i = 0; i < n; i++) { sum += nums[i]; } if (sum <= 0) return -1; priority_queue<long long> pq; long long cur = 1; int ans = 0; for (int i = 0; i < n; i++) { cur += nums[i]; if (nums[i] < 0) { pq.push(-nums[i]); } if (cur <= 0) { cur += pq.top(); pq.pop(); ans++; } } return ans; } }; #endif //CPP_030__SOLUTION1_H_
ooooo-youwillsee/leetcode
0819-Most-Common-Word/cpp_0819/Solution2.h
<filename>0819-Most-Common-Word/cpp_0819/Solution2.h // // Created by ooooo on 2020/1/30. // #ifndef CPP_0819__SOLUTION2_H_ #define CPP_0819__SOLUTION2_H_ #include <iostream> #include <vector> #include <regex> #include <unordered_map> #include <unordered_set> using namespace std; /** * */ class Solution { public: string mostCommonWord(string paragraph, vector<string> &banned) { unordered_map<string, int> m; unordered_set<string> bannedSet(begin(banned), end(banned)); int i = 0, j = 0; string ans = ""; int max = 0; while (true) { while (i < paragraph.size() && !isalpha(paragraph[i])) { i++; } while (j < paragraph.size() && isalpha(paragraph[j])) { paragraph[j] = tolower(paragraph[j]); j++; } if (j > i) { string word = paragraph.substr(i, j - i); if (!bannedSet.count(word)) { ++m[word]; // 计数的同时可以比较!!! if (max < m[word]) { max = m[word]; ans = word; } } j++; i = j; } else if (i > j) { // j不是字符,可能是',' j++; } else { break; } } return ans; } }; #endif //CPP_0819__SOLUTION2_H_
ooooo-youwillsee/leetcode
0212-Word-Search-II/cpp_0212/Solution1.h
<gh_stars>10-100 // // Created by ooooo on 2019/12/4. // #ifndef CPP_0212_SOLUTION1_H #define CPP_0212_SOLUTION1_H #include <iostream> #include <vector> #include <set> using namespace std; class Solution { private: struct Node { bool isWord = false; vector<Node *> children = vector<Node *>(26, nullptr); }; Node *root; int m; // 行数 int n; // 列数 vector<vector<char>> board; vector<vector<bool>> marked; vector<int> arri = {0, 0, 1, -1}; vector<int> arrj = {1, -1, 0, 0}; void insert(string word) { Node *node = root; for (int i = 0; i < word.size(); i++) { int index = word[i] - 'a'; if (!node->children[index]) { node->children[index] = new Node(); } node = node->children[index]; } node->isWord = true; } void dfs(int i, int j, Node *curNode, string word, set<string> &res) { int index = board[i][j] - 'a'; curNode = curNode->children[index]; if (curNode) { if (curNode->isWord) { res.insert(word + board[i][j]); } marked[i][j] = true; string tempWord = word; word += board[i][j]; for (int k = 0; k < 4; ++k) { i += arri[k]; j += arrj[k]; if (isValid(i, j)) { dfs(i, j, curNode, word, res); } i -= arri[k]; j -= arrj[k]; } word = tempWord; marked[i][j] = false; } return; } bool isValid(int i, int j) { return i >= 0 && i < m && j >= 0 && j < n && !marked[i][j]; } public: vector<string> findWords(vector<vector<char>> &board, vector<string> &words) { this->root = new Node(); this->m = board.size(); this->n = board[0].size(); this->marked = vector<vector<bool>>(m, vector<bool>(n, false)); this->board = board; for (const auto &word : words) insert(word); set<string> res; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { dfs(i, j, root, "", res); } } return vector<string>(res.begin(), res.end()); } }; #endif //CPP_0212_SOLUTION1_H
ooooo-youwillsee/leetcode
0337-House-Robber-III/cpp_0337/Solution2.h
<gh_stars>10-100 // // Created by ooooo on 2020/2/25. // #ifndef CPP_0337__SOLUTION2_H_ #define CPP_0337__SOLUTION2_H_ #include "TreeNode.h" #include <unordered_map> using namespace std; /** * max money = max(根节点 + 四个孙子 , 两个儿子) * A * / \ * B B * / \ / \ * C C C C * * dfs + memo */ class Solution { public: unordered_map<TreeNode *, int> memo; int rob(TreeNode *root) { if (!root) return 0; if (memo.count(root)) return memo[root]; int money = root->val; if (root->left) { money += rob(root->left->left) + rob(root->left->right); } if (root->right) { money += rob(root->right->left) + rob(root->right->right); } money = max(money, rob(root->left) + rob(root->right)); memo[root] = money; return money; } }; #endif //CPP_0337__SOLUTION2_H_
ooooo-youwillsee/leetcode
0153-Find-Minimum-in-Rotated-Sorted-Array/cpp_0153/Solution2.h
/** * @author ooooo * @date 2020/9/25 23:55 */ #ifndef CPP_0153__SOLUTION2_H_ #define CPP_0153__SOLUTION2_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: int findMin(vector<int> &nums, int l, int r) { int mid = l + (r - l) / 2; if (nums[mid] > nums[l] && nums[mid] > nums[r]) return findMin(nums, mid + 1, r); if (nums[mid] < nums[r] && nums[mid] > nums[l]) return findMin(nums, l, mid); return *min_element(nums.begin() + l, nums.begin() + r + 1); } int findMin(vector<int> &nums) { if (nums[0] <= nums[nums.size() - 1]) return nums[0]; return findMin(nums, 0, nums.size() - 1); } }; #endif //CPP_0153__SOLUTION2_H_
ooooo-youwillsee/leetcode
lcci_17_13/cpp_17_13/Solution1.h
/** * @author ooooo * @date 2020/10/10 11:58 */ #ifndef CPP_17_13__SOLUTION1_H_ #define CPP_17_13__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_set> using namespace std; class Solution { public: int respace(vector<string> &dictionary, string sentence) { int n = sentence.size(); if (dictionary.empty()) return n; int min_len = dictionary[0].size(), max_len = 0; unordered_set<string> word_set; for (auto &item: dictionary) { int len = item.size(); min_len = min(min_len, len); max_len = max(max_len, len); word_set.insert(item); } vector<int> dp(n + 1, 0); for (int i = 0; i < n; i++) { dp[i + 1] = dp[i] + 1; if (i + 1 < min_len) continue; for (int j = min_len; j <= max_len; j++) { int prev_i = i - j + 1; if (prev_i < 0) continue; string s = sentence.substr(prev_i, j); if (word_set.find(s) != word_set.end()) { dp[i + 1] = min(dp[i + 1], dp[prev_i]); } } } return dp[n]; } }; #endif //CPP_17_13__SOLUTION1_H_
ooooo-youwillsee/leetcode
0459-Repeated-Substring-Pattern/cpp_0459/Solution2.h
// // Created by ooooo on 2020/1/26. // #ifndef CPP_0459__SOLUTION2_H_ #define CPP_0459__SOLUTION2_H_ #include <iostream> using namespace std; class Solution { public: bool repeatedSubstringPattern(string s) { /** * "abab" ==> "abababab" ==> 2 != s.size() * "aba" ==> "abaaba" ==> 3 = s.size() */ return (s + s).find(s, 1) != s.size(); } }; #endif //CPP_0459__SOLUTION2_H_
ooooo-youwillsee/leetcode
1646-Get Maximum in Generated Array/cpp_1646/Solution1.h
/** * @author ooooo * @date 2021/2/28 13:02 */ #ifndef CPP_1646__SOLUTION1_H_ #define CPP_1646__SOLUTION1_H_ #include <iostream> #include <vector> #include <unordered_set> #include <unordered_map> #include <queue> #include <stack> #include <numeric> using namespace std; class Solution { public: unordered_map<int, int> memo; int getGenerated(int n) { if (memo.find(n) != memo.end()) return memo[n]; if (n == 0 || n == 1) return n; int ans = n; if (n % 2 == 0) { ans = getGenerated(n / 2); } else { ans = getGenerated(n / 2) + getGenerated(n / 2 + 1); } return memo[n] = ans; } int getMaximumGenerated(int n) { int ans = 0; for (int i = 0; i <= n; ++i) { ans = max(getGenerated(i), ans); } return ans; } }; #endif //CPP_1646__SOLUTION1_H_
ooooo-youwillsee/leetcode
0208-Implement-Trie-Prefix-Tree/cpp_0208/Solution1.h
<filename>0208-Implement-Trie-Prefix-Tree/cpp_0208/Solution1.h // // Created by ooooo on 2019/12/2. // #ifndef CPP_0208_SOLUTION1_H #define CPP_0208_SOLUTION1_H #include <string> #include <vector> using namespace std; class Trie { private: struct Node { char c; vector<Node *> children = vector<Node *>(26, nullptr); bool isWord = false; Node(char c) { this->c = c; } Node() { } }; Node *root; public: /** Initialize your data structure here. */ Trie() { root = new Node(); } /** Inserts a word into the trie. */ void insert(string word) { Node *node = this->root; for (int i = 0; i < word.size(); ++i) { int index = word[i] - 'a'; if (node->children[index]) { node = node->children[index]; } else { node->children[index] = new Node(word[i]); node = node->children[index]; } } node->isWord = true; } /** Returns if the word is in the trie. */ bool search(string word) { Node *node = this->root; for (int i = 0; i < word.size(); ++i) { int index = word[i] - 'a'; if (!node->children[index]) { return false; } node = node->children[index]; } return node->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { Node *node = this->root; for (int i = 0; i < prefix.size(); ++i) { int index = prefix[i] - 'a'; if (!node->children[index]) { return false; } node = node->children[index]; } return true; } }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */ #endif //CPP_0208_SOLUTION1_H
ooooo-youwillsee/leetcode
0207-Course-Schedule/cpp_0207/Solution2.h
// // Created by ooooo on 2020/2/19. // #ifndef CPP_0207__SOLUTION2_H_ #define CPP_0207__SOLUTION2_H_ #include <iostream> #include <vector> #include <queue> using namespace std; /** * 拓扑排序 */ class Solution { public: bool canFinish(int numCourses, vector<vector<int>> &prerequisites) { vector<int> indegrees(numCourses, 0); vector<vector<int>> adjacency(numCourses, vector<int>()); for (auto &item: prerequisites) { indegrees[item[0]] += 1; adjacency[item[1]].push_back(item[0]); } queue<int> q; for (int i = 0; i < indegrees.size(); ++i) { if (indegrees[i] == 0) q.push(i); } while (!q.empty()) { int j = q.front(); q.pop(); numCourses--; for (auto &k : adjacency[j]) { if (--indegrees[k] == 0) q.push(k); } } return numCourses == 0; } }; #endif //CPP_0207__SOLUTION2_H_
ooooo-youwillsee/leetcode
0300-Longest-Increasing-Subsequence/cpp_0300/Solution2.h
// // Created by ooooo on 2020/2/24. // #ifndef CPP_0300__SOLUTION2_H_ #define CPP_0300__SOLUTION2_H_ #include <iostream> #include <vector> using namespace std; /** * 二分法 * 每一循环,尽量把小的放进去 */ class Solution { public: int lengthOfLIS(vector<int> &nums) { int n = nums.size(); if (n <= 1) return n; vector<int> vec; for (int i = 0; i < n; ++i) { auto it = lower_bound(vec.begin(), vec.end(), nums[i]); if (it == vec.end()) { vec.push_back(nums[i]); } else { *it = nums[i]; } } return vec.size(); } }; #endif //CPP_0300__SOLUTION2_H_
ooooo-youwillsee/leetcode
lcof_062/cpp_062/Solution2.h
// // Created by ooooo on 2020/4/22. // #ifndef CPP_062__SOLUTION2_H_ #define CPP_062__SOLUTION2_H_ #include <iostream> #include <list> using namespace std; /** * */ class Solution { public: int lastRemaining(int n, int m) { int ans = 0; for (int i = 2; i <= n; ++i) { ans = (ans + m) % i; } return ans; } }; #endif //CPP_062__SOLUTION2_H_
ooooo-youwillsee/leetcode
0367-Valid-Perfect-Square/cpp_0367/Solution1.h
// // Created by ooooo on 2020/1/17. // #ifndef CPP_0367__SOLUTION1_H_ #define CPP_0367__SOLUTION1_H_ #include <iostream> using namespace std; /** * int * int 越界 */ class Solution { public: bool isPerfectSquare(int num) { if (num < 2) return true; long left = 2, right = num / 2; while (left <= right) { int mid = left + (right - left) / 2; long sum = mid * mid; if (sum == num) { return true; } else if (sum < num) { left = mid + 1; } else { right = mid - 1; } } return false; } }; #endif //CPP_0367__SOLUTION1_H_
ooooo-youwillsee/leetcode
0135-Candy/cpp_0135/Solution1.h
/** * @author ooooo * @date 2020/12/24 14:16 */ #ifndef CPP_0135__SOLUTION1_H_ #define CPP_0135__SOLUTION1_H_ #include <iostream> #include <map> #include <vector> #include <numeric> using namespace std; class Solution { public: int candy(vector<int> &ratings) { map<int, vector<int>> rate_map; int n = ratings.size(); for (int i = 0; i < n; ++i) { rate_map[ratings[i]].push_back(i); } vector<int> candy(n, 0); for (auto &[k, v]: rate_map) { for (int i = 0; i < v.size(); ++i) { int cur_index = v[i]; int left_index = v[i] - 1, right_index = v[i] + 1; candy[cur_index] = 1; if (left_index >= 0 && ratings[cur_index] > ratings[left_index]) { candy[cur_index] = max(candy[cur_index], candy[left_index] + 1); } if (right_index <= n-1 && ratings[cur_index] > ratings[right_index]) { candy[cur_index] = max(candy[cur_index], candy[right_index] + 1); } } } return accumulate(candy.begin(), candy.end(), 0); } }; #endif //CPP_0135__SOLUTION1_H_
ooooo-youwillsee/leetcode
1642-Furthest Building You Can Reach/cpp_1642/Solution2.h
<filename>1642-Furthest Building You Can Reach/cpp_1642/Solution2.h /** * @author ooooo * @date 2021/3/6 16:27 */ #ifndef CPP_1642__SOLUTION2_H_ #define CPP_1642__SOLUTION2_H_ #include <iostream> #include <vector> #include <numeric> using namespace std; /** * 二分法 */ class Solution { public: int furthestBuilding(vector<int> &heights, int bricks, int ladders) { int n = heights.size(); int l = 0, r = n - 1; vector<int> diff(n - 1); for (int i = 0; i < n - 1; ++i) { diff[i] = max(heights[i + 1] - heights[i], 0); } int pos = 0; while (l <= r) { int mid = l + (r - l) / 2; if (check(mid, diff, bricks, ladders)) { pos = mid; l = mid + 1; } else { r = mid - 1; } } return pos; } bool check(int mid, vector<int> &diff, int bricks, int ladders) { vector<int> nums = {diff.begin(), diff.begin() + mid}; sort(nums.begin(), nums.end(), greater<int>()); int need = 0; for (int i = ladders; i < nums.size() ; ++i) { need += nums[i]; } return need <= bricks; } }; #endif //CPP_1642__SOLUTION2_H_
ooooo-youwillsee/leetcode
0938-Range-Sum-of-BST/cpp_0938/Solution1.h
// // Created by ooooo on 2019/12/31. // #ifndef CPP_0938_SOLUTION1_H #define CPP_0938_SOLUTION1_H #include "TreeNode.h" class Solution { public: int rangeSumBST2(TreeNode *root, int L, int R) { if (!root) return 0; if (root->val < L) return rangeSumBST(root->right, L, R); if (root->val > R) return rangeSumBST(root->left, L, R); return rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R) + root->val; } int rangeSumBST(TreeNode *root, int L, int R) { if (!root) return 0; int x = root->val >= L && root->val <= R ? root->val : 0; return rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R) + x; } }; #endif //CPP_0938_SOLUTION1_H