From 6e0b93e5477f2d415d053aa5569054bd7617e9b8 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 26 Jan 2023 22:12:59 +0100 Subject: [PATCH 01/70] Add Path Sum C++ Solution --- Problems/.DS_Store | Bin 6148 -> 6148 bytes Problems/04-Path-Sum/Path-Sum.cpp | 21 +++++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 Problems/04-Path-Sum/Path-Sum.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index 5f39ce616c0394bf0adeaf5329e2c80960c17c8c..6401c378aabd81149e638cc5d39c9bf4924977f2 100644 GIT binary patch delta 294 zcmZoMXfc=|#>B!ku~2NHo+2af#(>?7iytsEG4f8Hz$CL-gDIa;Rh+?q!I(jp!HFS} zAqR-_7?K%M8B)L^nLu75LlHyeWH~0;dZJVU^@RX+q%x%D=DWD0l$InjFx>y{wlMi9 z0|NueCZr&lphdh9ldG6bS%1tvH8FK#p*Q1Zb`E|HU?^<9$o!poGQWr;2O|Rm6VN#f KnB)qu~2NHo+2aH#(>?7j9il^u*huIV995kJfBTM_Pg7{3~cFI zA+;gAsqKE>A}tFt41<&Na|<>La)_}^Y*5|I&cV+CGziH5&ODi4#E}E2gMpEOfn{@q H$Qot +using namespace std; +/** + * 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 hasPathSum(TreeNode* root, int targetSum) { + if (root == nullptr) return false; + if (root->left == nullptr and root->right == nullptr) return root->val == targetSum; + return hasPathSum(root->left, targetSum-root->val) or hasPathSum(root->right, targetSum-root->val); + } +}; \ No newline at end of file From 8b8e92b990b011c0808352964619cfceb53c3d8a Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 26 Jan 2023 22:14:35 +0100 Subject: [PATCH 02/70] Update Readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index c951557..7e22d05 100644 --- a/README.md +++ b/README.md @@ -9,4 +9,6 @@ Solutions in various programming languages are provided. Enjoy it. 1. 2023/01/23 [#100 Same Tree ](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/01-Same-Tree): Tree, Recursive 2. 2023/01/24 [#101 Symmetric Tree ](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/02-Symmetric-Tree): Tree, Recursive 3. 2023/01/25 [#110 Balanced Binary Tree](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/03-Balanced-Binary-Tree): Tree, Recursive +4. 2023/01/26 [#112 Path Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/04-Path-Sum): Tree, Recursive + From b8c09bcb5a40983338e2d0a8621af4d048e2e226 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Fri, 27 Jan 2023 17:35:03 +0100 Subject: [PATCH 03/70] Add Path Sum TS Solution --- Problems/04-Path-Sum/Path-Sum.ts | 52 ++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Problems/04-Path-Sum/Path-Sum.ts diff --git a/Problems/04-Path-Sum/Path-Sum.ts b/Problems/04-Path-Sum/Path-Sum.ts new file mode 100644 index 0000000..df589f4 --- /dev/null +++ b/Problems/04-Path-Sum/Path-Sum.ts @@ -0,0 +1,52 @@ + /** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + + /** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + + function hasPathSum(root: TreeNode | null, targetSum: number): boolean { + if(!root) return false; + let res: boolean = false; + let sum: number = 0; + //不是简洁的写法,但是回溯思路比较清晰 + function dfs(node: TreeNode | null) { + if(!node) return; + if(node.left === null && node.right === null){ + if(sum + node.val === targetSum){ + res = true; + return + } + } + sum += node.val; + dfs(node.left); + sum -= node.val; + + sum += node.val; + dfs(node.right); + sum -= node.val; + } + dfs(root); + return res; +} \ No newline at end of file From d88f097fe411e9d2d98c3c1829cb8800f84a7143 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 27 Jan 2023 21:33:17 +0100 Subject: [PATCH 04/70] Add Weekly Contest 329 --- Problems/.DS_Store | Bin 6148 -> 6148 bytes .../Alternating-Digit-Sum.cpp | 16 ++++++++ ...twise-Operations-to-Make-Strings-Equal.cpp | 16 ++++++++ .../Minimum-Cost-to-Split-an-Array.cpp | 36 ++++++++++++++++++ .../Sort-the-Students-by-Their-Kth-Score.cpp | 9 +++++ README.md | 6 +++ 6 files changed, 83 insertions(+) create mode 100644 Problems/Weekly-Contest-329/Alternating-Digit-Sum.cpp create mode 100644 Problems/Weekly-Contest-329/Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp create mode 100644 Problems/Weekly-Contest-329/Minimum-Cost-to-Split-an-Array.cpp create mode 100644 Problems/Weekly-Contest-329/Sort-the-Students-by-Their-Kth-Score.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index 6401c378aabd81149e638cc5d39c9bf4924977f2..d3ac7d1b31a10f52b7673b83c90fae9b76550efe 100644 GIT binary patch delta 215 zcmZoMXfc@J&nUDpU^g?P(Bug$GMhD6%9-l984MUq7<3r|7!nyu7&3sYV1`nL+?;g7 z;N<+=0tN)Yp)xn$#U-V*B$-J97t{_+C=$Eh{) delta 41 xcmZoMXfc@J&&azmU^g=(@8k(AGMhD6%9$p+vrDqfJ~c6QW1% +using namespace std; +class Solution { +public: + int alternateDigitSum(int n) { + std::string s = to_string(n); + int sum = 0; + int sign = 1; + for (int i = 0 ; i < s.length(); i++) + { + sum += sign * (s[i] - '0'); + sign *= -1; + } + return sum; + } +}; \ No newline at end of file diff --git a/Problems/Weekly-Contest-329/Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp b/Problems/Weekly-Contest-329/Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp new file mode 100644 index 0000000..9551018 --- /dev/null +++ b/Problems/Weekly-Contest-329/Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +class Solution { +public: + bool makeStringsEqual(string s, string target) { + bool has1_s = false, has1_target = false; + for (int i = 0; i < s.length(); i++) + { + if (s[i] == '1') has1_s = true; + if (target[i] == '1') has1_target = true; + } + return (s == target or (has1_s and has1_target)); + } +}; + diff --git a/Problems/Weekly-Contest-329/Minimum-Cost-to-Split-an-Array.cpp b/Problems/Weekly-Contest-329/Minimum-Cost-to-Split-an-Array.cpp new file mode 100644 index 0000000..c3ce591 --- /dev/null +++ b/Problems/Weekly-Contest-329/Minimum-Cost-to-Split-an-Array.cpp @@ -0,0 +1,36 @@ +#include +uisng namespace std; + +class Solution { +public: + int minCost(vector& nums, int k) { + int n = nums.size(); + + vector dp(n+1, 0); + dp[0] = k; + for (int i = 1; i < n; i++) + { + unordered_map counter; + int numberOfUniqueElement = 0; + long long minCost = -1; + for (int j = i; j >= 0; j--) + { + counter[nums[j]]++; + if (counter[nums[j]] == 1) numberOfUniqueElement++; + if (counter[nums[j]] == 2) numberOfUniqueElement--; + long long importance = k + (i - j + 1 - numberOfUniqueElement); + + long long cost = (j == 0)?importance:importance + dp[j-1]; + + if (minCost == -1) minCost = cost; + else if (minCost > cost) + { + minCost = cost; + } + dp[i] = minCost; + } + } + + return dp[n-1]; + } +}; diff --git a/Problems/Weekly-Contest-329/Sort-the-Students-by-Their-Kth-Score.cpp b/Problems/Weekly-Contest-329/Sort-the-Students-by-Their-Kth-Score.cpp new file mode 100644 index 0000000..0ad84f2 --- /dev/null +++ b/Problems/Weekly-Contest-329/Sort-the-Students-by-Their-Kth-Score.cpp @@ -0,0 +1,9 @@ +#include +using namespace std; +class Solution { +public: + vector> sortTheStudents(vector>& score, int k) { + sort(score.begin(), score.end(), [k](const vector& a, const vector& b){ return a[k] > b[k]; }); + return score; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index 7e22d05..88d92bb 100644 --- a/README.md +++ b/README.md @@ -12,3 +12,9 @@ Solutions in various programming languages are provided. Enjoy it. 4. 2023/01/26 [#112 Path Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/04-Path-Sum): Tree, Recursive +## Weekly Contest + +### Weekly Contest 329() +* [#2544 Alternating Digit Sum]: Maths +* [#2545 Sort the Students by Their Kth Score]: Customized Sort +* \ No newline at end of file From fc7d24adf2634b12fa25745986a9fe0b0407760d Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 27 Jan 2023 21:37:14 +0100 Subject: [PATCH 05/70] Update Readme --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 88d92bb..3ef946f 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@ Solutions in various programming languages are provided. Enjoy it. ## Weekly Contest -### Weekly Contest 329() +### Weekly Contest 329(https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/Weekly-Contest-329) * [#2544 Alternating Digit Sum]: Maths * [#2545 Sort the Students by Their Kth Score]: Customized Sort -* \ No newline at end of file +* [#2546 Apply Bitwise Operations to Make Strings Equal]: Maths +* [#2547 Minimum Cost to Split an Array]: DP \ No newline at end of file From f85df9f2e605f1d74e0224093a3991219de341d4 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 27 Jan 2023 21:38:27 +0100 Subject: [PATCH 06/70] Update Readme --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 3ef946f..a738eec 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,8 @@ Solutions in various programming languages are provided. Enjoy it. ## Weekly Contest -### Weekly Contest 329(https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/Weekly-Contest-329) -* [#2544 Alternating Digit Sum]: Maths -* [#2545 Sort the Students by Their Kth Score]: Customized Sort -* [#2546 Apply Bitwise Operations to Make Strings Equal]: Maths -* [#2547 Minimum Cost to Split an Array]: DP \ No newline at end of file +### [Weekly Contest 329](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/Weekly-Contest-329) +* #2544 Alternating Digit Sum: Maths +* #2545 Sort the Students by Their Kth Score: Customized Sort +* #2546 Apply Bitwise Operations to Make Strings Equal: Maths +* #2547 Minimum Cost to Split an Array: DP \ No newline at end of file From 9bf6ae724316ea49d1b27b31adfbc6f0024d2616 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 27 Jan 2023 22:33:02 +0100 Subject: [PATCH 07/70] Add Minimum Absolute Difference in BST C++ Solution --- Problems/.DS_Store | Bin 6148 -> 8196 bytes .../Minimum-Absolute-Difference-in-BST.cpp | 40 ++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 Problems/05-Minimum-Absolute-Difference-in-BST/Minimum-Absolute-Difference-in-BST.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index d3ac7d1b31a10f52b7673b83c90fae9b76550efe..4113f0c99ed71822b9cfce749a8e36f01e06f03f 100644 GIT binary patch delta 386 zcmZoMXmOBWU|?W$DortDU;r^WfEYvza8E20o2aMAD6uhMH}hr%jz7$c**Q2SHn1>C zOrF3Zvsr^hp1EF#A)Fx<2(uY-7%CZb8JrpN8S)rPfFi{}QkTJ)!HB^!C*3eOIX|}m zXeta4r7t(%#U-V*B$5Co5ygpBO^ew%I0Tu2dVxTI8%VfxY R1}2CFAUhd0$Mei#1_0?#8V3LX diff --git a/Problems/05-Minimum-Absolute-Difference-in-BST/Minimum-Absolute-Difference-in-BST.cpp b/Problems/05-Minimum-Absolute-Difference-in-BST/Minimum-Absolute-Difference-in-BST.cpp new file mode 100644 index 0000000..548d1c4 --- /dev/null +++ b/Problems/05-Minimum-Absolute-Difference-in-BST/Minimum-Absolute-Difference-in-BST.cpp @@ -0,0 +1,40 @@ +/** + * 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: + TreeNode* prev = nullptr; + void dfs(TreeNode* root, int& minDifference) + { + if (root->left) + { + dfs(root->left, minDifference); + } + + if (prev != nullptr) + { + minDifference = min(minDifference, abs(root->val - prev->val)); + } + + prev = root; + + if (root->right) + { + dfs(root->right, minDifference); + } + } + + int getMinimumDifference(TreeNode* root) { + int minDifference = INT_MAX; + dfs(root, minDifference); + return minDifference; + } +}; \ No newline at end of file From 82dec2f97129a3fcd1e8640c4e8e734101c66d5a Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 27 Jan 2023 22:34:33 +0100 Subject: [PATCH 08/70] Update Readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a738eec..fba4575 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Solutions in various programming languages are provided. Enjoy it. 2. 2023/01/24 [#101 Symmetric Tree ](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/02-Symmetric-Tree): Tree, Recursive 3. 2023/01/25 [#110 Balanced Binary Tree](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/03-Balanced-Binary-Tree): Tree, Recursive 4. 2023/01/26 [#112 Path Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/04-Path-Sum): Tree, Recursive - +5. 2023/01/27 [#530 Minimum Absolute Difference in BST](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/05-Minimum-Absolute-Difference-in-BST): BST, Tree Traversal ## Weekly Contest From c78776fbc38f826adcc04c9a0b903f5d9add79eb Mon Sep 17 00:00:00 2001 From: jackyu Date: Sat, 28 Jan 2023 15:47:43 +0800 Subject: [PATCH 09/70] inorder traversal --- .../Q530.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Problems/05-Minimum-Absolute-Difference-in-BST/Q530.cpp diff --git a/Problems/05-Minimum-Absolute-Difference-in-BST/Q530.cpp b/Problems/05-Minimum-Absolute-Difference-in-BST/Q530.cpp new file mode 100644 index 0000000..0c21b5a --- /dev/null +++ b/Problems/05-Minimum-Absolute-Difference-in-BST/Q530.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int getMinimumDifference(TreeNode* root) { + vector sorted; + inorder(root,sorted); + int min_diff = sorted.back(); // the largest one + for(int i=1; i& sorted){ // Time complexity : O(n) + if(!root) return; + inorder(root->left,sorted); + sorted.push_back(root->val); + inorder(root->right,sorted); + } +}; \ No newline at end of file From 5b79cc121b9c80421706e74823ced1ea45daaac8 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 29 Jan 2023 00:57:10 +0100 Subject: [PATCH 10/70] Add LCA C++ Solution --- Problems/.DS_Store | Bin 8196 -> 8196 bytes ...ommon-Ancestor-of-a-Binary-Search-Tree.cpp | 26 ++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index 4113f0c99ed71822b9cfce749a8e36f01e06f03f..8319aad0da8c29d5c3119b8322274a5b6a80f869 100644 GIT binary patch literal 8196 zcmeHM&2H2%5FSGjmC6CQ&_fTo^tcjB0f}2!QcfTtr4mP2vRPWuY%017>ILN$I3po= z3Elu9@e)1tRF2RexbTf_B14>#MayahhYsSfi8_EsDfM*E2Hv{xa_2-J$JF5XdwBb8@*e(< zt)cY&4>fpjSO5-J;paVgJfw9z#WbSK^EK9RI({9!`uH-1U$va2{lDS#*trZlufe*z z`1S^<8C!|>oAijbDMt)Pu%GY4B8>L&mm-3xjcZFwakOJv^Y}JF?G7Ht`=3_d0gs7l zFERWJ+C8|pf%|o!dIuOk2cFwNxkb0|#=Aidd^rYY_3&5@)LUr#XuGH#jr@<*6hi|) zC;Cg{n@j)xF@;&3IDK1sbM_calVZOppErLd;XX0sb2)h`Txsr9VZ); P^S| z;N<+=0tN&?kval == p->val || root->val == q->val) + { + return root; + } + + auto LCA_left = lowestCommonAncestor(root->left, p, q); + auto LCA_right = lowestCommonAncestor(root->right, p, q); + + if (LCA_left && LCA_right) return root; + return (LCA_left)?(LCA_left):(LCA_right); + } +}; \ No newline at end of file From d5b4bde9f5c723438626d9c22c6a1ddb2e4a4cf2 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 29 Jan 2023 00:59:05 +0100 Subject: [PATCH 11/70] Update Readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index fba4575..280e2db 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Solutions in various programming languages are provided. Enjoy it. 3. 2023/01/25 [#110 Balanced Binary Tree](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/03-Balanced-Binary-Tree): Tree, Recursive 4. 2023/01/26 [#112 Path Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/04-Path-Sum): Tree, Recursive 5. 2023/01/27 [#530 Minimum Absolute Difference in BST](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/05-Minimum-Absolute-Difference-in-BST): BST, Tree Traversal +6. 2023/01/28 [#235 Lowest Common Ancestor of a Binary Search Tree](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree): Tree, LCA ## Weekly Contest From 7b668f7c0f769e1959ee71c0d2320cc0ebe580aa Mon Sep 17 00:00:00 2001 From: jackyu Date: Sun, 29 Jan 2023 11:39:38 +0800 Subject: [PATCH 12/70] LCA python solution --- .../Q235-Lowest-Common-LCA.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Q235-Lowest-Common-LCA.py diff --git a/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Q235-Lowest-Common-LCA.py b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Q235-Lowest-Common-LCA.py new file mode 100644 index 0000000..a41a8d4 --- /dev/null +++ b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Q235-Lowest-Common-LCA.py @@ -0,0 +1,11 @@ +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + cur = root + + while cur: + if p.val > cur.val and q.val > cur.val: + cur = cur.right + elif p.val < cur.val and q.val < cur.val: + cur = cur.left + else: + return cur \ No newline at end of file From cde78a5b66041976c0681e217b20870e30851494 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Mon, 30 Jan 2023 10:12:01 +0100 Subject: [PATCH 13/70] Add 530 TS Solution --- .../530-Minimum-Absolute-Difference-in-BST.ts | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Problems/05-Minimum-Absolute-Difference-in-BST/530-Minimum-Absolute-Difference-in-BST.ts diff --git a/Problems/05-Minimum-Absolute-Difference-in-BST/530-Minimum-Absolute-Difference-in-BST.ts b/Problems/05-Minimum-Absolute-Difference-in-BST/530-Minimum-Absolute-Difference-in-BST.ts new file mode 100644 index 0000000..45f4280 --- /dev/null +++ b/Problems/05-Minimum-Absolute-Difference-in-BST/530-Minimum-Absolute-Difference-in-BST.ts @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function getMinimumDifference(root: TreeNode | null): number { + let res: number = Infinity; + let preNodeVal: number; + //二叉搜索树采用中序遍历,其实就是一个有序数组。 + function recur(node: TreeNode | null) { + if(node === null) return + recur(node.left); + if(preNodeVal!==null && Math.abs(preNodeVal-node.val) < res){ + res = Math.abs(preNodeVal-node.val); + } + preNodeVal = node.val; + recur(node.right); + } + recur(root); + return res; +}; \ No newline at end of file From 2443621553285d2cb3da09dbc1c75f70906d29c4 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Mon, 30 Jan 2023 10:44:44 +0100 Subject: [PATCH 14/70] Add 235 TS Solution --- .../235-LCA-BST.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235-LCA-BST.ts diff --git a/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235-LCA-BST.ts b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235-LCA-BST.ts new file mode 100644 index 0000000..9260745 --- /dev/null +++ b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235-LCA-BST.ts @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { + while (root) { + if (root.val < p.val && root.val < q.val) { + root = root.right; + } + else if (root.val > p.val && root.val > q.val) { + root = root.left; + } else { + return root; + } + } +} \ No newline at end of file From a7f2750610f9473375f08e7b27d4cf067f9df88b Mon Sep 17 00:00:00 2001 From: qinyii Date: Mon, 30 Jan 2023 19:02:31 +0100 Subject: [PATCH 15/70] python --- Problems/01-Same-Tree/Same_tree2.py | 17 ++++++++++++++ Problems/02-Symmetric-Tree/symetric_tree.py | 18 +++++++++++++++ .../balanced_binary_tree2.py | 22 +++++++++++++++++++ Problems/04-Path-Sum/path_sum.py | 18 +++++++++++++++ .../mini_abs_diff.py | 22 +++++++++++++++++++ .../lowest_common_ancestor.py | 18 +++++++++++++++ 6 files changed, 115 insertions(+) create mode 100644 Problems/01-Same-Tree/Same_tree2.py create mode 100644 Problems/02-Symmetric-Tree/symetric_tree.py create mode 100644 Problems/03-Balanced-Binary-Tree/balanced_binary_tree2.py create mode 100644 Problems/04-Path-Sum/path_sum.py create mode 100644 Problems/05-Minimum-Absolute-Difference-in-BST/mini_abs_diff.py create mode 100644 Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/lowest_common_ancestor.py diff --git a/Problems/01-Same-Tree/Same_tree2.py b/Problems/01-Same-Tree/Same_tree2.py new file mode 100644 index 0000000..30cf25d --- /dev/null +++ b/Problems/01-Same-Tree/Same_tree2.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isSameTree(self, p, q) : + """ + :type p: TreeNode + :type q: TreeNode + :rtype: bool + """ + if(not p and not q): return True + elif p and q and p.val== q.val: + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) + else: return False diff --git a/Problems/02-Symmetric-Tree/symetric_tree.py b/Problems/02-Symmetric-Tree/symetric_tree.py new file mode 100644 index 0000000..357d578 --- /dev/null +++ b/Problems/02-Symmetric-Tree/symetric_tree.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isSymmetric(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + def compare(n1,n2): + if not n1 and not n2 : return True + elif not n1 or not n2 : return False + elif n1.val != n2.val : return False + return compare(n1.left,n2.right) and compare(n1.right,n2.left) + return compare(root,root) \ No newline at end of file diff --git a/Problems/03-Balanced-Binary-Tree/balanced_binary_tree2.py b/Problems/03-Balanced-Binary-Tree/balanced_binary_tree2.py new file mode 100644 index 0000000..57e5b35 --- /dev/null +++ b/Problems/03-Balanced-Binary-Tree/balanced_binary_tree2.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isBalanced(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + n = self.diff(root) + if n == -1: return False + else: return True + + def diff(self,root): + if root == None: return 0 + hautL = self.diff(root.left) + hautR = self.diff(root.right) + if hautL >= 0 and hautR >= 0 and abs(hautL-hautR) <= 1: return max(hautR,hautL)+1 + else: return -1 \ No newline at end of file diff --git a/Problems/04-Path-Sum/path_sum.py b/Problems/04-Path-Sum/path_sum.py new file mode 100644 index 0000000..072f988 --- /dev/null +++ b/Problems/04-Path-Sum/path_sum.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def hasPathSum(self, root, targetSum): + """ + :type root: TreeNode + :type targetSum: int + :rtype: bool + """ + if root == None : return False + newTarget = targetSum-root.val + if root.left == None and root.right == None and newTarget == 0: + return True + return self.hasPathSum(root.left,newTarget) or self.hasPathSum(root.right,newTarget) \ No newline at end of file diff --git a/Problems/05-Minimum-Absolute-Difference-in-BST/mini_abs_diff.py b/Problems/05-Minimum-Absolute-Difference-in-BST/mini_abs_diff.py new file mode 100644 index 0000000..1f2d28f --- /dev/null +++ b/Problems/05-Minimum-Absolute-Difference-in-BST/mini_abs_diff.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def getMinimumDifference(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def inorder(root): + if not root : return [] + return inorder(root.left)+[root.val]+inorder(root.right) + + mini = float("inf") + inord = inorder(root) + for i in range(1,len(inord)): + mini = min(mini,inord[i]-inord[i-1]) + return mini + \ No newline at end of file diff --git a/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/lowest_common_ancestor.py b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/lowest_common_ancestor.py new file mode 100644 index 0000000..87c5f0f --- /dev/null +++ b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/lowest_common_ancestor.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def lowestCommonAncestor(self, root, p, q): + """ + :type root: TreeNode + :type p: TreeNode + :type q: TreeNode + :rtype: TreeNode + """ + if max(p.val,q.val)root.val: return self.lowestCommonAncestor(root.right,p,q) + return root \ No newline at end of file From c546bd25d349c6465b755b0d922fc5de0954bd32 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 30 Jan 2023 23:02:53 +0100 Subject: [PATCH 16/70] Add C++ 07 08 Solution --- Problems/.DS_Store | Bin 8196 -> 10244 bytes ...ll-Elements-in-Two-Binary-Search-Trees.cpp | 49 ++++++++++++++++++ .../Search-Insert-Position.cpp | 17 ++++++ 3 files changed, 66 insertions(+) create mode 100644 Problems/07-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.cpp create mode 100644 Problems/08-Search-Insert-Position/Search-Insert-Position.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index 8319aad0da8c29d5c3119b8322274a5b6a80f869..efd4aea1d102fbbdfda181f9d35f4160a6926cf2 100644 GIT binary patch delta 760 zcmZp1XbF&DU|?W$DortDU{C-uIe-{M3-C-V6q~50$f&Y0U^hRb%H#MO2v&b_hg<@lJ7>WxrFg(Q!3>ymuT`b;(%AojQ z%Y<1#AHZdh9EBoNkTH3mnAzq%V&04!8-B0~GDCt;fg4D>f?{f8;dkcA{4#+eOpy4~ p04ZQ(0J;STCKt%`Ze|pn#yHd?&WoWqHyYn>7UT**4FY zC}0$11}Xsp32q?a3R1nX@H_Klew9EDMu-^ getAllElements(TreeNode* root1, TreeNode* root2) { + vector ans; + stack s1, s2; + + while (root1 || root2 || !s1.empty() || !s2.empty()) + { + while (root1) + { + s1.push(root1); + root1 = root1->left; + } + + while (root2) + { + s2.push(root2); + root2 = root2->left; + } + + if(s2.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val)) + { + root1 = s1.top(); + s1.pop(); + ans.push_back(root1->val); + root1 = root1->right; + } + else + { + root2 = s2.top(); + s2.pop(); + ans.push_back(root2->val); + root2 = root2->right; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/08-Search-Insert-Position/Search-Insert-Position.cpp b/Problems/08-Search-Insert-Position/Search-Insert-Position.cpp new file mode 100644 index 0000000..a6777f6 --- /dev/null +++ b/Problems/08-Search-Insert-Position/Search-Insert-Position.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int searchInsert(vector& nums, int target) { + int left = 0; + int right = nums.size()-1; + while (left <= right) + { + int mid = (right - left) / 2 + left; + if (nums[mid] == target) return mid; + if (nums[mid] < target) left = mid + 1; + else right = mid - 1; + } + + if (right >= 0 && nums[right] > target) return right; + else return right + 1; + } +}; \ No newline at end of file From 8d2011ca6c7b63c5314bbe529c470f90506f26bb Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 30 Jan 2023 23:05:04 +0100 Subject: [PATCH 17/70] Update Readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 280e2db..251029c 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ Solutions in various programming languages are provided. Enjoy it. 4. 2023/01/26 [#112 Path Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/04-Path-Sum): Tree, Recursive 5. 2023/01/27 [#530 Minimum Absolute Difference in BST](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/05-Minimum-Absolute-Difference-in-BST): BST, Tree Traversal 6. 2023/01/28 [#235 Lowest Common Ancestor of a Binary Search Tree](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree): Tree, LCA +7. 2023/01/29 [#1305 All Elements in Two Binary Search Trees](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/07-All-Elements-in-Two-Binary-Search-Trees): Tree Traversal +8. 2023/01/30 [#35 Search Insert Position](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/08-Search-Insert-Position): Binary Search ## Weekly Contest From 186f431ee016fdb76e640a9989f788aec2eff785 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Tue, 31 Jan 2023 15:21:53 +0100 Subject: [PATCH 18/70] add 1305 TS solution --- .../1305-All-Elements-BST.ts | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Problems/07-All-Elements-in-Two-Binary-Search-Trees/1305-All-Elements-BST.ts diff --git a/Problems/07-All-Elements-in-Two-Binary-Search-Trees/1305-All-Elements-BST.ts b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/1305-All-Elements-BST.ts new file mode 100644 index 0000000..0170cbc --- /dev/null +++ b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/1305-All-Elements-BST.ts @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function getAllElements(root1: TreeNode | null, root2: TreeNode | null): number[] { + function getElements(node: TreeNode | null): number[] { + let res: number[] = []; + let queue: TreeNode[] = []; + while(node || queue.length) { + if(node){ + queue.push(node); + node = node.left; + continue; + } + node = queue.pop(); + res.push(node.val); + node = node.right; + } + return res; + } + let res :number[] = []; + let arr1 = getElements(root1); + let ptr1 = arr1.length-1; + let arr2 = getElements(root2); + let ptr2 = arr2.length-1; + let ptr = arr1.length + arr2.length - 1; + while(ptr >= 0){ + if(ptr2<0 || arr1[ptr1] > arr2[ptr2]) { + res[ptr--] = arr1[ptr1--]; + } else { + res[ptr--] = arr2[ptr2--]; + } + } + return res; +}; \ No newline at end of file From 5f0f3fbf1e07b6b5423253bfe40bd9b848eaae3b Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Tue, 31 Jan 2023 16:23:17 +0100 Subject: [PATCH 19/70] add 35 TS solution --- .../Search-Insert-Position.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Problems/08-Search-Insert-Position/Search-Insert-Position.ts diff --git a/Problems/08-Search-Insert-Position/Search-Insert-Position.ts b/Problems/08-Search-Insert-Position/Search-Insert-Position.ts new file mode 100644 index 0000000..d07d78c --- /dev/null +++ b/Problems/08-Search-Insert-Position/Search-Insert-Position.ts @@ -0,0 +1,14 @@ +function searchInsert(nums: number[], target: number): number { + + let left: number = 0; + let right: number = nums.length; + let mid: number + while (left < right) { + mid = left + Math.floor((right - left) / 2); + if (nums[mid] >= target) right = mid; + else left = mid + 1; + + } + return left; + +}; \ No newline at end of file From 85ea7978b8eecbca426aad413c78446d316298f1 Mon Sep 17 00:00:00 2001 From: qinyii Date: Tue, 31 Jan 2023 22:03:34 +0100 Subject: [PATCH 20/70] Add python Solution --- .../All_elements.py | 26 +++++++++++++++++++ .../Search-Insert-Position.py | 21 +++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 Problems/07-All-Elements-in-Two-Binary-Search-Trees/All_elements.py create mode 100644 Problems/08-Search-Insert-Position/Search-Insert-Position.py diff --git a/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All_elements.py b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All_elements.py new file mode 100644 index 0000000..85d973b --- /dev/null +++ b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All_elements.py @@ -0,0 +1,26 @@ +class Solution: + def getAllElements(self, root1, root2) : + def inorder(node, res): + if node: + inorder(node.left, res) + res.append(node.val) + inorder(node.right, res) + res,inor1,inor2 = [],[],[] + inorder(root1,inor1) + inorder(root2,inor2) + l1, r1 = 0, len(inor1) + l2, r2 = 0, len(inor2) + while True: + if l1 == r1: + res.extend(inor2[l2:]) + break + if l2 == r2: + res.extend(inor1[l1:]) + break + if inor1[l1] < inor2[l2]: + res.append(inor1[l1]) + l1 += 1 + else: + res.append(inor2[l2]) + l2 += 1 + return res \ No newline at end of file diff --git a/Problems/08-Search-Insert-Position/Search-Insert-Position.py b/Problems/08-Search-Insert-Position/Search-Insert-Position.py new file mode 100644 index 0000000..c7a3275 --- /dev/null +++ b/Problems/08-Search-Insert-Position/Search-Insert-Position.py @@ -0,0 +1,21 @@ +class Solution(object): + def searchInsert(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + l = len(nums) + i = 0 + j = l-1 + res = l + while (i<=j): + mid = (i+j)/2 + if target == nums[mid]: + res = mid + break + elif target < nums[mid]: + res = mid + j = mid -1 + else: i = mid+1 + return res From 85aa1e3fe067fbc2fa4a9427e35658c705366a79 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 1 Feb 2023 07:06:35 +0100 Subject: [PATCH 21/70] Add C++ 09 Solution --- Problems/.DS_Store | Bin 10244 -> 10244 bytes .../Longest-Subsequence-With-Limited-Sum.cpp | 32 ++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 Problems/09-Longest-Subsequence-With-Limited-Sum/Longest-Subsequence-With-Limited-Sum.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index efd4aea1d102fbbdfda181f9d35f4160a6926cf2..f0c4b9a82ee642459599a38b3e2e128a0abc10ec 100644 GIT binary patch delta 429 zcmZn(XbG6$ÄU^hRb#^ebCGMhC7_&Mq&84MUK7<3te8B!S%8HyN^88U!8Plh~( zVxUM7LkW-p8*WdhlmKvrH(x?yl~er^E+0+3-!ZoZ34N@;ybG6Tc?zwfq8m<2SA zEMroD#*l3aJJe5;dn7*Bv!!c=)Q0e;w)=gHw8Y{|6nTjI!507DICX6s(D`WcaED=) UFUUX-#m#k+k*u5975=gV09^NMn*aa+ delta 127 zcmZn(XbG6$C7U^hRb%H#Oa|;*{04kH4@8XhD pT9VAbaR2YSEfZz|6~JXuaL7!yk^H=Qy;KD2#s&k%&Fl()*#R(>BQ*d3 diff --git a/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest-Subsequence-With-Limited-Sum.cpp b/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest-Subsequence-With-Limited-Sum.cpp new file mode 100644 index 0000000..9c1d67f --- /dev/null +++ b/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest-Subsequence-With-Limited-Sum.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + vector answerQueries(vector& nums, vector& queries) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector prefixSum(n+1, 0); + for (int i = 1; i <= n; i++) prefixSum[i] = prefixSum[i-1] + nums[i-1]; + + int m = queries.size(); + vector ans(m, 0); + + for (int i = 0; i < m; i++) + { + int left = 1, right = n; + ans[i] = 0; + while (left <= right) + { + int mid = (right - left) / 2 + left; + if (prefixSum[mid] <= queries[i]) + { + ans[i] = mid; + left = mid + 1; + } + else + { + right = mid - 1; + } + } + } + return ans; + } +}; \ No newline at end of file From 8220a0ec9cb539d2cab625d95d9a917b83fe3c42 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 1 Feb 2023 07:09:14 +0100 Subject: [PATCH 22/70] Update Readme --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 251029c..2d13afb 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Solutions in various programming languages are provided. Enjoy it. 6. 2023/01/28 [#235 Lowest Common Ancestor of a Binary Search Tree](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree): Tree, LCA 7. 2023/01/29 [#1305 All Elements in Two Binary Search Trees](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/07-All-Elements-in-Two-Binary-Search-Trees): Tree Traversal 8. 2023/01/30 [#35 Search Insert Position](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/08-Search-Insert-Position): Binary Search +9. 2023/01/31 [#2389 Longest Subsequence With Limited Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/09-Longest-Subsequence-With-Limited-Sum): Binary Search ## Weekly Contest @@ -21,4 +22,4 @@ Solutions in various programming languages are provided. Enjoy it. * #2544 Alternating Digit Sum: Maths * #2545 Sort the Students by Their Kth Score: Customized Sort * #2546 Apply Bitwise Operations to Make Strings Equal: Maths -* #2547 Minimum Cost to Split an Array: DP \ No newline at end of file +* #2547 Minimum Cost to Split an Array: DP From 5ce201b6ec9355ddf87355da017be434c3db8928 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Wed, 1 Feb 2023 12:31:18 +0100 Subject: [PATCH 23/70] add 2389 ts solution --- .../2389.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Problems/09-Longest-Subsequence-With-Limited-Sum/2389.ts diff --git a/Problems/09-Longest-Subsequence-With-Limited-Sum/2389.ts b/Problems/09-Longest-Subsequence-With-Limited-Sum/2389.ts new file mode 100644 index 0000000..3804168 --- /dev/null +++ b/Problems/09-Longest-Subsequence-With-Limited-Sum/2389.ts @@ -0,0 +1,26 @@ +function answerQueries(nums: number[], queries: number[]): number[] { + nums = nums.sort((a, b) => a - b); + let prefix: number[] = [nums[0]]; + let res: number[] = []; + for (let i = 1; i < nums.length; i++) { + prefix.push(prefix[i - 1] + nums[i]); + } + + for (let target of queries) { + let left: number = 0; + let right: number = prefix.length; + let mid: number; + while (left < right) { + mid = left + Math.floor((right - left) / 2); + if (prefix[mid] > target) right = mid; + else if (prefix[mid] === target) { + left = mid + 1; + break; + } + else left = mid + 1; + } + + res.push(left); + } + return res; +}; \ No newline at end of file From 9f14d415cf8989dd3b60e8342d60f8fd1780ee2b Mon Sep 17 00:00:00 2001 From: qinyii Date: Thu, 2 Feb 2023 21:41:40 +0100 Subject: [PATCH 24/70] Add python solution --- .../Longest_Subsequence_With_Limite.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Problems/09-Longest-Subsequence-With-Limited-Sum/Longest_Subsequence_With_Limite.py diff --git a/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest_Subsequence_With_Limite.py b/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest_Subsequence_With_Limite.py new file mode 100644 index 0000000..f507dbf --- /dev/null +++ b/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest_Subsequence_With_Limite.py @@ -0,0 +1,23 @@ +import bisect + +class Solution: + def findTheDistanceValue1(self, arr1, arr2, d): + """ + :type arr1: List[int] + :type arr2: List[int] + :type d: int + :rtype: int + """ + return sum(all(abs(x - y) > d for y in arr2) for x in arr1) + + + def findTheDistanceValue(self, arr1, arr2, d): + arr2.sort() + res = 0 + for n in arr1: + i = bisect.bisect_left(arr2, n) + if (i >= len(arr2) or arr2[i]-n > d) and (i == 0 or n - arr2[i-1] > d): + res += 1 + return res + + From 59c1ff981f382517771f0f903eb9b5dd25f86902 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 2 Feb 2023 22:49:06 +0100 Subject: [PATCH 25/70] Add C++ 10 11 Solution --- Problems/.DS_Store | Bin 10244 -> 10244 bytes ...-the-Distance-Value-Between-Two-Arrays.cpp | 38 ++++++++++++++++++ .../Guess-Number-Higher-or-Lower.cpp | 31 ++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find-the-Distance-Value-Between-Two-Arrays.cpp create mode 100644 Problems/11-Guess-Number-Higher-or-Lower/Guess-Number-Higher-or-Lower.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index f0c4b9a82ee642459599a38b3e2e128a0abc10ec..3826d4bc82bf6d277320e7fdb9577d6f98b4b6da 100644 GIT binary patch delta 823 zcmZn(XbG6$RCU^hRb-sA}aGMhC7)H&VN84MUK8FU$Z81fnN7}6P18HyQ7fc#*F zQidcTJC&gj$VvsuB?C!ahH!>VpnL{cM& arr1, vector& arr2, int d) { + int m = arr2.size(); + int ans = 0; + sort(arr2.begin(), arr2.end()); + for (auto x: arr1) + { + int left = 0, right = m-1; + int index = m-1; + while (left <= right) + { + int mid = (right - left) / 2 + left; + if (arr2[mid] == x) + { + index = mid; + break; + } + else if (arr2[mid] < x) + { + left = mid + 1; + } + else // (arr2[mid] > x) + { + index = mid; + right = mid - 1; + } + } + + if (abs(arr2[index]-x) > d && (index - 1 < 0 || abs(arr2[index-1] -x) > d)) + { + ans += 1; + } + + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/11-Guess-Number-Higher-or-Lower/Guess-Number-Higher-or-Lower.cpp b/Problems/11-Guess-Number-Higher-or-Lower/Guess-Number-Higher-or-Lower.cpp new file mode 100644 index 0000000..bc8881a --- /dev/null +++ b/Problems/11-Guess-Number-Higher-or-Lower/Guess-Number-Higher-or-Lower.cpp @@ -0,0 +1,31 @@ +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * int guess(int num); + */ + +class Solution { +public: + int guessNumber(int n) { + if (n == 1) return 1; + int left = 1, right = n; + while (left <= right) + { + int mid = (right - left) / 2 + left; + int res = guess(mid); + if (res == 0) return mid; + if (res == 1) + { + left = mid + 1; + } + else + { + right = mid - 1; + } + } + return left; + } +}; \ No newline at end of file From cad2b7ce4bb425a1854fca64689da398faa3ea5b Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 2 Feb 2023 22:50:58 +0100 Subject: [PATCH 26/70] Update Readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2d13afb..7b1e5fd 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,8 @@ Solutions in various programming languages are provided. Enjoy it. 7. 2023/01/29 [#1305 All Elements in Two Binary Search Trees](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/07-All-Elements-in-Two-Binary-Search-Trees): Tree Traversal 8. 2023/01/30 [#35 Search Insert Position](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/08-Search-Insert-Position): Binary Search 9. 2023/01/31 [#2389 Longest Subsequence With Limited Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/09-Longest-Subsequence-With-Limited-Sum): Binary Search +10. 2023/02/01 [#1385 Find the Distance Value Between Two Arrays](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/10-Find-the-Distance-Value-Between-Two-Arrays): Binary Search +11. 2023/02/02 [#374 Guess Number Higher or Lower](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/11-Guess-Number-Higher-or-Lower): Binary Search ## Weekly Contest From 2d1706ac25bd1d5f28def1684a3ccafa50d4c44a Mon Sep 17 00:00:00 2001 From: qinyii Date: Fri, 3 Feb 2023 17:53:26 +0100 Subject: [PATCH 27/70] Add Python Solution(374) --- .../Find_the_Distance_Value.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distance_Value.py diff --git a/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distance_Value.py b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distance_Value.py new file mode 100644 index 0000000..9b4e62a --- /dev/null +++ b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distance_Value.py @@ -0,0 +1,25 @@ +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if num is higher than the picked number +# 1 if num is lower than the picked number +# otherwise return 0 +# def guess(num): + +class Solution(object): + def guessNumber(self, n): + """ + :type n: int + :rtype: int + """ + min, max = 1, n + while min < max: + mid = (min + max) // 2 + res = guess(mid) + if res == 0: + return mid + elif res < 0: + max = mid + else: + min = mid + 1 + + return min \ No newline at end of file From e48c4ce1e51a79c5bfe2cf6abba595fde853c9d3 Mon Sep 17 00:00:00 2001 From: qinyii Date: Fri, 3 Feb 2023 17:57:54 +0100 Subject: [PATCH 28/70] Add Python Solution(374) --- .../Guess_Number_Higher_or_Lower.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Problems/{10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distance_Value.py => 11-Guess-Number-Higher-or-Lower/Guess_Number_Higher_or_Lower.py} (100%) diff --git a/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distance_Value.py b/Problems/11-Guess-Number-Higher-or-Lower/Guess_Number_Higher_or_Lower.py similarity index 100% rename from Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distance_Value.py rename to Problems/11-Guess-Number-Higher-or-Lower/Guess_Number_Higher_or_Lower.py From a2e3965bbb9c333b62693c15f379a32be9fc3732 Mon Sep 17 00:00:00 2001 From: qinyii Date: Fri, 3 Feb 2023 18:04:41 +0100 Subject: [PATCH 29/70] Add python solution --- .../Find_the_Distane_value.py} | 2 -- 1 file changed, 2 deletions(-) rename Problems/{09-Longest-Subsequence-With-Limited-Sum/Longest_Subsequence_With_Limite.py => 10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distane_value.py} (99%) diff --git a/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest_Subsequence_With_Limite.py b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distane_value.py similarity index 99% rename from Problems/09-Longest-Subsequence-With-Limited-Sum/Longest_Subsequence_With_Limite.py rename to Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distane_value.py index f507dbf..aeec29e 100644 --- a/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest_Subsequence_With_Limite.py +++ b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distane_value.py @@ -19,5 +19,3 @@ def findTheDistanceValue(self, arr1, arr2, d): if (i >= len(arr2) or arr2[i]-n > d) and (i == 0 or n - arr2[i-1] > d): res += 1 return res - - From 04cff3228f6e0f523858594ff732a6dea9992b10 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 3 Feb 2023 23:29:08 +0100 Subject: [PATCH 30/70] Add C++ 12 Solution --- Problems/.DS_Store | Bin 10244 -> 10244 bytes ...st-Position-of-Element-in-Sorted-Array.cpp | 48 ++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find-First-and-Last-Position-of-Element-in-Sorted-Array.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index 3826d4bc82bf6d277320e7fdb9577d6f98b4b6da..adf1f0ae978907b896eed70139ebb861ff1adc78 100644 GIT binary patch delta 356 zcmZn(XbG6$&uFwUU^hRb(c}pNGMhC7(s}CT84Q6?m%*K(lp&R&7zlM4{DACSh9n@r z2*~qb$Ye-o$bj searchRange(vector& nums, int target) { + int n = nums.size(); + int left = 0, right = n-1; + int first = -1; + while (left <= right) + { + int mid = (right - left ) / 2 + left; + if (nums[mid] == target) + { + first = mid; + right = mid - 1; + } + else if (nums[mid] < target) + { + left = mid + 1; + } + else + { + right = mid - 1; + } + } + + if (first == -1) return {-1, -1}; + + int last = -1; + left = 0, right = n-1; + while (left <= right) + { + int mid = (right - left ) / 2 + left; + if (nums[mid] == target) + { + last = mid; + left = mid + 1; + } + else if (nums[mid] < target) + { + left = mid + 1; + } + else + { + right = mid - 1; + } + } + return {first, last}; + } +}; \ No newline at end of file From 281eaa12554dea378a0cd1050d2341a4df8b8d2a Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 3 Feb 2023 23:30:36 +0100 Subject: [PATCH 31/70] Update Readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7b1e5fd..cc1b1de 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ Solutions in various programming languages are provided. Enjoy it. 9. 2023/01/31 [#2389 Longest Subsequence With Limited Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/09-Longest-Subsequence-With-Limited-Sum): Binary Search 10. 2023/02/01 [#1385 Find the Distance Value Between Two Arrays](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/10-Find-the-Distance-Value-Between-Two-Arrays): Binary Search 11. 2023/02/02 [#374 Guess Number Higher or Lower](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/11-Guess-Number-Higher-or-Lower): Binary Search +12. 2023/02/03 [#34 Find First and Last Position of Element in Sorted Array](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array): Binary Search ## Weekly Contest From 5b1c6f09d8340baddb4e428b3a47f471f1df22f8 Mon Sep 17 00:00:00 2001 From: qinyii Date: Mon, 6 Feb 2023 21:04:36 +0100 Subject: [PATCH 32/70] Add python solution (34) --- .../Find_First_and_Last_Position.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find_First_and_Last_Position.py diff --git a/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find_First_and_Last_Position.py b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find_First_and_Last_Position.py new file mode 100644 index 0000000..ed5d14a --- /dev/null +++ b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find_First_and_Last_Position.py @@ -0,0 +1,27 @@ +class Solution(object): + def searchRange(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + left = 0 + right = len(nums)-1 + def binarySearch(nums,target,left,right): + while (left <= right): + mid = left + (right-left) / 2 + if(target > nums[mid]): + left = mid + 1 + elif(target < nums[mid]): + right = mid -1 + else: + return mid + return -1 + index = binarySearch(nums,target,left,right) + if index == -1: return [-1,-1] + index2 = index + while index -1 >=0 and nums[index - 1] == target: index -=1 + while index2+1 < len(nums) and nums[index2 + 1] == target: index2 +=1 + return[index,index2] + + \ No newline at end of file From df95f778ff114e39911cd4c139027586a459feba Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 7 Feb 2023 00:46:24 +0100 Subject: [PATCH 33/70] Add C++ Solution 13 14 15 --- Problems/.DS_Store | Bin 10244 -> 12292 bytes .../Max-Consecutive-Ones-III.cpp | 29 +++++++++++++++ .../Search-a-2D-Matrix.cpp | 26 ++++++++++++++ .../Maximum-Tastiness-of-Candy-Basket.cpp | 33 ++++++++++++++++++ 4 files changed, 88 insertions(+) create mode 100644 Problems/13-Max-Consecutive-Ones-III/Max-Consecutive-Ones-III.cpp create mode 100644 Problems/14-Search-a-2D-Matrix/Search-a-2D-Matrix.cpp create mode 100644 Problems/15-Maximum-Tastiness-of-Candy-Basket/Maximum-Tastiness-of-Candy-Basket.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index adf1f0ae978907b896eed70139ebb861ff1adc78..66afaab5dbc8273b9d245f8b6ed27bd4acdb0bca 100644 GIT binary patch literal 12292 zcmeHNOKVd>6h7BhTWAFpL`1?YoIEH}qCL)vkl)%rVzLL_V8S9Y6{H+N4=>Q!q z;7?GDk_h9Jr3~JTA!SmSrYQv)5dViMP1o=*gmRpY(5NVr#{U>)CPuxXNGdsDHyuV9 zyh)~_K|4<;Gy)m{jetf#Be1p*;Jp`5d(nO`b9Jl{&EGKSq;m?FeE$jJzN~rXVDo+B|90CoeZmG!?I8e z(K`4%qBt2oNp-9d&rJ4BSg91pP$~kS6yG&nyGGbV*=y1u6DW zL=c;FPT<2Hh(V;1;$MuS_|F_k1!i?_!G-6aCwJy&foI)Yu(57X3kp4$Ib6Z z0?#b`JdAh{IjoamTL)*6P6(~Ak0^$B(}-C|j_=5iF`Y)aYm`ywq=BtD`dKh?cZYZ@ zYiMhET{WXMh2C~SZ(c}vLg*s{O__9>X98vquPY{YYE?i5DARnX&Nzv8_+ zg4xD9_7u`4oxw=qJR^W69(ih$q3?rut zJBh?Ei+MFhR~6V)!0pDv-#z;ncvQsgU{E=?Lhda%neZNX8S|fSOXT?A886q1gOI;R zA@Pd%99eVUAH1Hr0a;hbmzT0KK81W6M)rrVhd0LNPA{JCaZZB^ZT_sc3;ij0ui!@! z{b&R<0vdrehrkX<+zIQ7&*>qYANa{ckRfMJzoKrONPbu@o(=T!-}}bgB0=6nlqK!VkfxEa|6+QygiYS9yPt{Gug*aU536 zv^v)A!sExsPkqmUM_p^TF>FBX3f$QnbOfm8Jq7X<%coji4cJ%5I*=&yJLy+Q0e=%C zs(3aPS_9?hRufuv>FL+bhiyNgr>3-O>#vEeD)icrZ@?5Yt0C>Ubocvn%bA2B@7Ld9d)ERm>|y4n4F+9 Nb2FprIVPZ~rU0#%CZqrW diff --git a/Problems/13-Max-Consecutive-Ones-III/Max-Consecutive-Ones-III.cpp b/Problems/13-Max-Consecutive-Ones-III/Max-Consecutive-Ones-III.cpp new file mode 100644 index 0000000..9d6f25d --- /dev/null +++ b/Problems/13-Max-Consecutive-Ones-III/Max-Consecutive-Ones-III.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int longestOnes(vector& nums, int k) { + int n = nums.size(); + vector prefixSum(n+1, 0); + for (int i = 1; i <= n; i++) prefixSum[i] = prefixSum[i-1] + nums[i-1]; + + int res = 0; + for (int i = 1; i <= n; i++) + { + int left = i; + int right = n; + + int ans = 0; + while (left <= right) + { + int mid = (right-left)/2+left; + int num0 = (mid-i+1)-prefixSum[mid] + prefixSum[i-1]; // in [i..mid] + if (num0 <= k) {ans = mid; left = mid + 1;} + else {right = mid-1;} + } + + res = max(res, ans - i + 1); + } + + return res; + + } +}; \ No newline at end of file diff --git a/Problems/14-Search-a-2D-Matrix/Search-a-2D-Matrix.cpp b/Problems/14-Search-a-2D-Matrix/Search-a-2D-Matrix.cpp new file mode 100644 index 0000000..f752b70 --- /dev/null +++ b/Problems/14-Search-a-2D-Matrix/Search-a-2D-Matrix.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int getValue(vector>& matrix, int mid) + { + int n = matrix.size(); + int m = matrix[0].size(); + int i = mid / m; + int j = mid % m; + return matrix[i][j]; + } + + bool searchMatrix(vector>& matrix, int target) { + int n = matrix.size(); + int m = matrix[0].size(); + int left = 0, right = n * m-1; + while (left <= right) + { + int mid = (right - left)/2+left; + int value = getValue(matrix, mid); + if (target == value) return true; + if (target < value) right = mid-1; + else left = mid + 1; + } + return false; + } +}; \ No newline at end of file diff --git a/Problems/15-Maximum-Tastiness-of-Candy-Basket/Maximum-Tastiness-of-Candy-Basket.cpp b/Problems/15-Maximum-Tastiness-of-Candy-Basket/Maximum-Tastiness-of-Candy-Basket.cpp new file mode 100644 index 0000000..80024b7 --- /dev/null +++ b/Problems/15-Maximum-Tastiness-of-Candy-Basket/Maximum-Tastiness-of-Candy-Basket.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + bool check(int x, vector& price, int k) + { + int n = price.size(); + int last = 0; + int idx = 1; + for (int i = 1; i < k; i++) + { + while (idx < n && price[idx] - price[last] < x) idx++; + if (idx == n) return false; + last = idx; + idx++; + } + return true; + } + int maximumTastiness(vector& price, int k) { + sort(price.begin(), price.end()); + int left = 0, right = price[price.size()-1] - price[0]; + int ans = 0; + while (left <= right) + { + int mid = (right-left)/2+left; + if (check(mid, price, k)) + { + ans = mid; + left = mid+1; + } + else right = mid-1; + } + return ans; + } +}; \ No newline at end of file From d4a5dd2d005299e6553ac6c29343fef0d5e8ef85 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 7 Feb 2023 00:49:53 +0100 Subject: [PATCH 34/70] Update Readme --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index cc1b1de..1e1b993 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,10 @@ Solutions in various programming languages are provided. Enjoy it. 10. 2023/02/01 [#1385 Find the Distance Value Between Two Arrays](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/10-Find-the-Distance-Value-Between-Two-Arrays): Binary Search 11. 2023/02/02 [#374 Guess Number Higher or Lower](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/11-Guess-Number-Higher-or-Lower): Binary Search 12. 2023/02/03 [#34 Find First and Last Position of Element in Sorted Array](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array): Binary Search +13. 2023/02/04 [#1004. Max Consecutive Ones III](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/13-Max-Consecutive-Ones-III): Binary Search +14. 2023/02/05 [#74. Search a 2D Matrix](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/14-Search-a-2D-Matrix): Binary Search +15. 2023/02/06 [#2517. Maximum Tastiness of Candy Basket](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/15-Maximum-Tastiness-of-Candy-Basket): Binary Search + ## Weekly Contest From ca630874982947b6d0cde65279d538cdcb059f6a Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Tue, 7 Feb 2023 12:02:47 +0100 Subject: [PATCH 35/70] add 1385 ts solution --- .../1385.ts | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Problems/10-Find-the-Distance-Value-Between-Two-Arrays/1385.ts diff --git a/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/1385.ts b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/1385.ts new file mode 100644 index 0000000..b25837e --- /dev/null +++ b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/1385.ts @@ -0,0 +1,27 @@ +function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number { + + function isValid(arr: number[], target: number, d: number): boolean { + let left = 0; + let right = arr.length-1; + while(left <= right) { + let mid = left + Math.floor((right-left/2)); + if(Math.abs(target-arr[mid]) <= d) { + return false; + } else if(arr[mid] > target) { + right = mid - 1 ; + } else { + left = mid + 1; + } + } + return true; + } + arr2= arr2.sort((a,b)=>a-b); + let res = 0; + + for(let i of arr1) { + if( isValid(arr2, i, d)){ + res++; + } + } + return res; +}; \ No newline at end of file From e37d19acfaa8cd3f8db344174eb7af54e44b8bd0 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Tue, 7 Feb 2023 12:29:33 +0100 Subject: [PATCH 36/70] add 374 ts solution --- .../11-Guess-Number-Higher-or-Lower/374.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Problems/11-Guess-Number-Higher-or-Lower/374.ts diff --git a/Problems/11-Guess-Number-Higher-or-Lower/374.ts b/Problems/11-Guess-Number-Higher-or-Lower/374.ts new file mode 100644 index 0000000..9a5207b --- /dev/null +++ b/Problems/11-Guess-Number-Higher-or-Lower/374.ts @@ -0,0 +1,21 @@ +/** + * Forward declaration of guess API. + * @param {number} num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * var guess = function(num) {} + */ + + +function guessNumber(n: number): number { + let right = n + 1; + let left = 0; + while (left < right) { + let mid = Math.floor((left + right) / 2); + if (guess(mid) === 0) return mid; + else if (guess(mid) === -1) right = mid; + else if (guess(mid) === 1) left = mid + 1; + } + +}; \ No newline at end of file From 7204e6c284d4c7f7d02bcae28cf25c3239b008fa Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Thu, 9 Feb 2023 00:49:59 +0100 Subject: [PATCH 37/70] add 34 ts solution --- .../34.ts | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/34.ts diff --git a/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/34.ts b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/34.ts new file mode 100644 index 0000000..70e22c4 --- /dev/null +++ b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/34.ts @@ -0,0 +1,33 @@ +function searchRange(nums: number[], target: number): number[] { + + const max = binarySearch(nums, target, true); + + if (max !== undefined) { + const min = binarySearch(nums, target, false); + return [min!, max]; + } + return [-1, -1]; + + function binarySearch(nums: number[], target: number, flag: boolean): number | undefined { + let position: number | undefined; + let left = 0; + let right = nums.length - 1; + while (left <= right) { + let mid = Math.floor((left + right) / 2); + if (nums[mid] > target) { + right = mid - 1; + } else if (nums[mid] < target) { + left = mid + 1; + } else { + position = mid; + if (flag) { + left = left + 1; + } else { + right = right - 1; + } + } + } + return position; + } + +}; \ No newline at end of file From 4ff63bcdd4f9adab6097bba331326850c21dfac1 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Thu, 9 Feb 2023 10:28:46 +0100 Subject: [PATCH 38/70] add 485 ts solution --- Problems/13-Max-Consecutive-Ones-III/485.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Problems/13-Max-Consecutive-Ones-III/485.ts diff --git a/Problems/13-Max-Consecutive-Ones-III/485.ts b/Problems/13-Max-Consecutive-Ones-III/485.ts new file mode 100644 index 0000000..6f3c2a6 --- /dev/null +++ b/Problems/13-Max-Consecutive-Ones-III/485.ts @@ -0,0 +1,18 @@ +function findMaxConsecutiveOnes(nums: number[]): number { + let slow: number = 0, fast: number = 0; + let res: number = 0; + while (fast < nums.length) { + if (nums[slow] !== 1 && nums[fast] !== 1) { + slow++; + fast++; + } + else if (nums[slow] === 1 && nums[fast] === 1) { + fast++; + } + else if (nums[fast] !== 1) { + slow = fast; + } + res = res > (fast - slow) ? res : (fast - slow); + } + return res; +}; \ No newline at end of file From a94b0b021144cf1718140477f3aa7ff089ae475f Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Thu, 9 Feb 2023 11:06:05 +0100 Subject: [PATCH 39/70] add 74 ts solution --- Problems/14-Search-a-2D-Matrix/74.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Problems/14-Search-a-2D-Matrix/74.ts diff --git a/Problems/14-Search-a-2D-Matrix/74.ts b/Problems/14-Search-a-2D-Matrix/74.ts new file mode 100644 index 0000000..6293383 --- /dev/null +++ b/Problems/14-Search-a-2D-Matrix/74.ts @@ -0,0 +1,26 @@ +function searchMatrix(matrix: number[][], target: number): boolean { + function searchMx(matrix: number[][], target: number): number { + let left = 0, right = matrix.length - 1; + while (left <= right) { + let mid = Math.floor((left + right) / 2); + let head = matrix[mid][0]; + let tail = matrix[mid][matrix[mid].length - 1]; + if (target > tail) left = mid + 1; + else if (target < head) right = mid - 1; + else if (target <= tail && target >= head) return mid; + } + return -1; + } + + if (searchMx(matrix, target) === -1) return false; + const arr = matrix[searchMx(matrix, target)]; + let left = 0; + let right = arr.length - 1; + while (left <= right) { + let mid = Math.floor((left + right) / 2); + if (arr[mid] > target) right = mid - 1; + else if (arr[mid] < target) left = mid + 1; + else return true; + } + return false; +}; \ No newline at end of file From 76fbb9f3b1f606321c75ad63dc2fa9e498947309 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 9 Feb 2023 23:54:57 +0100 Subject: [PATCH 40/70] Add C++ 16 17 18 Solution --- Problems/.DS_Store | Bin 12292 -> 14340 bytes ...ur-Digit-Number-After-Splitting-Digits.cpp | 19 ++++++++++++++++++ .../Split-a-String-in-Balanced-Strings.cpp | 15 ++++++++++++++ .../Can-Place-Flowers.cpp | 19 ++++++++++++++++++ 4 files changed, 53 insertions(+) create mode 100644 Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits.cpp create mode 100644 Problems/17-Split-a-String-in-Balanced-Strings/Split-a-String-in-Balanced-Strings.cpp create mode 100644 Problems/18-Can-Place-Flowers/Can-Place-Flowers.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index 66afaab5dbc8273b9d245f8b6ed27bd4acdb0bca..b66dcc445d36727bc6780ad32b445b877cc80e41 100644 GIT binary patch literal 14340 zcmeHN&u<$=6n;xuT9hKSNC+X2>O(7}NS2b6A4yM6>VzK(Z6sS%hy$dKrpJ%razmuRG;;7c&$eR-IS$SjaN_>BNKq|K_EMe=E3O!QI;W@>r$Tbk}{w(I81#zLJC{<{xOWkcQmVK!_%@N2E$Pvg9$PxITA;7g4$I)S%=GPp7 z9Dy8x00G*E0#2qSFWs@JF&(&Y3(x1=!kYv4@B>UY-+{DvEt%*H9MY%;+WbYS1`rJDcLl?<_P2nv?DNrtS8_nPr^H%qgO2r zc*vW^->%4(Tr&Rm8@Q|ES;yMdN*9@L5SvH85kwZ=v0uEln{i9q zBStx{g2|#xA=;PfzXdJ?@4WAR+87jTYC8CT-h!dzI9Z3UYyq@#FDO5gI68XE^@De8_OnzC*MZ`!A)4c=FQX1#fh%kG=bU>%rLY+NF_5UbrgAANV_Ent;U&PSm;Ii-L1H%6*&Rv)b2IKTh$WOV$G zJaFrEv?umlkw=mI@DMnOwBvhnWsGzz8yOdg-oGb(SFiAQ0$wuxgbGHtYxeopQq+)F zg=N9mS6ZGxD$Yl+v$9&@b+9xf6-o!f9hI`CSF)bLT#GsUgze z+q0k4zCnMx))4f)M-2)N!@z<2*LmQ;2ndnj-Osod^W|sq|S4z54A>k`t$LRkK6@M zeW^9zuaC7VypDiZ?iZ&pb5@bY<2dx%?2Pf_n+bSSBcGYn6XEW!--a%{4em0kCtxen zdK7+o_(o5$YdvU*Vf*e?0D6Zzu`qKV`}th)2#LlnA`Q~DS4??b(N!@2*D zl`;8o*cKh-_kS~;zyD9JFfW-SkR$M)L%=yyu9T delta 199 zcmZoEXh~3DU|?W$DortDV9)?EIe-{M3-ADmb_NCo?uiQeqIN(IGf v {}; + while(num){ + v.push_back(num % 10); + num /= 10; + } + + sort(v.begin(), v.end()); + + vector a(2, 0); + for (int i = 0; i < v.size(); i++) + { + a[i % 2] = a[i % 2] * 10 + v[i]; + } + return a[0] + a[1]; + } +}; \ No newline at end of file diff --git a/Problems/17-Split-a-String-in-Balanced-Strings/Split-a-String-in-Balanced-Strings.cpp b/Problems/17-Split-a-String-in-Balanced-Strings/Split-a-String-in-Balanced-Strings.cpp new file mode 100644 index 0000000..fa8d0b4 --- /dev/null +++ b/Problems/17-Split-a-String-in-Balanced-Strings/Split-a-String-in-Balanced-Strings.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int balancedStringSplit(string s) { + int ans = 0; + int cpt = 0; + for (auto& c: s) + { + if (c == 'R') cpt ++; + else cpt --; + + if (cpt == 0) ans ++; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/18-Can-Place-Flowers/Can-Place-Flowers.cpp b/Problems/18-Can-Place-Flowers/Can-Place-Flowers.cpp new file mode 100644 index 0000000..74ef164 --- /dev/null +++ b/Problems/18-Can-Place-Flowers/Can-Place-Flowers.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool canPlaceFlowers(vector& flowerbed, int n) { + + int m = flowerbed.size(); + if (n == 0) return true; + int sum = 0; + for (int j = 0; j < m; j++) + { + if ((j==0 or flowerbed[j-1] == 0) and (j == m-1 or flowerbed[j+1] == 0) and flowerbed[j] == 0) + { + flowerbed[j] = 1; + sum++; + } + } + + return sum >= n; + } +}; \ No newline at end of file From af9818e1f57941dd062e30395482db37439e08d3 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 9 Feb 2023 23:58:35 +0100 Subject: [PATCH 41/70] Update Readme --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 1e1b993..45c4fa5 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,9 @@ Solutions in various programming languages are provided. Enjoy it. 13. 2023/02/04 [#1004. Max Consecutive Ones III](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/13-Max-Consecutive-Ones-III): Binary Search 14. 2023/02/05 [#74. Search a 2D Matrix](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/14-Search-a-2D-Matrix): Binary Search 15. 2023/02/06 [#2517. Maximum Tastiness of Candy Basket](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/15-Maximum-Tastiness-of-Candy-Basket): Binary Search +16. 2023/02/07 [#2160 Minimum Sum of Four Digit Number After Splitting Digits](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits): Greedy +17. 2023/02/08 [#1221 Split a String in Balanced Strings](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/17-Split-a-String-in-Balanced-Strings): Greedy +18. 2023/02/09 [#605 Can Place Flowers](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/18-Can-Place-Flowers): Greedy ## Weekly Contest From 184d2797515248f505fddd93362e07cee0916e07 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Sat, 11 Feb 2023 23:31:45 +0100 Subject: [PATCH 42/70] add 2517 ts solution --- .../2517.ts | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Problems/15-Maximum-Tastiness-of-Candy-Basket/2517.ts diff --git a/Problems/15-Maximum-Tastiness-of-Candy-Basket/2517.ts b/Problems/15-Maximum-Tastiness-of-Candy-Basket/2517.ts new file mode 100644 index 0000000..5684382 --- /dev/null +++ b/Problems/15-Maximum-Tastiness-of-Candy-Basket/2517.ts @@ -0,0 +1,35 @@ +function maximumTastiness(price: number[], k: number): number { + + let n = price.length; + price = price.sort((a,b)=> a-b); + let left = 0, right = price[n-1] - price[0] , ans = 0; + + while(left <= right){ + let mid = Math.floor(left+(right-left)/2); + if(possible(mid)){ + ans = mid; + left = mid+1; + }else{ + right = mid-1; + } + } + + function possible(diff){ + let count = 1; + let curr = 0; + + for(let i=1; i= diff){ + curr = i; + count++; + } + } + + if(count >= k) return true + else return false; + + } + + return ans; + +}; \ No newline at end of file From 7b337713ff52ca5c70ab1b2822b837aaf02c84b8 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 11 Feb 2023 23:35:13 +0100 Subject: [PATCH 43/70] Add C++ 19 20 Solutions --- .../Optimal-Partition-of-String.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Problems/20-Optimal-Partition-of-String/Optimal-Partition-of-String.cpp diff --git a/Problems/20-Optimal-Partition-of-String/Optimal-Partition-of-String.cpp b/Problems/20-Optimal-Partition-of-String/Optimal-Partition-of-String.cpp new file mode 100644 index 0000000..248ba70 --- /dev/null +++ b/Problems/20-Optimal-Partition-of-String/Optimal-Partition-of-String.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int partitionString(string s) { + int ans = 0; + unordered_set st; + for (auto& c: s) + { + if (st.find(c) == st.end()) + { + st.insert(c); + } + else + { + st.clear(); + st.insert(c); + ans++; + } + } + if (!st.empty()) ans++; + return ans; + } +}; \ No newline at end of file From bb9876aac4da78a2233f75c75d2264124c32ed9f Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 11 Feb 2023 23:36:13 +0100 Subject: [PATCH 44/70] Add C++ 19 20 Solutions --- Problems/.DS_Store | Bin 14340 -> 14340 bytes .../19-Partition-Labels/Partition-Labels.cpp | 27 ++++++++++++++++++ README.md | 2 +- 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 Problems/19-Partition-Labels/Partition-Labels.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index b66dcc445d36727bc6780ad32b445b877cc80e41..eab3357f77cfaf2bf630b0a3c946c17e4b147844 100644 GIT binary patch delta 529 zcmZoEXepTBFB-tWz`)GFAi%(&%izn9$WQ^KohJ)2Do-{rVPRzi%Cb!UCuTMIotVJJ zTZa6M@|*vOJ!DfCVK8K{04W7($pg{>3^_nnGD9km?FMA$Gn50_MUy`Wiq;dUmZ3N| z-^C@Rv?Q5<;Q_Z6=a(#?p-6fu-A zWP))%*t0%BuOz`)GFAi%(&%Mi?v%8 partitionLabels(string s) { + int n = s.length(); + vector lastPos(26, 0); + for (int i = 0; i < n; i++) + { + lastPos[s[i] - 'a'] = i; + } + + vector ans; + int startIndex = 0; + while (startIndex < n) + { + int j = startIndex; + int endIndex = lastPos[s[startIndex] - 'a']; + while (j < endIndex) + { + if (lastPos[s[j] - 'a'] > endIndex) endIndex = lastPos[s[j] - 'a']; + j++; + } + ans.push_back(endIndex - startIndex + 1); + startIndex = endIndex + 1; + } + return ans; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index 45c4fa5..0f265e9 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Solutions in various programming languages are provided. Enjoy it. 16. 2023/02/07 [#2160 Minimum Sum of Four Digit Number After Splitting Digits](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits): Greedy 17. 2023/02/08 [#1221 Split a String in Balanced Strings](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/17-Split-a-String-in-Balanced-Strings): Greedy 18. 2023/02/09 [#605 Can Place Flowers](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/18-Can-Place-Flowers): Greedy - +19. 2023/02/10 [#763 Partition Labels](): Greedy ## Weekly Contest From 0823fdf9d2ce2c12ab127085bf8d4a014c595d40 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 11 Feb 2023 23:38:24 +0100 Subject: [PATCH 45/70] Update Readme --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f265e9..cc1576c 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,8 @@ Solutions in various programming languages are provided. Enjoy it. 16. 2023/02/07 [#2160 Minimum Sum of Four Digit Number After Splitting Digits](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits): Greedy 17. 2023/02/08 [#1221 Split a String in Balanced Strings](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/17-Split-a-String-in-Balanced-Strings): Greedy 18. 2023/02/09 [#605 Can Place Flowers](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/18-Can-Place-Flowers): Greedy -19. 2023/02/10 [#763 Partition Labels](): Greedy +19. 2023/02/10 [#763 Partition Labels](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/19-Partition-Labels): Greedy +20. 2023/02/11 [#2405 Optimal Partition of String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/20-Optimal-Partition-of-String): Greedy ## Weekly Contest From 535df8f2cdbcac7293365edc89e8da61a443c686 Mon Sep 17 00:00:00 2001 From: qinyii Date: Sun, 12 Feb 2023 14:12:17 +0100 Subject: [PATCH 46/70] Add Python 13 14 15 solution --- .../Max_consecutive_ones_III.py | 19 +++++++++++++++ .../search_a_2D_Matrix.py | 15 ++++++++++++ .../Max_Tastiness_of_Candy.py | 23 +++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 Problems/13-Max-Consecutive-Ones-III/Max_consecutive_ones_III.py create mode 100644 Problems/14-Search-a-2D-Matrix/search_a_2D_Matrix.py create mode 100644 Problems/15-Maximum-Tastiness-of-Candy-Basket/Max_Tastiness_of_Candy.py diff --git a/Problems/13-Max-Consecutive-Ones-III/Max_consecutive_ones_III.py b/Problems/13-Max-Consecutive-Ones-III/Max_consecutive_ones_III.py new file mode 100644 index 0000000..63a5927 --- /dev/null +++ b/Problems/13-Max-Consecutive-Ones-III/Max_consecutive_ones_III.py @@ -0,0 +1,19 @@ +class Solution(object): + def longestOnes(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + left ,right = 0,0 + res = 0 + while(right matrix[i][0]): k = i + for j in range(1,len(matrix[k])): + if(target == matrix[k][j]): return True + return False \ No newline at end of file diff --git a/Problems/15-Maximum-Tastiness-of-Candy-Basket/Max_Tastiness_of_Candy.py b/Problems/15-Maximum-Tastiness-of-Candy-Basket/Max_Tastiness_of_Candy.py new file mode 100644 index 0000000..9ee5932 --- /dev/null +++ b/Problems/15-Maximum-Tastiness-of-Candy-Basket/Max_Tastiness_of_Candy.py @@ -0,0 +1,23 @@ +class Solution(object): + def maximumTastiness(self, price, k): + """ + :type price: List[int] + :type k: int + :rtype: int + """ + price.sort() + def check(d): + cnt, x0 = 1, price[0] + for x in price: + if x - x0 >= d: + cnt += 1 + x0 = x + return cnt >= k + + left = 0 + right = price[-1]-price[0] + while(left < right): + mid = (left+right+1)//2 + if check(mid): left = mid + else: right = mid-1 + return left From 58c7b5f422da5d3317f5d12ef48ccff5f817544f Mon Sep 17 00:00:00 2001 From: qinyii Date: Sun, 12 Feb 2023 18:08:05 +0100 Subject: [PATCH 47/70] add python 16 17 18 19 20 solutions --- .../Minimun_Sum_of_Four_Digit_Number.py | 12 ++++++++++++ .../Split_a_String_in_Balanced_Strings.py | 15 +++++++++++++++ .../18-Can-Place-Flowers/Can-Place-Flowers.py | 13 +++++++++++++ .../19-Partition-Labels/Partition_Labels.py | 17 +++++++++++++++++ .../Optimal_Partition_of_String.py | 15 +++++++++++++++ 5 files changed, 72 insertions(+) create mode 100644 Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimun_Sum_of_Four_Digit_Number.py create mode 100644 Problems/17-Split-a-String-in-Balanced-Strings/Split_a_String_in_Balanced_Strings.py create mode 100644 Problems/18-Can-Place-Flowers/Can-Place-Flowers.py create mode 100644 Problems/19-Partition-Labels/Partition_Labels.py create mode 100644 Problems/20-Optimal-Partition-of-String/Optimal_Partition_of_String.py diff --git a/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimun_Sum_of_Four_Digit_Number.py b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimun_Sum_of_Four_Digit_Number.py new file mode 100644 index 0000000..4b54e9b --- /dev/null +++ b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimun_Sum_of_Four_Digit_Number.py @@ -0,0 +1,12 @@ +class Solution(object): + def minimumSum(self, num): + """ + :type num: int + :rtype: int + """ + res = [] + while num: + res.append(num%10) + num/=10 + res.sort() + return res[0]*10+res[2]+ res[1]*10+res[3] \ No newline at end of file diff --git a/Problems/17-Split-a-String-in-Balanced-Strings/Split_a_String_in_Balanced_Strings.py b/Problems/17-Split-a-String-in-Balanced-Strings/Split_a_String_in_Balanced_Strings.py new file mode 100644 index 0000000..0632fb6 --- /dev/null +++ b/Problems/17-Split-a-String-in-Balanced-Strings/Split_a_String_in_Balanced_Strings.py @@ -0,0 +1,15 @@ +class Solution(object): + def balancedStringSplit(self, s): + """ + :type s: str + :rtype: int + """ + res, tmp = 0,0 + for char in s: + if char == 'R': + tmp += 1 + else: + tmp -= 1 + if tmp == 0: + res += 1 + return res \ No newline at end of file diff --git a/Problems/18-Can-Place-Flowers/Can-Place-Flowers.py b/Problems/18-Can-Place-Flowers/Can-Place-Flowers.py new file mode 100644 index 0000000..b4b3da5 --- /dev/null +++ b/Problems/18-Can-Place-Flowers/Can-Place-Flowers.py @@ -0,0 +1,13 @@ +class Solution(object): + def canPlaceFlowers(self, flowerbed, n): + """ + :type flowerbed: List[int] + :type n: int + :rtype: bool + """ + tmp = [0]+flowerbed+[0] + for i in range(1,len(tmp)-1): + if tmp[i-1] == 0 and tmp[i] == 0 and tmp[i+1] == 0: + tmp[i] = 1 + n -= 1 + return n <= 0 diff --git a/Problems/19-Partition-Labels/Partition_Labels.py b/Problems/19-Partition-Labels/Partition_Labels.py new file mode 100644 index 0000000..19c5f42 --- /dev/null +++ b/Problems/19-Partition-Labels/Partition_Labels.py @@ -0,0 +1,17 @@ +class Solution(object): + def partitionLabels(self, s): + """ + :type s: str + :rtype: List[int] + """ + last = [0] * 26 + for i in range(len(s)): + last[ord(s[i]) - ord('a')] = i + res = [] + left,right = 0,0 + for i in range(len(s)): + right = max(right, last[ord(s[i]) - ord('a')]) + if i == right: + res.append(right - left + 1) + left = i + 1 + return res \ No newline at end of file diff --git a/Problems/20-Optimal-Partition-of-String/Optimal_Partition_of_String.py b/Problems/20-Optimal-Partition-of-String/Optimal_Partition_of_String.py new file mode 100644 index 0000000..50c258b --- /dev/null +++ b/Problems/20-Optimal-Partition-of-String/Optimal_Partition_of_String.py @@ -0,0 +1,15 @@ +class Solution(object): + def partitionString(self, s): + """ + :type s: str + :rtype: int + """ + res = 1 + tmp = [] + for char in s: + if char in tmp: + tmp = [char] + res +=1 + else: + tmp.append(char) + return res From 52daf33075f57a3d9698cef0fcd0bea6ce6d9840 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Mon, 13 Feb 2023 10:01:00 +0100 Subject: [PATCH 48/70] add 2160 ts solution --- .../2160.ts | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/2160.ts diff --git a/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/2160.ts b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/2160.ts new file mode 100644 index 0000000..36cdba1 --- /dev/null +++ b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/2160.ts @@ -0,0 +1,38 @@ + + +// minimum sum of any length of number. +function minimumSum(num: number): number { + const str = num.toString().split(''); + let digits = str.map(Number); + digits.sort((a,b)=>a-b); + + for(let i = 0; i< digits.length; i++) { + if(digits[i] !== 0) { + digits = digits.slice(i) + break; + } + } + let p1 = 0,p2 = 1; + let num1: number[] = []; + let num2: number[] = []; + while(digits[p1]) { + num1.push(digits[p1]); + if(p2 < digits.length){ + num2.push(digits[p2]) + } + p1 += 2; + p2 += 2; + } + return Num(num1) + Num(num2); + + function Num(digits: number[]): number { + let res : number = 0; + let len = digits.length-1; + for(let i = 0; i < digits.length; i++) { + res += Math.pow(10,len)* digits[i]; + len --; + } + return res; + } + +}; \ No newline at end of file From 57583ab6022b812fb68aefa944de11e644352772 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Mon, 13 Feb 2023 10:27:50 +0100 Subject: [PATCH 49/70] add 1221 ts solution --- .../17-Split-a-String-in-Balanced-Strings/1221.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Problems/17-Split-a-String-in-Balanced-Strings/1221.ts diff --git a/Problems/17-Split-a-String-in-Balanced-Strings/1221.ts b/Problems/17-Split-a-String-in-Balanced-Strings/1221.ts new file mode 100644 index 0000000..8c2765c --- /dev/null +++ b/Problems/17-Split-a-String-in-Balanced-Strings/1221.ts @@ -0,0 +1,14 @@ +function balancedStringSplit(s: string): number { + let res: number = 0; + let x:number = 0; + + for(let i of s) { + if( i === 'R') x++; + else x--; + + if(x === 0) { + res ++; + } + } + return res; +}; \ No newline at end of file From 4d37c5a39ecf35083f779b12cbed8d46053ca717 Mon Sep 17 00:00:00 2001 From: JeremyXXXuuu Date: Mon, 13 Feb 2023 10:57:24 +0100 Subject: [PATCH 50/70] add 605 ts solution --- Problems/18-Can-Place-Flowers/605.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Problems/18-Can-Place-Flowers/605.ts diff --git a/Problems/18-Can-Place-Flowers/605.ts b/Problems/18-Can-Place-Flowers/605.ts new file mode 100644 index 0000000..d07fca6 --- /dev/null +++ b/Problems/18-Can-Place-Flowers/605.ts @@ -0,0 +1,12 @@ +function canPlaceFlowers(flowerbed: number[], n: number): boolean { + let num: number = 0; + let flag: boolean = false; + for (let i = 0; i < flowerbed.length; i++) { + if (flag === true) i++; + if ((flowerbed[i - 1] === 0 || flowerbed[i - 1] === undefined) && flowerbed[i] === 0 && (flowerbed[i + 1] === 0 || flowerbed[i + 1] === undefined)) { + num++; + flag = true; + } else flag = false; + } + return num >= n; +}; \ No newline at end of file From ef64fdcab6a6d2c4c7e8d42cedf6984e421e8e15 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 14 Feb 2023 11:20:16 +0100 Subject: [PATCH 51/70] Add C++ 21 22 solutions --- Problems/.DS_Store | Bin 14340 -> 14340 bytes .../Minimum-Suffix-Flips.cpp | 12 +++++++++ .../Merge-Strings-Alternately.cpp | 24 ++++++++++++++++++ README.md | 3 +++ 4 files changed, 39 insertions(+) create mode 100644 Problems/21-Minimum-Suffix-Flips/Minimum-Suffix-Flips.cpp create mode 100644 Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index eab3357f77cfaf2bf630b0a3c946c17e4b147844..e0564960b27a378ec842c88ef3dbb2960770a6a2 100644 GIT binary patch delta 558 zcmZoEXepTB<5aU^hRb=EMnBo81KJIYi|cj2H|UbQ$~^3K&WlG8u9i5*czPPmmC| z%x6dgiU$Kli-6*J4Cy)PhQZ1CxdjXeK!Wbvd>5CL(voBbh6lVSd{^!U8bXrp6ryzp zVz|5@1HxKX z{eL+h=wFgefcqI}f)VLPOx_^zRfjEIE2K7rH?`gGTcl-fKEg=;VU^hRb{KN@Xo81KJIVST;KiI4*bB}qm0%Hf$W^RR_;s8LF4zmCN diff --git a/Problems/21-Minimum-Suffix-Flips/Minimum-Suffix-Flips.cpp b/Problems/21-Minimum-Suffix-Flips/Minimum-Suffix-Flips.cpp new file mode 100644 index 0000000..4ee1280 --- /dev/null +++ b/Problems/21-Minimum-Suffix-Flips/Minimum-Suffix-Flips.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minFlips(string target) { + int n = target.size(); + int ans = 0; + for (int i = 0; i < n; i++) + { + if ((ans % 2 == 0 && target[i] != '0') || (ans % 2 == 1 && target[i] == '0')) ans++; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.cpp b/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.cpp new file mode 100644 index 0000000..fc9a370 --- /dev/null +++ b/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + string mergeAlternately(string word1, string word2) { + int n = word1.length(); + int m = word2.length(); + string s = ""; + + int i = 0, j = 0; + while (i < n and j < m) + { + s += word1[i++]; + s += word2[j++]; + } + if (i == n) + { + while (j < m) s+= word2[j++]; + } + if (j == m) + { + while (i < n) s+= word1[i++]; + } + return s; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index cc1576c..d611a66 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,9 @@ Solutions in various programming languages are provided. Enjoy it. 18. 2023/02/09 [#605 Can Place Flowers](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/18-Can-Place-Flowers): Greedy 19. 2023/02/10 [#763 Partition Labels](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/19-Partition-Labels): Greedy 20. 2023/02/11 [#2405 Optimal Partition of String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/20-Optimal-Partition-of-String): Greedy +21. 2023/02/12 [#1529 Minimum Suffix Flips](): Greedy +22. 2023/02/13 [#1768 Merge Strings Alternately](): String + ## Weekly Contest From c67eae60ae77a5c6b48edc2d98f952930dd140b1 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 14 Feb 2023 11:21:23 +0100 Subject: [PATCH 52/70] Update Readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d611a66..3b7bb2e 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,8 @@ Solutions in various programming languages are provided. Enjoy it. 18. 2023/02/09 [#605 Can Place Flowers](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/18-Can-Place-Flowers): Greedy 19. 2023/02/10 [#763 Partition Labels](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/19-Partition-Labels): Greedy 20. 2023/02/11 [#2405 Optimal Partition of String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/20-Optimal-Partition-of-String): Greedy -21. 2023/02/12 [#1529 Minimum Suffix Flips](): Greedy -22. 2023/02/13 [#1768 Merge Strings Alternately](): String +21. 2023/02/12 [#1529 Minimum Suffix Flips](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/21-Minimum-Suffix-Flips): Greedy +22. 2023/02/13 [#1768 Merge Strings Alternately](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/22-Merge-Strings-Alternately): String ## Weekly Contest From 44e20795cb86b23a2b12b2e3ad33fac62d8875d4 Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Thu, 16 Feb 2023 00:11:28 +0100 Subject: [PATCH 53/70] add 763 ts solution --- Problems/19-Partition-Labels/763.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Problems/19-Partition-Labels/763.ts diff --git a/Problems/19-Partition-Labels/763.ts b/Problems/19-Partition-Labels/763.ts new file mode 100644 index 0000000..7011261 --- /dev/null +++ b/Problems/19-Partition-Labels/763.ts @@ -0,0 +1,21 @@ +function partitionLabels(s: string): number[] { + + let map: Map = new Map(); + let res: number[] = []; + + for(let i = 0; i < s.length; i++) { + map.set(s[i],i); + } + + let start = 0, end = 0; + for(let i = 0; i < s.length; i++) { + end = Math.max(map.get(s[i])!, end); + if(i === end){ + end = i; + res.push(end - start + 1); + start = end+1; + } + } + return res; + +}; \ No newline at end of file From db34c3b0a56433f48a8571fa6bd33a4da0487bc2 Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Sat, 18 Feb 2023 00:43:49 +0100 Subject: [PATCH 54/70] add 2405 ts solution --- Problems/20-Optimal-Partition-of-String/2405.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Problems/20-Optimal-Partition-of-String/2405.ts diff --git a/Problems/20-Optimal-Partition-of-String/2405.ts b/Problems/20-Optimal-Partition-of-String/2405.ts new file mode 100644 index 0000000..b963f9f --- /dev/null +++ b/Problems/20-Optimal-Partition-of-String/2405.ts @@ -0,0 +1,13 @@ +function partitionString(s: string): number { + let arr: string[] = []; + let count = 0; + for(let i = 0; i < s.length; i++) { + if(arr.indexOf(s[i])>= 0) { + count ++; + arr = []; + } + arr.push(s[i]); + } + return count+1; + +}; \ No newline at end of file From 943974c33cbdec841a99e04c2b769b0d76f66076 Mon Sep 17 00:00:00 2001 From: qinyii Date: Sat, 18 Feb 2023 19:19:00 +0100 Subject: [PATCH 55/70] add Python 21,22 solutions --- .../Minimum_Suffix_Flips.py | 13 ++++++++++++ .../Merge-Strings-Alternately.py | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 Problems/21-Minimum-Suffix-Flips/Minimum_Suffix_Flips.py create mode 100644 Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.py diff --git a/Problems/21-Minimum-Suffix-Flips/Minimum_Suffix_Flips.py b/Problems/21-Minimum-Suffix-Flips/Minimum_Suffix_Flips.py new file mode 100644 index 0000000..504e526 --- /dev/null +++ b/Problems/21-Minimum-Suffix-Flips/Minimum_Suffix_Flips.py @@ -0,0 +1,13 @@ +class Solution(object): + def minFlips(self, target): + """ + :type target: str + :rtype: int + """ + res= 0 + s ="0" + for c in target: + if c != s: + res += 1 + s = c + return res \ No newline at end of file diff --git a/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.py b/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.py new file mode 100644 index 0000000..4807a90 --- /dev/null +++ b/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.py @@ -0,0 +1,20 @@ +class Solution(object): + def mergeAlternately(self, word1, word2): + """ + :type word1: str + :type word2: str + :rtype: str + """ + l1 = len(word1) + l2 = len(word2) + i,j = 0,0 + res = list() + while i < l1 or j < l2: + if i < l1: + res.append(word1[i]) + i += 1 + if j < l2: + res.append(word2[j]) + j += 1 + + return "".join(res) \ No newline at end of file From 4ee54262add9752f64f94765b68a7873d47819de Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 19 Feb 2023 22:25:48 +0100 Subject: [PATCH 56/70] Add C++ --- Problems/.DS_Store | Bin 14340 -> 18436 bytes .../Partition-Array-for-Maximum-Sum.cpp | 22 ++++++++ .../Where-Will-the-Ball-Fall.cpp | 29 +++++++++++ .../Flip-String-to-Monotone-Increasing.cpp | 21 ++++++++ Problems/26-Knight-Dialer/Knight-Dialer.cpp | 25 ++++++++++ .../Ways-to-Make-a-Fair-Array.cpp | 47 ++++++++++++++++++ README.md | 6 ++- 7 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 Problems/23-Partition-Array-for-Maximum-Sum/Partition-Array-for-Maximum-Sum.cpp create mode 100644 Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.cpp create mode 100644 Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.cpp create mode 100644 Problems/26-Knight-Dialer/Knight-Dialer.cpp create mode 100644 Problems/27-Ways-to-Make-a-Fair-Array/Ways-to-Make-a-Fair-Array.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index e0564960b27a378ec842c88ef3dbb2960770a6a2..7a8b365f6e0c83cd0701d3d8e4ea680b1ca4e5d3 100644 GIT binary patch delta 1665 zcmb`IyKmD_6voeWoF>pfTpp?;7ZFN9NUf!&4G(pIBn=T2YE-F6Wo(s{CMYkpjYKDB zC<78h%>6TvSgynhVqs)sU}8i-7iN(7ZcG!W4{SxXWuJ48eLmmw^YQg=W4FyFh=^sH z#RO3bZWxEOS_EMX;;_>Zdtx%!KvcCK&GI;F@#&<>6#HdfMKH+o`V>#;8eh^<{EIdz z&M{?3gu-f=T^D)%onnpA40e+iX`MD{180+#X&Zi-Y8Y=}oTdsQ@_LQdI$ni#DjSLA zLcJ=Vy}u2hWkD8V)p|BtY;G5bzK%pczL0YtKx|*D=wIu$N0p7zp(@A0YnHe5(JN^X z*#watFnU6D_>$uqJp;QcHL1$qj2pr3{b|qpJM59?!l7p#zx@mx1F3XD98&Qy_o=If zWuVq1X0<}4&ij|$v4ZL<*iCeTjGB}|%}ylect`ZcKuQ)>`cS;S{1hk#l9Ea;9R8H7 zW9mDiE3SdmO|Zy;M41}!++UGoRYzmaw~d~-c|JQ6!)ouINC z=KQ@6cLCE=-SR(iH(|f>p6UT`;Xh+BO9SCsVE7Qk%2=67plDJSzU)4%PCag@%h^10 z`iR)-E2JHhGuL}iU!DI=a&q{4bCjPk_V|o(p6?mav)#o`pZ~TH=HCq?*zv^aF{X+* zQxq{A{~fhkD%0)uoXBaPLgM0$U!hAwPF<;C*!u_n1!9E#2=Hh!afjh@%ej@{E7FCP b>#7{cU&#aMBewL}#ig;3xxIXp&# delta 221 zcmZpfz}Qlt!oa}5=v10w$iQF#WO4v8h!)@h6738O3Lu(cqKYPX#rLaBqpcx^iIxK)ts!MAUt`$O7i9zsyR#mAxADD diff --git a/Problems/23-Partition-Array-for-Maximum-Sum/Partition-Array-for-Maximum-Sum.cpp b/Problems/23-Partition-Array-for-Maximum-Sum/Partition-Array-for-Maximum-Sum.cpp new file mode 100644 index 0000000..8991569 --- /dev/null +++ b/Problems/23-Partition-Array-for-Maximum-Sum/Partition-Array-for-Maximum-Sum.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int maxSumAfterPartitioning(vector& arr, int k) { + int n = arr.size(); + vector dp(n+1, 0); + dp[1] = arr[0]; + for (int i = 2; i <= n; i++) + { + long long maxValue = -1; + for (int j = i-1; j >= max(0, i-k); j--) + { + if (arr[j] > maxValue) maxValue = arr[j]; + long long cur = maxValue * (i - j) + dp[j]; + if ( cur > dp[i]) + { + dp[i] = cur; + } + } + } + return dp[n]; + } +}; \ No newline at end of file diff --git a/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.cpp b/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.cpp new file mode 100644 index 0000000..03f10ee --- /dev/null +++ b/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector findBall(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + vector> dp(m+1, vector(n, -1)); + for (int j = 0; j < n; j++) dp[m][j] = j; + + for (int i = m-1; i >= 0; i--) + { + for (int j = n-1; j >= 0; j--) + { + if (j != n-1 and grid[i][j+1] == -1 and grid[i][j] == -1) + { + dp[i][j+1] = dp[i+1][j]; + } + else if (j != 0 and grid[i][j-1] == 1 and grid[i][j] == 1) + { + dp[i][j-1] = dp[i+1][j]; + } + } + } + + vector ans(n, 0); + for (int j = 0; j < n; j++) ans[j] = dp[0][j]; + return ans; + } +}; \ No newline at end of file diff --git a/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.cpp b/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.cpp new file mode 100644 index 0000000..3e8ebb4 --- /dev/null +++ b/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minFlipsMonoIncr(string s) { + int n = s.length(); + vector accZero(n+1, 0); + for (int i = n-1; i>= 0; i--) + { + accZero[i] = accZero[i+1]; + if (s[i] == '0') accZero[i]++; + } + + int ans = accZero[0]; + int numOne = 0; + for (int i = 0; i < n ; i++) + { + if (s[i] == '1') numOne++; + ans = min(ans, (numOne + accZero[i+1])); + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/26-Knight-Dialer/Knight-Dialer.cpp b/Problems/26-Knight-Dialer/Knight-Dialer.cpp new file mode 100644 index 0000000..2a15a34 --- /dev/null +++ b/Problems/26-Knight-Dialer/Knight-Dialer.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int knightDialer(int n) { + const int M = 1000000007; + vector> dp(10, vector(n+1, 0)); + for (int i = 0; i < 10; i++) dp[i][0] = 1; + + for (int j = 1; j < n; j++) + { + dp[1][j] = (dp[6][j-1] + dp[8][j-1]) % M; + dp[2][j] = (dp[7][j-1] + dp[9][j-1]) % M; + dp[3][j] = (dp[4][j-1] + dp[8][j-1]) % M; + dp[4][j] = ((dp[3][j-1] + dp[9][j-1]) % M + dp[0][j-1]) % M; + dp[5][j] = 0; + dp[6][j] = ((dp[1][j-1] + dp[7][j-1]) % M + dp[0][j-1]) % M; + dp[7][j] = (dp[2][j-1] + dp[6][j-1]) % M; + dp[8][j] = (dp[1][j-1] + dp[3][j-1]) % M; + dp[9][j] = (dp[2][j-1] + dp[4][j-1]) % M; + dp[0][j] = (dp[4][j-1] + dp[6][j-1]) % M; + } + int ans = 0; + for (int i = 0; i < 10; i++) ans = (ans + dp[i][n-1]) % M; + return ans; + } +}; \ No newline at end of file diff --git a/Problems/27-Ways-to-Make-a-Fair-Array/Ways-to-Make-a-Fair-Array.cpp b/Problems/27-Ways-to-Make-a-Fair-Array/Ways-to-Make-a-Fair-Array.cpp new file mode 100644 index 0000000..11e08fa --- /dev/null +++ b/Problems/27-Ways-to-Make-a-Fair-Array/Ways-to-Make-a-Fair-Array.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int waysToMakeFair(vector& nums) { + int n = nums.size(); + if (n == 1) return 1; + + vector v(n, 0); + v[0] = nums[0]; + v[1] = nums[1]; + + for (int i = 2; i < n; i++) + { + v[i] = v[i-2] + nums[i]; + } + + int lastEven = (n % 2 == 0)?(n-2):(n-1); + int lastOdd = (n % 2 == 1)?(n-2):(n-1); + + int ans = 0; + for (int i = 0; i < n; i++) + { + if (i == 0) + { + if (v[lastEven] - v[0] == v[lastOdd]) ans++; + } + else if (i == 1) + { + if (v[0] + v[lastOdd] - v[1] == v[lastEven] - v[0]) ans++; + } + else + if (i % 2 == 0) + { + auto sumEven = v[i-2] + v[lastOdd] - v[i-1]; + auto sumOdd = v[i-1] + v[lastEven] - v[i]; + if (sumEven == sumOdd) ans++; + } + else + { + auto sumEven = v[i-1] + v[lastOdd] - v[i]; + auto sumOdd = v[i-2] + v[lastEven] - v[i-1]; + if (sumEven == sumOdd) ans++; + + } + } + return ans; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index 3b7bb2e..4a6b622 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,11 @@ Solutions in various programming languages are provided. Enjoy it. 20. 2023/02/11 [#2405 Optimal Partition of String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/20-Optimal-Partition-of-String): Greedy 21. 2023/02/12 [#1529 Minimum Suffix Flips](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/21-Minimum-Suffix-Flips): Greedy 22. 2023/02/13 [#1768 Merge Strings Alternately](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/22-Merge-Strings-Alternately): String - +23. 2023/02/14 [#1043 Partition Array for Maximum Sum](): DP +24. 2023/02/15 [#1706 Where Will the Ball Fall](): DP +25. 2023/02/16 [#926 Flip String to Monotone Increasing](): DP +26. 2023/02/17 [#935 Knight Dialer](): DP +27. 2023/02/18 [#1664 Ways to Make a Fair Array](): DP ## Weekly Contest From 616e9ece789816dbf97c14c1a8a9daca8a9680b0 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 19 Feb 2023 22:27:13 +0100 Subject: [PATCH 57/70] Update Readme --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4a6b622..2d3aaee 100644 --- a/README.md +++ b/README.md @@ -28,11 +28,11 @@ Solutions in various programming languages are provided. Enjoy it. 20. 2023/02/11 [#2405 Optimal Partition of String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/20-Optimal-Partition-of-String): Greedy 21. 2023/02/12 [#1529 Minimum Suffix Flips](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/21-Minimum-Suffix-Flips): Greedy 22. 2023/02/13 [#1768 Merge Strings Alternately](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/22-Merge-Strings-Alternately): String -23. 2023/02/14 [#1043 Partition Array for Maximum Sum](): DP -24. 2023/02/15 [#1706 Where Will the Ball Fall](): DP -25. 2023/02/16 [#926 Flip String to Monotone Increasing](): DP -26. 2023/02/17 [#935 Knight Dialer](): DP -27. 2023/02/18 [#1664 Ways to Make a Fair Array](): DP +23. 2023/02/14 [#1043 Partition Array for Maximum Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/23-Partition-Array-for-Maximum-Sum): DP +24. 2023/02/15 [#1706 Where Will the Ball Fall](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/24-Where-Will-the-Ball-Fall): DP +25. 2023/02/16 [#926 Flip String to Monotone Increasing](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/25-Flip-String-to-Monotone-Increasing): DP +26. 2023/02/17 [#935 Knight Dialer](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/26-Knight-Dialer): DP +27. 2023/02/18 [#1664 Ways to Make a Fair Array](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/27-Ways-to-Make-a-Fair-Array): DP ## Weekly Contest From e5d3654200d0b34dc25a93c8a52a397d6c35d31e Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Tue, 21 Feb 2023 10:13:10 +0100 Subject: [PATCH 58/70] add 1529 ts solution --- Problems/21-Minimum-Suffix-Flips/1529.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Problems/21-Minimum-Suffix-Flips/1529.ts diff --git a/Problems/21-Minimum-Suffix-Flips/1529.ts b/Problems/21-Minimum-Suffix-Flips/1529.ts new file mode 100644 index 0000000..5064095 --- /dev/null +++ b/Problems/21-Minimum-Suffix-Flips/1529.ts @@ -0,0 +1,13 @@ +function minFlips(target: string): number { + let init = 0; + let flips = 0; + + for(let i = 0; i < target.length; i++) { + if(Number(target[i]) !== init){ + init = Number(target[i]); + flips ++; + } + } + return flips + +}; \ No newline at end of file From 695011c05021521f5ad3cb203bb133f766a990d5 Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Tue, 21 Feb 2023 10:24:57 +0100 Subject: [PATCH 59/70] add 1768 ts solution --- Problems/22-Merge-Strings-Alternately/1768.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Problems/22-Merge-Strings-Alternately/1768.ts diff --git a/Problems/22-Merge-Strings-Alternately/1768.ts b/Problems/22-Merge-Strings-Alternately/1768.ts new file mode 100644 index 0000000..963b551 --- /dev/null +++ b/Problems/22-Merge-Strings-Alternately/1768.ts @@ -0,0 +1,18 @@ +function mergeAlternately(word1: string, word2: string): string { + let ptr1: number = 0; + let ptr2: number = 0; + const len1 = word1.length; + const len2 = word2.length; + let res: string[] = []; + while (ptr1 < len1 || ptr2 < len2) { + if (ptr1 < len1 && ptr2 < len2) { + res.push(word1[ptr1++]); + res.push(word2[ptr2++]); + } else if (ptr1 > len1 || ptr2 < len2) { + res.push(word2[ptr2++]); + } else if (ptr1 < len1 || ptr2 > len2) { + res.push(word1[ptr1++]); + } + } + return res.join(""); +} From 7fe393e2bd42b8b01e06bc6c4a2981631c32574c Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Tue, 21 Feb 2023 11:53:19 +0100 Subject: [PATCH 60/70] add 1043 ts solution --- Problems/23-Partition-Array-for-Maximum-Sum/1043.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Problems/23-Partition-Array-for-Maximum-Sum/1043.ts diff --git a/Problems/23-Partition-Array-for-Maximum-Sum/1043.ts b/Problems/23-Partition-Array-for-Maximum-Sum/1043.ts new file mode 100644 index 0000000..7ad43b2 --- /dev/null +++ b/Problems/23-Partition-Array-for-Maximum-Sum/1043.ts @@ -0,0 +1,13 @@ +function maxSumAfterPartitioning(arr: number[], k: number): number { + let dp: number[] = []; + dp[0] = 0; + dp[1] = arr[0]; + for (let i = 1; i <= arr.length; i++) { + let m = -1; + for (let j = 1; j <= Math.min(i, k); j++) { + m = Math.max(m, arr[i - j]); + dp[i] = dp[i] ? Math.max(dp[i], dp[i - j] + m * j) : dp[i - j] + m * j; + } + } + return dp[arr.length]; +} From 1b80f7d90ed48ecbb15d260c397da443b817c005 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 23 Feb 2023 17:40:04 +0100 Subject: [PATCH 61/70] Add C++ Solution --- Problems/.DS_Store | Bin 18436 -> 18436 bytes .../Egg-Drop-With-2-Eggs-and-N-Floors.cpp | 20 ++++++++++++ .../Number-of-Good-Ways-to-Split-a-String.cpp | 23 ++++++++++++++ .../Minimum-Sideway-Jumps.cpp | 29 ++++++++++++++++++ .../31-Delete-and-Earn/Delete-and-Earn.cpp | 15 +++++++++ README.md | 4 +++ 6 files changed, 91 insertions(+) create mode 100644 Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/Egg-Drop-With-2-Eggs-and-N-Floors.cpp create mode 100644 Problems/29-Number-of-Good-Ways-to-Split-a-String/Number-of-Good-Ways-to-Split-a-String.cpp create mode 100644 Problems/30-Minimum-Sideway-Jumps/Minimum-Sideway-Jumps.cpp create mode 100644 Problems/31-Delete-and-Earn/Delete-and-Earn.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index 7a8b365f6e0c83cd0701d3d8e4ea680b1ca4e5d3..f7a78eae88c0618bd76a0020d31ed8f4eb258671 100644 GIT binary patch delta 1173 zcmZpfz}PZ@ae_Z%-Nu03{EQ}(;}~@|TL?_%(3N2@VlZdWWe8_TWT<2)2C_;R@`0o; zke|(v3S=b$u^W)gWGI^KpeJ8Xk`AC=M}{IG1e%_k@8XhDT9VAb@Ib=(g(n9C0|Oam zO%Br+G$l*_d8ZvM#&++XF*}2(#;naVW^}6j-p6U^o$GGZsxw zFcme{04lWvhfgU(E<+M9%@hH7`3z}5(j6RHpwL4}Uz4j$<=k@84TF>Oa|?i;g#mJn zLJmJyzL)wy^T;;}5n7ZPq*i9Ovfl`$!+70L%^^g!wgs;SUiv=&k#`3n0#8|tpIZJbNhc&Ycq!w LGvj7%g`esGa<%Qy delta 97 zcmZpfz}PZ@ae_Z%!N!2y{ETXo;}~@|TL?_%n9MErmMJHF@+~<9Jr|dh(voBbh6fVP rFFZLI7#P^nwL)q`cvIW`zC~K*=BJ>@Z|0C^W?Zbm#JZVV;iozP6~!L? diff --git a/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/Egg-Drop-With-2-Eggs-and-N-Floors.cpp b/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/Egg-Drop-With-2-Eggs-and-N-Floors.cpp new file mode 100644 index 0000000..4319af8 --- /dev/null +++ b/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/Egg-Drop-With-2-Eggs-and-N-Floors.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int solve(int k, int n, vector& dp) + { + if (k == 1) return n; + if (dp[n] != 0) return dp[n]; + for (int i = 1; i <= n; i++) + { + int tmp = 1 + max(solve(k-1, i-1, dp), solve(k, n-i, dp)); + if (dp[n] == 0) dp[n] = tmp; + else dp[n] = min(dp[n], tmp); + } + return dp[n]; + } + + int twoEggDrop(int n) { + vector dp(n+1, 0); + return solve(2, n, dp); + } +}; \ No newline at end of file diff --git a/Problems/29-Number-of-Good-Ways-to-Split-a-String/Number-of-Good-Ways-to-Split-a-String.cpp b/Problems/29-Number-of-Good-Ways-to-Split-a-String/Number-of-Good-Ways-to-Split-a-String.cpp new file mode 100644 index 0000000..c644d64 --- /dev/null +++ b/Problems/29-Number-of-Good-Ways-to-Split-a-String/Number-of-Good-Ways-to-Split-a-String.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int numSplits(string s) { + int n = s.length(); + vector right(n+1, 0); + + unordered_set ss; + for (int i = n-1; i >= 0; i--) + { + ss.insert(s[i]); + right[i] = ss.size(); + } + + ss.clear(); + int ans = 0; + for (int i = 0; i < n; i++) + { + ss.insert(s[i]); + if (ss.size() == right[i+1]) ans++; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/30-Minimum-Sideway-Jumps/Minimum-Sideway-Jumps.cpp b/Problems/30-Minimum-Sideway-Jumps/Minimum-Sideway-Jumps.cpp new file mode 100644 index 0000000..8788a8c --- /dev/null +++ b/Problems/30-Minimum-Sideway-Jumps/Minimum-Sideway-Jumps.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minSideJumps(vector& obstacles) { + int n = obstacles.size(); + vector> dp(n, vector(3,0)); + dp[0][0] = dp[0][2] = 1; + + for (int i = 1; i < n; i++) + { + for (int j = 0; j < 3; j++) + { + dp[i][j] = INT_MAX-1; + if (obstacles[i] - 1 == j) continue; + + if (obstacles[i-1] -1 != j) dp[i][j] = min(dp[i][j], dp[i-1][j]); + + int lane = (j+1) % 3; + if (obstacles[i-1] -1 != lane && obstacles[i] -1 != lane) dp[i][j] = min(dp[i][j], dp[i-1][lane]+1); + + lane = (j+2) % 3; + if (obstacles[i-1] -1 != lane && obstacles[i] -1 != lane) dp[i][j] = min(dp[i][j], dp[i-1][lane]+1); + } + } + + int ans = INT_MAX; + for (int j = 0; j < 3; j++) ans = min(ans, dp[n-1][j]); + return ans; + } +}; \ No newline at end of file diff --git a/Problems/31-Delete-and-Earn/Delete-and-Earn.cpp b/Problems/31-Delete-and-Earn/Delete-and-Earn.cpp new file mode 100644 index 0000000..857a784 --- /dev/null +++ b/Problems/31-Delete-and-Earn/Delete-and-Earn.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int deleteAndEarn(vector& nums) { + unordered_map m; + for (auto x: nums) m[x]++; + + vector dp(10001, 0); + dp[1] = m[1]; + for (int i = 2; i <= 10000; i++) + { + dp[i] = max(dp[i-2] + i * m[i], dp[i-1]); + } + return dp[10000]; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index 2d3aaee..5439ade 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,10 @@ Solutions in various programming languages are provided. Enjoy it. 25. 2023/02/16 [#926 Flip String to Monotone Increasing](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/25-Flip-String-to-Monotone-Increasing): DP 26. 2023/02/17 [#935 Knight Dialer](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/26-Knight-Dialer): DP 27. 2023/02/18 [#1664 Ways to Make a Fair Array](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/27-Ways-to-Make-a-Fair-Array): DP +28. 2023/02/19 [#1884 Egg Drop With 2 Eggs and N Floors](): DP +29. 2023/02/20 [#1525 Number of Good Ways to Split a String](): DP +30. 2023/02/21 [#1824 Minimum Sideway Jumps](): DP +31. 2023/02/22 [#740 Delete and Earn](): DP ## Weekly Contest From 2b97495ce31419c391d971fe99375d5ba4c0def5 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 23 Feb 2023 17:41:31 +0100 Subject: [PATCH 62/70] Update Readme --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5439ade..da513ee 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,10 @@ Solutions in various programming languages are provided. Enjoy it. 25. 2023/02/16 [#926 Flip String to Monotone Increasing](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/25-Flip-String-to-Monotone-Increasing): DP 26. 2023/02/17 [#935 Knight Dialer](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/26-Knight-Dialer): DP 27. 2023/02/18 [#1664 Ways to Make a Fair Array](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/27-Ways-to-Make-a-Fair-Array): DP -28. 2023/02/19 [#1884 Egg Drop With 2 Eggs and N Floors](): DP -29. 2023/02/20 [#1525 Number of Good Ways to Split a String](): DP -30. 2023/02/21 [#1824 Minimum Sideway Jumps](): DP -31. 2023/02/22 [#740 Delete and Earn](): DP +28. 2023/02/19 [#1884 Egg Drop With 2 Eggs and N Floors](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors): DP +29. 2023/02/20 [#1525 Number of Good Ways to Split a String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/29-Number-of-Good-Ways-to-Split-a-String): DP +30. 2023/02/21 [#1824 Minimum Sideway Jumps](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/30-Minimum-Sideway-Jumps): DP +31. 2023/02/22 [#740 Delete and Earn](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/31-Delete-and-Earn): DP ## Weekly Contest From 846fd74ea5edabe38cbafe96fb520aff78f11761 Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Sat, 25 Feb 2023 12:23:59 +0100 Subject: [PATCH 63/70] add 1706 ts solution --- Problems/24-Where-Will-the-Ball-Fall/1706.ts | 33 ++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Problems/24-Where-Will-the-Ball-Fall/1706.ts diff --git a/Problems/24-Where-Will-the-Ball-Fall/1706.ts b/Problems/24-Where-Will-the-Ball-Fall/1706.ts new file mode 100644 index 0000000..a1c313c --- /dev/null +++ b/Problems/24-Where-Will-the-Ball-Fall/1706.ts @@ -0,0 +1,33 @@ +function findBall(grid: number[][]): number[] { + let m = grid.length; + let n = grid[0].length; + let res: number[] = []; + + for (let i = 0; i < n; i++) { + let x = 0, + y = i; + while (x < m) { + if (grid[x][y] === 1) { + if (y === n - 1) { + break; + } else if (grid[x][y + 1] === -1) { + break; + } + x++; + y++; + } else { + if (y === 0) { + break; + } else if (grid[x][y - 1] === 1) { + break; + } + x++; + y--; + } + } + if (x === m) { + res.push(y); + } else res.push(-1); + } + return res; +} From 4155bb3a8ebe079b2de3cf0bf5f92bea9350c901 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 26 Feb 2023 22:21:14 +0100 Subject: [PATCH 64/70] Add C++ --- Problems/.DS_Store | Bin 18436 -> 18436 bytes .../Minimum-Total-Importance-of-Roads.cpp | 24 +++++++++++++ .../Maximum-Star-Sum-of-Graph.cpp | 32 ++++++++++++++++++ .../Course-Schedule-IV.cpp | 24 +++++++++++++ README.md | 3 ++ 5 files changed, 83 insertions(+) create mode 100644 Problems/32-Minimum-Total-Importance-of-Roads/Minimum-Total-Importance-of-Roads.cpp create mode 100644 Problems/33-Maximum-Star-Sum-of-Graph/Maximum-Star-Sum-of-Graph.cpp create mode 100644 Problems/34-Course-Schedule-IV/Course-Schedule-IV.cpp diff --git a/Problems/.DS_Store b/Problems/.DS_Store index f7a78eae88c0618bd76a0020d31ed8f4eb258671..107a95d180807e6a569918f350bc5e5a6bfdfa65 100644 GIT binary patch delta 856 zcmZpfz}PZ@ae_Z%=f(g*#>s~T^(XHT65hO+F@ulMbaH~Q&1M#1PHtsm215p21{a1@ zh8!R+0b*T-M20+u6d>&iWEC;wO*W7dttUcVZoZ34N@+LrB zLQr2GHis2t7zQWj=N14hf&mqvg+@T9`!Zw#J(05#B6$qSV6*cX(tvV7K=DL|l*u0iMeC_#7DF*oz$n&a3uFKtON80=#5fdWI6U-7 zFq{ap8B-=Fn2NH>07KMxa)XGdIVk*!fMFC24O2*nxdX)#f#I2vla3J^MC(Nfp&mIl zUES>H8WnGpIB(Wm|H=BQE9ROqt#|NgY)c@Z<}jQ?qC#} S>>;4B*-RjSY4Zsy8(sj&E4DBI delta 122 zcmV-=0EPdAkO72{0gz7tez8yy0h3WUDU(1r5R*_aK(pEbF%AJVvragA0+WV1GLw)2 z6O&sIIkQL*2@8`6A0w0W9@8BiM*rC=00006XDU>ER1IZ^PWD+jaA+}8V{dJ6lMw>z cqYEGq0T`1I0XnlrFwY0G6)5rtvj;%^2YhrV(f|Me diff --git a/Problems/32-Minimum-Total-Importance-of-Roads/Minimum-Total-Importance-of-Roads.cpp b/Problems/32-Minimum-Total-Importance-of-Roads/Minimum-Total-Importance-of-Roads.cpp new file mode 100644 index 0000000..7ad49c5 --- /dev/null +++ b/Problems/32-Minimum-Total-Importance-of-Roads/Minimum-Total-Importance-of-Roads.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + long long maximumImportance(int n, vector>& roads) { + vector a(50000, 0); + for (auto& e: roads) + { + a[e[0]]++; + a[e[1]]++; + } + + sort(a.begin(), a.end()); + long long ans = 0; + long long j = n; + for (int i = 50000-1; i >=0; i--) + { + if (a[i]) + { + ans += a[i] * j; + j--; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/33-Maximum-Star-Sum-of-Graph/Maximum-Star-Sum-of-Graph.cpp b/Problems/33-Maximum-Star-Sum-of-Graph/Maximum-Star-Sum-of-Graph.cpp new file mode 100644 index 0000000..a67f26b --- /dev/null +++ b/Problems/33-Maximum-Star-Sum-of-Graph/Maximum-Star-Sum-of-Graph.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int maxStarSum(vector& vals, vector>& edges, int k) { + int n = vals.size(); + vector> a(n, vector()); + + for (auto& e: edges) + { + a[e[0]].push_back(vals[e[1]]); + a[e[1]].push_back(vals[e[0]]); + } + + for (int i = 0; i < n; i++) + { + sort(a[i].begin(), a[i].end(), greater()); + } + + int ans = INT_MIN; + for (int i = 0; i < n; i++) + { + int sum = vals[i]; + int m = (k < a[i].size())?k:a[i].size(); + for (int j = 0; j < m; j++) + { + if (a[i][j] > 0) sum += a[i][j]; + else break; + } + if (sum > ans) ans = sum; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/34-Course-Schedule-IV/Course-Schedule-IV.cpp b/Problems/34-Course-Schedule-IV/Course-Schedule-IV.cpp new file mode 100644 index 0000000..e525c6d --- /dev/null +++ b/Problems/34-Course-Schedule-IV/Course-Schedule-IV.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector checkIfPrerequisite(int numCourses, vector>& prerequisites, vector>& queries) { + vector> dp(numCourses, vector(numCourses, false)); + for (auto& e: prerequisites) + { + dp[e[0]][e[1]] = true; + } + + for (int k = 0; k < numCourses; k++) + for (int i = 0; i < numCourses; i++) + for (int j = 0; j < numCourses; j++) + { + dp[i][j] = dp[i][j] or (dp[i][k] and dp[k][j]); + } + + vector ans; + for (auto& q: queries) + { + ans.push_back(dp[q[0]][q[1]]); + } + return ans; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index da513ee..5663eec 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,9 @@ Solutions in various programming languages are provided. Enjoy it. 29. 2023/02/20 [#1525 Number of Good Ways to Split a String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/29-Number-of-Good-Ways-to-Split-a-String): DP 30. 2023/02/21 [#1824 Minimum Sideway Jumps](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/30-Minimum-Sideway-Jumps): DP 31. 2023/02/22 [#740 Delete and Earn](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/31-Delete-and-Earn): DP +32. 2023/02/23 [#2285 Maximum Total Importance of Roads](): Star Graph +33. 2023/02/24 [#2497 Maximum Star Sum of a Graph](): Star Graph +34. 2023/02/25 [#1462 Course Schedule IV](): Graph, Floyd ## Weekly Contest From d9db13f0ef16e63a1a6443d53e5d635bd1708728 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 26 Feb 2023 22:22:34 +0100 Subject: [PATCH 65/70] Update Readme --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5663eec..60e20a8 100644 --- a/README.md +++ b/README.md @@ -37,9 +37,9 @@ Solutions in various programming languages are provided. Enjoy it. 29. 2023/02/20 [#1525 Number of Good Ways to Split a String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/29-Number-of-Good-Ways-to-Split-a-String): DP 30. 2023/02/21 [#1824 Minimum Sideway Jumps](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/30-Minimum-Sideway-Jumps): DP 31. 2023/02/22 [#740 Delete and Earn](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/31-Delete-and-Earn): DP -32. 2023/02/23 [#2285 Maximum Total Importance of Roads](): Star Graph -33. 2023/02/24 [#2497 Maximum Star Sum of a Graph](): Star Graph -34. 2023/02/25 [#1462 Course Schedule IV](): Graph, Floyd +32. 2023/02/23 [#2285 Maximum Total Importance of Roads](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/32-Minimum-Total-Importance-of-Roads): Star Graph +33. 2023/02/24 [#2497 Maximum Star Sum of a Graph](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/33-Maximum-Star-Sum-of-Graph): Star Graph +34. 2023/02/25 [#1462 Course Schedule IV](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/34-Course-Schedule-IV): Graph, Floyd ## Weekly Contest From b72e16a53542a654afcdb158f4d457a53943a6f0 Mon Sep 17 00:00:00 2001 From: qinyii Date: Tue, 28 Feb 2023 15:22:25 +0100 Subject: [PATCH 66/70] add Python 23,24,25,26 solutions --- .../Partition_Array_for_Max_Sum.py | 21 +++++++++++++++ .../Where-Will-the-Ball-Fall.py | 26 +++++++++++++++++++ .../Flip-String-to-Monotone-Increasing.py | 17 ++++++++++++ Problems/26-Knight-Dialer/Knight-Dialer.py | 18 +++++++++++++ 4 files changed, 82 insertions(+) create mode 100644 Problems/23-Partition-Array-for-Maximum-Sum/Partition_Array_for_Max_Sum.py create mode 100644 Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.py create mode 100644 Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.py create mode 100644 Problems/26-Knight-Dialer/Knight-Dialer.py diff --git a/Problems/23-Partition-Array-for-Maximum-Sum/Partition_Array_for_Max_Sum.py b/Problems/23-Partition-Array-for-Maximum-Sum/Partition_Array_for_Max_Sum.py new file mode 100644 index 0000000..31cc9bd --- /dev/null +++ b/Problems/23-Partition-Array-for-Maximum-Sum/Partition_Array_for_Max_Sum.py @@ -0,0 +1,21 @@ +class Solution(object): + def maxSumAfterPartitioning(self, arr, k): + """ + :type arr: List[int] + :type k: int + :rtype: int + """ + n = len(arr) + res = [0] * (n+1) + + for i in range(1, n+1): + max_val = 0 + for j in range(1, k+1): + pos = i - j + if pos < 0: + break + if arr[pos] > max_val: + max_val = arr[pos] + res[i] = max(res[i], max_val * j + res[pos]) + return res[-1] + \ No newline at end of file diff --git a/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.py b/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.py new file mode 100644 index 0000000..d3f2587 --- /dev/null +++ b/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.py @@ -0,0 +1,26 @@ +class Solution(object): + def findBall(self, grid): + """ + :type grid: List[List[int]] + :rtype: List[int] + """ + n = len(grid[0]) + ans = [-1] * n + for i in range(n): + col = i + print(col) + for row in grid: + dir = row[col] + col += dir + if col < 0 or col == n or row[col] != dir: + break + else: + ans[i] = col + return ans + + + + + +grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] +print(Solution().findBall(grid)) \ No newline at end of file diff --git a/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.py b/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.py new file mode 100644 index 0000000..10b3ee9 --- /dev/null +++ b/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.py @@ -0,0 +1,17 @@ +class Solution(object): + def minFlipsMonoIncr(self, s): + """ + :type s: str + :rtype: int + """ + + #使得该分界点之前1的个数和分界点之后0的个数之和最小,把分界点之前的1变成0,之后的0变成1 + m=s.count('0') + res=[m] + for x in s: + if x=='1': + m+=1 + else: + m-=1 + res.append(m) + return min(res) \ No newline at end of file diff --git a/Problems/26-Knight-Dialer/Knight-Dialer.py b/Problems/26-Knight-Dialer/Knight-Dialer.py new file mode 100644 index 0000000..2fdb273 --- /dev/null +++ b/Problems/26-Knight-Dialer/Knight-Dialer.py @@ -0,0 +1,18 @@ +class Solution(object): + def knightDialer(self, n): + """ + :type n: int + :rtype: int + """ + if n==1: + return 10 + #A:{1,3,7,9}, B:{2,8}, C:{4,6}, D:{0} + # 处于状态A中的数字(1,3,7,9)通过一次跳跃要么变成状态B(2,8),要么变成状态C(4,6) + # 处于状态B中的数字(2,8)通过一次跳跃有两种方式变成状态A(1,3,7,9) + # 处于状态C中的数字(4,6)通过一次跳跃有两种方式变成状态A(1,3,7,9),还有一种方式变成状态D(0) + # 处于状态D中的数字(0)通过一次跳跃有两种方式变成状态C(4,6) + + nums=[1,1,1,1] + for _ in range(n-1): + nums=[nums[1]+nums[2], 2*nums[0], 2*nums[0]+nums[3], 2*nums[2]] + return (4*nums[0]+2*nums[1]+2*nums[2]+nums[3])%1000000007 From 35ff1c6bc9c6b82dc5d02af0013c99b9a9fd6cb3 Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Wed, 1 Mar 2023 14:33:01 +0100 Subject: [PATCH 67/70] add 926 ts solution --- .../25-Flip-String-to-Monotone-Increasing/926.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Problems/25-Flip-String-to-Monotone-Increasing/926.ts diff --git a/Problems/25-Flip-String-to-Monotone-Increasing/926.ts b/Problems/25-Flip-String-to-Monotone-Increasing/926.ts new file mode 100644 index 0000000..a7fe4c3 --- /dev/null +++ b/Problems/25-Flip-String-to-Monotone-Increasing/926.ts @@ -0,0 +1,13 @@ +function minFlipsMonoIncr(s: string): number { + let countOne: number = 0; + let flip: number = 0; + for (let i of s) { + if (i === "1") { + countOne++; + } else { + flip++; + flip = Math.min(countOne, flip); + } + } + return flip; +} From 8cbb2a683fbdc1643a81677650edc519843509c7 Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Wed, 1 Mar 2023 19:39:01 +0100 Subject: [PATCH 68/70] add 935 ts solution --- Problems/26-Knight-Dialer/935.ts | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Problems/26-Knight-Dialer/935.ts diff --git a/Problems/26-Knight-Dialer/935.ts b/Problems/26-Knight-Dialer/935.ts new file mode 100644 index 0000000..627399b --- /dev/null +++ b/Problems/26-Knight-Dialer/935.ts @@ -0,0 +1,40 @@ +function knightDialer(n: number): number { + let dp: number[][] = new Array(4).fill(new Array(3)); + const M = 1000000007; + dp = [ + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [0, 1, 0], + ]; + + for (let i = 1; i < n; i++) { + let newDp: number[][]; + newDp = [ + [ + (dp[2][1] + dp[1][2]) % M, + (dp[2][0] + dp[2][2]) % M, + (dp[1][0] + dp[2][1]) % M, + ], + [ + (dp[0][2] + dp[2][2] + dp[3][1]) % M, + 0, + (dp[0][0] + dp[2][0] + dp[3][1]) % M, + ], + [ + (dp[0][1] + dp[1][2]) % M, + (dp[0][0] + dp[0][2]) % M, + (dp[1][0] + dp[0][1]) % M, + ], + [0, (dp[1][0] + dp[1][2]) % M, 0], + ]; + dp = newDp; + } + let res = 0; + for (let i = 0; i < 4; i++) { + for (let j = 0; j < 3; j++) { + res += dp[i][j]; + } + } + return res % 1000000007; +} From 7db4c63fafbe1ae4fa5ef020d515db1d92f5d7a9 Mon Sep 17 00:00:00 2001 From: jeremyxu Date: Thu, 2 Mar 2023 11:13:42 +0100 Subject: [PATCH 69/70] add 1664 ts solution --- Problems/27-Ways-to-Make-a-Fair-Array/1664.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Problems/27-Ways-to-Make-a-Fair-Array/1664.ts diff --git a/Problems/27-Ways-to-Make-a-Fair-Array/1664.ts b/Problems/27-Ways-to-Make-a-Fair-Array/1664.ts new file mode 100644 index 0000000..238d6f4 --- /dev/null +++ b/Problems/27-Ways-to-Make-a-Fair-Array/1664.ts @@ -0,0 +1,25 @@ +function waysToMakeFair(nums: number[]): number { + const n: number = nums.length; + nums.unshift(0); + let leftEven: number[] = new Array(n + 1).fill(0); + let leftOdd: number[] = new Array(n + 1).fill(0); + let leftEvenSum = 0, + leftOddSum = 0; + for (let i = 1; i <= n; i++) { + if (i % 2 === 0) leftEvenSum += nums[i]; + else leftOddSum += nums[i]; + leftEven[i] = leftEvenSum; + leftOdd[i] = leftOddSum; + } + let rightEvenSum = 0, + rightOddSum = 0; + let res = 0; + for (let i = n; i >= 1; i--) { + if (leftEven[i - 1] + rightOddSum === leftOdd[i - 1] + rightEvenSum) { + res++; + } + if (i % 2 === 0) rightEvenSum += nums[i]; + else rightOddSum += nums[i]; + } + return res; +} From ff52ff133c40309ebe439929f67c3b820781ff29 Mon Sep 17 00:00:00 2001 From: jeremyxxxuuu Date: Fri, 10 Mar 2023 14:44:24 +0100 Subject: [PATCH 70/70] add 1525 ts solution --- .../1884.ts | 21 +++++++++++++++++++ .../1525.ts | 19 +++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/1884.ts create mode 100644 Problems/29-Number-of-Good-Ways-to-Split-a-String/1525.ts diff --git a/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/1884.ts b/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/1884.ts new file mode 100644 index 0000000..c432a4f --- /dev/null +++ b/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/1884.ts @@ -0,0 +1,21 @@ +function twoEggDrop(n: number): number { + + let dp : number[][] = Array.from(Array(3), () => new Array(n+1)) + + dp[1][0] = 0; + dp[2][0] = 0; + + for(let i = 1; i <= n; i++) { + dp[1][i] = i; + } + + for(let i = 1; i <= n; i++) { + for(let j = 1; j <= i; j++) { + dp[2][i] = dp[2][i]!==undefined? Math.min(dp[2][i], 1+Math.max(dp[1][j-1],dp[2][i-j])) : 1+Math.max(dp[1][j-1],dp[2][i-j]) + } + } + + return dp[2][n]; + + +}; \ No newline at end of file diff --git a/Problems/29-Number-of-Good-Ways-to-Split-a-String/1525.ts b/Problems/29-Number-of-Good-Ways-to-Split-a-String/1525.ts new file mode 100644 index 0000000..5b03cfc --- /dev/null +++ b/Problems/29-Number-of-Good-Ways-to-Split-a-String/1525.ts @@ -0,0 +1,19 @@ +function numSplits(s: string): number { + const left_set = new Set(); + const right_set = new Set(); + let arr = []; + let res = 0; + + for(let i=0; i=0; i--) { + right_set.add(s[i]); + if(right_set.size === arr[i-1]){ + res++ + } + } + return res; + +}; \ No newline at end of file