From f9573e406a1bd96556530fbbdfa68e4f9c7c1dcb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Sep 2021 16:32:57 -0700 Subject: [PATCH 0001/2729] Create 2018.Check-if-Word-Can-Be-Placed-In-Crossword.cpp --- ...eck-if-Word-Can-Be-Placed-In-Crossword.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword/2018.Check-if-Word-Can-Be-Placed-In-Crossword.cpp diff --git a/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword/2018.Check-if-Word-Can-Be-Placed-In-Crossword.cpp b/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword/2018.Check-if-Word-Can-Be-Placed-In-Crossword.cpp new file mode 100644 index 000000000..335ab53cd --- /dev/null +++ b/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword/2018.Check-if-Word-Can-Be-Placed-In-Crossword.cpp @@ -0,0 +1,46 @@ +class Solution { + int m,n; + vector>dir; +public: + bool match(vector>& board, int i, int j, int k, string word) + { + for (int t=0; t=m||y<0||y>=n) return false; + if (board[x][y]!=' '&&board[x][y]!=word[t]) + return false; + } + int t = word.size(); + int x = i+dir[k].first*t; + int y = j+dir[k].second*t; + if (x>=0&&x=0&&y>& board, string word) + { + m = board.size(); + n = board[0].size(); + dir = {{1,0},{-1,0},{0,1},{0,-1}}; + + for (int i=0; i=0 && x=0 && y Date: Sun, 26 Sep 2021 16:37:13 -0700 Subject: [PATCH 0002/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword/Readme.md diff --git a/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword/Readme.md b/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword/Readme.md new file mode 100644 index 000000000..57bbefbaa --- /dev/null +++ b/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword/Readme.md @@ -0,0 +1,9 @@ +### 2018.Check-if-Word-Can-Be-Placed-In-Crossword + +此题就是暴力搜索。 + +搜索的关键是找一个起点格子和方向。起点给子的要求是:1. 靠着边界或者一个#符号。2. 格子本身是空格或者word[0]. 3. 在条件1的反方向一侧是我们的尝试匹配的方向。 + +匹配的要求是:1. 一路所经过的格子恰好是word,允许其中有空格。2. 匹配完之后再走一步的话,必须是边界或者一个#符号。 + +了解了这些要求之后,代码就不难写了。 From 1b62dbb2ebb1a03d8717372d65b81a176bc50e36 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Sep 2021 16:38:56 -0700 Subject: [PATCH 0003/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f45ab21f0..cd07362ab 100644 --- a/Readme.md +++ b/Readme.md @@ -1083,6 +1083,7 @@ [1862.Sum-of-Floored-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Others/1862.Sum-of-Floored-Pairs) (M+) [1904.The-Number-of-Full-Rounds-You-Have-Played](https://github.com/wisdompeak/LeetCode/tree/master/Others/1904.The-Number-of-Full-Rounds-You-Have-Played) (M) [1997.First-Day-Where-You-Have-Been-in-All-the-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/1997.First-Day-Where-You-Have-Been-in-All-the-Rooms) (H) +[2018.Check-if-Word-Can-Be-Placed-In-Crossword](https://github.com/wisdompeak/LeetCode/tree/master/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword) (M+) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 7502f12d8e432e325e5ecb8307579c205500dd6b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Sep 2021 18:02:04 -0700 Subject: [PATCH 0004/2729] Create 241.Different-Ways-to-Add-Parentheses_v2.cpp --- ...1.Different-Ways-to-Add-Parentheses_v2.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Recursion/241.Different-Ways-to-Add-Parentheses/241.Different-Ways-to-Add-Parentheses_v2.cpp diff --git a/Recursion/241.Different-Ways-to-Add-Parentheses/241.Different-Ways-to-Add-Parentheses_v2.cpp b/Recursion/241.Different-Ways-to-Add-Parentheses/241.Different-Ways-to-Add-Parentheses_v2.cpp new file mode 100644 index 000000000..0104f5e14 --- /dev/null +++ b/Recursion/241.Different-Ways-to-Add-Parentheses/241.Different-Ways-to-Add-Parentheses_v2.cpp @@ -0,0 +1,50 @@ +class Solution { + vectornums; + vectorops; + +public: + vector diffWaysToCompute(string input) + { + for (int i=0; i>>dp(n, vector>(n)); + helper(dp, 0, n-1); + return dp[0][n-1]; + } + + void helper(vector>>&dp, int a, int b) + { + if (!dp[a][b].empty()) + return; + if (a==b) + { + dp[a][b] = {nums[a]}; + return; + } + + for (int i=a; i Date: Sun, 26 Sep 2021 20:45:14 -0700 Subject: [PATCH 0005/2729] Update Readme.md --- Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md b/Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md index 8d747f643..30e6d81b2 100644 --- a/Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md +++ b/Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md @@ -1,6 +1,6 @@ ### 241.Different-Ways-to-Add-Parentheses -此题只要想到,任何多项式运算最终可以化简为最后的双目运算.只要确定这个双目运算符的位置,其前后两端用递归处理就行了. +此题只要想到,任何多项式运算最终可以化简为最后的双目运算。只要遍历这个双目运算符的位置,其将运算符前后两部分都用递归处理,然后这两部分的结果再两两组合即可. -[Leetcode Link](https://leetcode.com/problems/different-ways-to-add-parentheses) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/different-ways-to-add-parentheses) From 1a00847fd83827722684cb24b8b0fd38ae62fa6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Sep 2021 20:45:36 -0700 Subject: [PATCH 0006/2729] Update Readme.md --- Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md b/Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md index 30e6d81b2..181db6851 100644 --- a/Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md +++ b/Recursion/241.Different-Ways-to-Add-Parentheses/Readme.md @@ -1,6 +1,6 @@ ### 241.Different-Ways-to-Add-Parentheses -此题只要想到,任何多项式运算最终可以化简为最后的双目运算。只要遍历这个双目运算符的位置,其将运算符前后两部分都用递归处理,然后这两部分的结果再两两组合即可. +此题的突破口:任何多项式运算最终可以化简为最后的双目运算。只要遍历这个“最终的”双目运算符的位置,其将运算符前后两部分都用递归处理,然后这两部分的结果再两两组合即可. [Leetcode Link](https://leetcode.com/problems/different-ways-to-add-parentheses) From a6615480df5b09f46fbd999f798dc24d6ccf6af1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Sep 2021 21:43:36 -0700 Subject: [PATCH 0007/2729] Update 241.Different-Ways-to-Add-Parentheses_v2.cpp --- ...1.Different-Ways-to-Add-Parentheses_v2.cpp | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/Recursion/241.Different-Ways-to-Add-Parentheses/241.Different-Ways-to-Add-Parentheses_v2.cpp b/Recursion/241.Different-Ways-to-Add-Parentheses/241.Different-Ways-to-Add-Parentheses_v2.cpp index 0104f5e14..e982139e9 100644 --- a/Recursion/241.Different-Ways-to-Add-Parentheses/241.Different-Ways-to-Add-Parentheses_v2.cpp +++ b/Recursion/241.Different-Ways-to-Add-Parentheses/241.Different-Ways-to-Add-Parentheses_v2.cpp @@ -1,7 +1,7 @@ class Solution { vectornums; vectorops; - + vector dp[21][21]; public: vector diffWaysToCompute(string input) { @@ -10,18 +10,17 @@ class Solution { int j = i; while (j>>dp(n, vector>(n)); - helper(dp, 0, n-1); - return dp[0][n-1]; + helper(0, n-1); + return dp[0][n-1]; } - - void helper(vector>>&dp, int a, int b) + + void helper(int a, int b) { if (!dp[a][b].empty()) return; @@ -33,10 +32,10 @@ class Solution { for (int i=a; i Date: Sun, 26 Sep 2021 21:48:01 -0700 Subject: [PATCH 0008/2729] Create 2019.The-Score-of-Students-Solving-Math-Expression.cpp --- ...re-of-Students-Solving-Math-Expression.cpp | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 Recursion/2019.The-Score-of-Students-Solving-Math-Expression/2019.The-Score-of-Students-Solving-Math-Expression.cpp diff --git a/Recursion/2019.The-Score-of-Students-Solving-Math-Expression/2019.The-Score-of-Students-Solving-Math-Expression.cpp b/Recursion/2019.The-Score-of-Students-Solving-Math-Expression/2019.The-Score-of-Students-Solving-Math-Expression.cpp new file mode 100644 index 000000000..d277de41f --- /dev/null +++ b/Recursion/2019.The-Score-of-Students-Solving-Math-Expression/2019.The-Score-of-Students-Solving-Math-Expression.cpp @@ -0,0 +1,102 @@ +class Solution { + vectornums; + vectorops; + unordered_set dp[20][20]; +public: + int scoreOfStudents(string s, vector& answers) + { + for (int i=0; inums; + + for (int i=0; i Date: Sun, 26 Sep 2021 21:49:17 -0700 Subject: [PATCH 0009/2729] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index cd07362ab..a49462af4 100644 --- a/Readme.md +++ b/Readme.md @@ -809,12 +809,10 @@ [133.Clone-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/133.Clone-Graph) (M+) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (H-) [337.House-Robber-III](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/337.House-Robber-III) (M+) -[241.Different-Ways-to-Add-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/241.Different-Ways-to-Add-Parentheses) (H-) [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [397.Integer-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/397.Integer-Replacement) (M+) 440.K-th-Smallest-in-Lexicographical-Order (H) -[679.24-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/679.24-Game) (H) [761.Special-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/761.Special-Binary-String) (H) 779.K-th-Symbol-in-Grammar (M) [780.Reaching-Points](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/780.Reaching-Points) (H-) @@ -830,6 +828,10 @@ 1545. Find Kth Bit in Nth Binary String (TBD) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) +* ``Evaluate Expressions`` +[241.Different-Ways-to-Add-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/241.Different-Ways-to-Add-Parentheses) (M+) +[2019.The-Score-of-Students-Solving-Math-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2019.The-Score-of-Students-Solving-Math-Expression) (H-) +[679.24-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/679.24-Game) (H) * ``Min-Max Strategy`` [464.Can-I-Win](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/464.Can-I-Win) (M+) [877.Stone-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/877.Stone-Game) (M+) (aka. 486.Predict-the-Winner) From f8245637220a0267d3b12d01a653f081eafd3681 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Sep 2021 21:58:52 -0700 Subject: [PATCH 0010/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Recursion/2019.The-Score-of-Students-Solving-Math-Expression/Readme.md diff --git a/Recursion/2019.The-Score-of-Students-Solving-Math-Expression/Readme.md b/Recursion/2019.The-Score-of-Students-Solving-Math-Expression/Readme.md new file mode 100644 index 000000000..31efe40f8 --- /dev/null +++ b/Recursion/2019.The-Score-of-Students-Solving-Math-Expression/Readme.md @@ -0,0 +1,7 @@ +### 2019.The-Score-of-Students-Solving-Math-Expression + +此题的本质就是```227. Basic Calculator II```和```241. Different Ways to Add Parentheses```的组合。 + +LC227的代码可以得到按照乘法优先的运算顺序的计算结果。LC241的代码求得的就是按照任何组合顺序得到的计算结果(因为任意组合的顺序总是对应着某种符号添加方案)。如果answers里面的数值是前者,就可以得5分;否则如果在后者里,得2分;除此之外就得零分。 + +此外,本题的一个坑就是,任何中间过程,我们只保留数值小于1000的结果。否则会TLE。 From 16c2cf7d031eecc7954293ef3af217a2007d334a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 Sep 2021 22:46:15 -0700 Subject: [PATCH 0011/2729] Create Hash.cpp --- Template/CPP_LANG/Hash.cpp | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Template/CPP_LANG/Hash.cpp diff --git a/Template/CPP_LANG/Hash.cpp b/Template/CPP_LANG/Hash.cpp new file mode 100644 index 000000000..31df24315 --- /dev/null +++ b/Template/CPP_LANG/Hash.cpp @@ -0,0 +1,41 @@ +#include +// from boost (functional/hash): +// see http://www.boost.org/doc/libs/1_35_0/doc/html/hash/combine.html template +template +inline void hash_combine(std::size_t &seed, const T &val) { + seed ^= std::hash()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2); +} +// auxiliary generic functions to create a hash value using a seed +template inline void hash_val(std::size_t &seed, const T &val) { + hash_combine(seed, val); +} +template +inline void hash_val(std::size_t &seed, const T &val, const Types &... args) { + hash_combine(seed, val); + hash_val(seed, args...); +} + +template +inline std::size_t hash_val(const Types &... args) { + std::size_t seed = 0; + hash_val(seed, args...); + return seed; +} + +struct pair_hash { + template + std::size_t operator()(const std::pair &p) const { + return hash_val(p.first, p.second); + } +}; + +#include +using namespace std; +using ll = long long; + +int main() { + unordered_map, ll, pair_hash> slopeCount; + unordered_set, pair_hash> seen; + return 0; +} +// Reference: [C++ Standard Library: A tutorial and reference, Second version](https://www.mica.edu.vn/perso/Vu-Hai/EE3490/Ref/The%20C++Standard%20Library%20-%202nd%20Edition.pdf) Chapter 7.9.2: Creating and Controlling unordered Container From cc5094ab4ca70f0df9daf7efebc25450a4361783 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 Sep 2021 22:46:39 -0700 Subject: [PATCH 0012/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a49462af4..44d3df780 100644 --- a/Readme.md +++ b/Readme.md @@ -1140,3 +1140,4 @@ [Combination-Number](https://github.com/wisdompeak/LeetCode/tree/master/Template/Combination-Number) [RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) [IO](https://github.com/wisdompeak/LeetCode/tree/master/Template/IO) +[CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) From de938add30178b34c32af784e3900214994d5678 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Oct 2021 14:58:47 -0700 Subject: [PATCH 0013/2729] Update Readme.md --- .../Readme.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Hash/424.Longest-Repeating-Character-Replacement/Readme.md b/Hash/424.Longest-Repeating-Character-Replacement/Readme.md index 14fdd3d66..46e90c5e2 100644 --- a/Hash/424.Longest-Repeating-Character-Replacement/Readme.md +++ b/Hash/424.Longest-Repeating-Character-Replacement/Readme.md @@ -1,20 +1,21 @@ ### 424.Longest-Repeating-Character-Replacement -本题的本质就是用一个滑动窗口,查找最长的sub array,使得其最多含有k-1个与majority不相同的字符.这里majority指的是窗口中出现最多的那个字符. +本题的本质就是用一个滑动窗口,查找最长的subarray,使得其最多含有k个与majority不相同的字符.这里majority指的是窗口中出现最多的那个字符. -很显然,我们需要一个hash map或者字典来存放每个字符出现的次数.在不断拓宽窗口的过程中,如果 +很显然,我们需要一个hash map或者字典来存放每个字符出现的次数.在不断拓宽窗口的过程中保持 ``` -窗口长度数M - majority元素的个数N > K +窗口长度数L - majority元素的个数M <= K ``` -那么就需要移动左指针缩短窗口.为什么呢?因为如果只移动右指针,即使加入了majority元素,窗口内的那些非majority元素仍然多于K,使得整体无法成为一个合法的窗口. +如果不满足这个条件,那么就需要移动左指针一位,以缩短窗口.然后再尝试拓展右边界j。 + +细节分析: -分析: 1.为什么左指针移动之后不用更新结果? -这是因为,我们移动左指针的起因是之前s[j]的引入,它必然是一个非majority的字符(否则整个窗口应该会继续保持合法),而无论左指针弹出的是否majority元素,都不会得到更好的结果,最多持平,所以我们不需要更新结果. +这是因为,我们移动左指针的起因是之前s[j]的引入,它必然是一个非majority的字符(否则整个窗口应该会继续保持合法),而无论左指针弹出的是否majority元素,都不会得到更好的结果,最多持平,所以我们不需要更新结果。 2.为什么左指针移动只需要一步? 因为我们求最长的窗口,左指针的移动不用太大.事实上,只要移动左指针一步,那么整个窗口还是有机会通过移动右指针找到下一个可能的窗口.参看上面的那个公式. -[Leetcode Link](https://leetcode.com/problems/longest-repeating-character-replacement) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/longest-repeating-character-replacement) From 3a1d9aacf3a77b304906481bb289301a7bb32814 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Oct 2021 15:08:31 -0700 Subject: [PATCH 0014/2729] Update and rename 424.Longest-Repeating-Character-Replacement.cpp to 424.Longest-Repeating-Character-Replacement_v1.cpp --- ...ongest-Repeating-Character-Replacement.cpp | 25 --------------- ...est-Repeating-Character-Replacement_v1.cpp | 32 +++++++++++++++++++ 2 files changed, 32 insertions(+), 25 deletions(-) delete mode 100644 Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement.cpp create mode 100644 Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp diff --git a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement.cpp b/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement.cpp deleted file mode 100644 index afc0eb18c..000000000 --- a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - int characterReplacement(string s, int k) - { - vectorCount(26,0); - int i = 0; - int result = 0; - - for (int j=0; jcount; +public: + int characterReplacement(string s, int k) + { + int ret = 0; + int j = 0; + count.resize(26); + for (int i=0; i Date: Sat, 2 Oct 2021 15:09:30 -0700 Subject: [PATCH 0015/2729] Update 424.Longest-Repeating-Character-Replacement_v2.cpp --- .../424.Longest-Repeating-Character-Replacement_v2.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp b/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp index e8965c56a..f889157db 100644 --- a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp +++ b/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp @@ -2,7 +2,7 @@ class Solution { public: int characterReplacement(string s, int k) { - vectorCount(26,0); + vectorcount(26,0); int i = 0; int result = 0; @@ -11,7 +11,7 @@ class Solution { { Count[s[j]-'A']++; - while (j-i+1-*max_element(Count.begin(),Count.end()) >k) + while (j-i+1 - *max_element(Count.begin(),count.end()) > k) { Count[s[i]-'A']--; i++; From c2c91293f45d2efb8b3f2ebe448cfee437a08a77 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Oct 2021 15:10:05 -0700 Subject: [PATCH 0016/2729] Update 424.Longest-Repeating-Character-Replacement_v2.cpp --- .../424.Longest-Repeating-Character-Replacement_v2.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp b/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp index f889157db..94b50ded7 100644 --- a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp +++ b/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp @@ -9,11 +9,11 @@ class Solution { for (int j=0; j k) + while (j-i+1 - *max_element(count.begin(),count.end()) > k) { - Count[s[i]-'A']--; + count[s[i]-'A']--; i++; } result = max(result, j-i+1); From 95bf313afc5a750653d14e913c6105af2c860e19 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Oct 2021 15:37:19 -0700 Subject: [PATCH 0017/2729] Update 424.Longest-Repeating-Character-Replacement_v1.cpp --- ...est-Repeating-Character-Replacement_v1.cpp | 33 ++++++++----------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp b/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp index 089eb0a33..0688ac6f3 100644 --- a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp +++ b/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp @@ -1,32 +1,25 @@ -class Solution { - vectorcount; +class Solution { public: int characterReplacement(string s, int k) { int ret = 0; int j = 0; - count.resize(26); + vectorcount(26); for (int i=0; i Date: Sat, 2 Oct 2021 15:53:27 -0700 Subject: [PATCH 0018/2729] Create 2024.Maximize-the-Confusion-of-an-Exam.cpp --- ...2024.Maximize-the-Confusion-of-an-Exam.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam/2024.Maximize-the-Confusion-of-an-Exam.cpp diff --git a/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam/2024.Maximize-the-Confusion-of-an-Exam.cpp b/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam/2024.Maximize-the-Confusion-of-an-Exam.cpp new file mode 100644 index 000000000..aa209927a --- /dev/null +++ b/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam/2024.Maximize-the-Confusion-of-an-Exam.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int maxConsecutiveAnswers(string answerKey, int k) + { + int ret = 0; + int n = answerKey.size(); + + int flip = 0; + int j = 0; + for (int i=0; i Date: Sat, 2 Oct 2021 15:54:01 -0700 Subject: [PATCH 0019/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 44d3df780..1e1db003a 100644 --- a/Readme.md +++ b/Readme.md @@ -39,6 +39,7 @@ [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [1763.Longest-Nice-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1763.Longest-Nice-Substring) (H) [2009.Minimum-Number-of-Operations-to-Make-Array-Continuous](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2009.Minimum-Number-of-Operations-to-Make-Array-Continuous) (M+) +[2024.Maximize-the-Confusion-of-an-Exam](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam) (M) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 641ed549249050d6684ef456d564be00f612f6ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Oct 2021 16:03:17 -0700 Subject: [PATCH 0020/2729] Create Readme.md --- .../2024.Maximize-the-Confusion-of-an-Exam/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam/Readme.md diff --git a/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam/Readme.md b/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam/Readme.md new file mode 100644 index 000000000..547f53c06 --- /dev/null +++ b/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam/Readme.md @@ -0,0 +1,7 @@ +### 2024.Maximize-the-Confusion-of-an-Exam + +本题和```LC 1004. Max Consecutive Ones III```非常相似。本质就是找一段最长的subarray,使得滑窗满足:除了0之外只有最多k个1,或者除了1之外只有最多k个0. + +比较简单的写法就是将上面两种情况分为两次pass来做。比如考虑“若干个0 + k个1”的情况。固定左边界i,探索右边界j的最远位置,一路统计需要flip的次数(即1的个数)直至flip达到上限k。此时```j-i+1```就是一个合法的解区间。然后移动左边界```i+=1```,再次调整右边界j。同理,对于“若干个1 + k个0”的情况,类似的代码。 + +本题其实还有参考```LC 424. Longest Repeating Character Replacement```,有one pass的实现方法。 From 898ff0eb5dd41279d11c61a5eb521328910826a1 Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Sat, 2 Oct 2021 16:05:58 -0700 Subject: [PATCH 0021/2729] mv 424 --- .../424.Longest-Repeating-Character-Replacement_v1.cpp | 0 .../424.Longest-Repeating-Character-Replacement_v2.cpp | 0 .../424.Longest-Repeating-Character-Replacement/Readme.md | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {Hash => Two_Pointers}/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp (100%) rename {Hash => Two_Pointers}/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp (100%) rename {Hash => Two_Pointers}/424.Longest-Repeating-Character-Replacement/Readme.md (100%) diff --git a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp b/Two_Pointers/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp similarity index 100% rename from Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp rename to Two_Pointers/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp diff --git a/Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp b/Two_Pointers/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp similarity index 100% rename from Hash/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp rename to Two_Pointers/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v2.cpp diff --git a/Hash/424.Longest-Repeating-Character-Replacement/Readme.md b/Two_Pointers/424.Longest-Repeating-Character-Replacement/Readme.md similarity index 100% rename from Hash/424.Longest-Repeating-Character-Replacement/Readme.md rename to Two_Pointers/424.Longest-Repeating-Character-Replacement/Readme.md From c18d297364341bec0201f5190fbe21317860f6d0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Oct 2021 16:06:54 -0700 Subject: [PATCH 0022/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1e1db003a..ba42177d1 100644 --- a/Readme.md +++ b/Readme.md @@ -40,6 +40,7 @@ [1763.Longest-Nice-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1763.Longest-Nice-Substring) (H) [2009.Minimum-Number-of-Operations-to-Make-Array-Continuous](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2009.Minimum-Number-of-Operations-to-Make-Array-Continuous) (M+) [2024.Maximize-the-Confusion-of-an-Exam](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam) (M) +[424.Longest-Repeating-Character-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/424.Longest-Repeating-Character-Replacement) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) @@ -127,7 +128,6 @@ [356.Line-Reflection](https://github.com/wisdompeak/LeetCode/tree/master/Hash/356.Line-Reflection) (H-) [594.Longest-Harmonious-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Hash/594.Longest-Harmonious-Subsequence) (M+) [532.K-diff-Pairs-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/532.K-diff-Pairs-in-an-Array) (E+) -[424.Longest-Repeating-Character-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Hash/424.Longest-Repeating-Character-Replacement) (H) [446.Arithmetic-Slices-II-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Hash/446.Arithmetic-Slices-II-Subsequence) (H) [128.Longest-Consecutive-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/128.Longest-Consecutive-Sequence) (H-) [753.Cracking-the-Safe](https://github.com/wisdompeak/LeetCode/tree/master/Hash/753.Cracking-the-Safe) (H) From f3ddd03d597a6f96dbb9c0e82f2abb52329326b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Oct 2021 16:47:09 -0700 Subject: [PATCH 0023/2729] Update 424.Longest-Repeating-Character-Replacement_v1.cpp --- ...est-Repeating-Character-Replacement_v1.cpp | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/Two_Pointers/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp b/Two_Pointers/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp index 0688ac6f3..846968447 100644 --- a/Two_Pointers/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp +++ b/Two_Pointers/424.Longest-Repeating-Character-Replacement/424.Longest-Repeating-Character-Replacement_v1.cpp @@ -1,25 +1,31 @@ -class Solution { +class Solution { + vectorcount; public: int characterReplacement(string s, int k) { int ret = 0; int j = 0; - vectorcount(26); + count.resize(26); for (int i=0; i Date: Sat, 2 Oct 2021 21:00:05 -0700 Subject: [PATCH 0024/2729] Update Readme.md --- Stack/316.Remove-Duplicate-Letters/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Stack/316.Remove-Duplicate-Letters/Readme.md b/Stack/316.Remove-Duplicate-Letters/Readme.md index 867024f4e..d9401bdc0 100644 --- a/Stack/316.Remove-Duplicate-Letters/Readme.md +++ b/Stack/316.Remove-Duplicate-Letters/Readme.md @@ -2,11 +2,11 @@ 总体思想是贪心法,用stack做辅助。基本方法仍然是用手头的字符尽量维持一个递增字符序列,因为递增序列意味着字典序最小。 -首先,在维护栈的过程中,遇到已经用过的字符就跳过。比如当前待处理的字符是c,而当前的栈已经有c了,意味着什么呢?因为栈在维护着一个递增序列,说明c后面的字符要比c大。如果舍弃已经用过的c,那么必将导致后续的大字符前移,使得构建的栈内的单词字典序会变小。 +在维护栈的过程中,第一个原则是:遇到已经用过的字符就跳过。举个例子,假设当前待处理的字符是c,而发现当前栈里已经有c了,意味着什么呢?因为栈在维护着一个递增序列,说明栈里c后面的字符要比c大。如果舍弃已经栈里的c,那么必将导致后续的大字符前移,使得构建的栈内的单词字典序会变大。 -接下来,如果遇到非递增的字符,则大致方向就是退栈--处理掉一些栈顶元素,使得新加入的仍能保持递增。但需要注意,如果待退栈处理的字符在后面还有出现的机会,就放心退栈,扔到后面去考虑;如果后面已经没有再出现的机会,则保留这个栈顶元素同时结束退栈。所以需要一个Hash表来实时记录每个字符剩下来还会出现几次,也就是说每遍历一个字符,就把Map[s[i]]--. +第二个原则:如果遇到非递增的字符,则大致方向就是退栈,处理掉一些栈顶元素,使得新加入的仍能保持递增。但需要注意,如果待退栈处理的字符在后面还有出现的机会,就放心退栈,扔到后面去考虑;如果后面已经没有再出现的机会,则保留这个栈顶元素同时结束退栈。所以需要一个Hash表来实时记录每个字符剩下来还会出现几次,也就是说每遍历一个字符,就把Map[s[i]]--. 本题和1081. Smallest Subsequence of Distinct Characters一模一样。 -[Leetcode Link](https://leetcode.com/problems/remove-duplicate-letters) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/remove-duplicate-letters) From 34a92e58e9347f1ffaa820aaddc4add1b1fbef39 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Oct 2021 01:34:32 -0700 Subject: [PATCH 0025/2729] Create 2025.Maximum-Number-of-Ways-to-Partition-an-Array.cpp --- ...m-Number-of-Ways-to-Partition-an-Array.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array/2025.Maximum-Number-of-Ways-to-Partition-an-Array.cpp diff --git a/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array/2025.Maximum-Number-of-Ways-to-Partition-an-Array.cpp b/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array/2025.Maximum-Number-of-Ways-to-Partition-an-Array.cpp new file mode 100644 index 000000000..3e0f48b5e --- /dev/null +++ b/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array/2025.Maximum-Number-of-Ways-to-Partition-an-Array.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int waysToPartition(vector& nums, int k) + { + int n = nums.size(); + long sum = accumulate(nums.begin(), nums.end(), 0L); + vectorrets(n); + + vectorpre(n); + pre[0] = nums[0]; + for (int i=1; icount; + for (int i=0; isuf(n); + suf[n-1] = nums[n-1]; + for (int i=n-2; i>=0; i--) + suf[i] = suf[i+1]+nums[i]; + count.clear(); + for (int i=n-1; i>=0; i--) + { + int new_sum = sum + k-nums[i]; + if (new_sum % 2 == 0) + rets[i] += count[new_sum/2]; + count[suf[i]]++; + } + + long ret = 0; + for (int i=0; i Date: Sun, 3 Oct 2021 01:35:01 -0700 Subject: [PATCH 0026/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ba42177d1..8b7639b7e 100644 --- a/Readme.md +++ b/Readme.md @@ -150,6 +150,7 @@ [1542.Find-Longest-Awesome-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1542.Find-Longest-Awesome-Substring) (H-) [1915.Number-of-Wonderful-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1915.Number-of-Wonderful-Substrings) (M+) [1983.Widest-Pair-of-Indices-With-Equal-Range-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum) (M+) +[2025.Maximum-Number-of-Ways-to-Partition-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array) (H) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From d5f37b22f639fc29c4eae381b9a5947358a71ead Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Oct 2021 11:59:42 -0700 Subject: [PATCH 0027/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array/Readme.md diff --git a/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array/Readme.md b/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array/Readme.md new file mode 100644 index 000000000..4b6be5d01 --- /dev/null +++ b/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array/Readme.md @@ -0,0 +1,9 @@ +### 2025.Maximum-Number-of-Ways-to-Partition-an-Array + +在不做任何改动的情况下,我们的工作很简单,就是查看哪些presum等于sum/2,用Hash统计一下即可。 + +如果我们对nums[i]做了变动,那么就有```new_sum = sum + d```其中```d = k-nums[i]```. 此时我们想要看的是更新后的new_presum里有多少等于new_sum/2。但是如果把所有的new_presum都计算一遍,需要o(N)的操作,很不合算。此时我们发现,在i之前的那些presum其实是没有变化的,即```new_presum = presum```。也就是说,如果有合法的切分点位于i之前,那么我们只需要在之前的presum里查看一下即可。 + +那么很显然,下一步我们会想,如果有合法的切分点位于i之后,我们还是得查看new_presum对不对?此时我们转念一下,在这种情况下,切分点后面的sufsum数列其实没有改变。如果有sufsum等于new_sum/2,那么同样意味着整个数组可以等分为两半。 + +所以本题的算法很简单:预先计算presum和sufsum。遍历改动的位置nums[i],在i之前查看有多少presum等于new_sum/2,再在i之后查看有多少sufsum等于new_sum/2. 这两部分方案数之和就是这次改动能够成立的partition方法。 From 933bc82e829d0d5ccae89fda2d2c2fef6f8e4e74 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Oct 2021 13:44:10 -0700 Subject: [PATCH 0028/2729] Create 679.24-Game_v3.cpp --- Recursion/679.24-Game/679.24-Game_v3.cpp | 45 ++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Recursion/679.24-Game/679.24-Game_v3.cpp diff --git a/Recursion/679.24-Game/679.24-Game_v3.cpp b/Recursion/679.24-Game/679.24-Game_v3.cpp new file mode 100644 index 000000000..939d636d2 --- /dev/null +++ b/Recursion/679.24-Game/679.24-Game_v3.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + bool judgePoint24(vector& nums) + { + vectorNums(4); + for (int i=0; i<4; i++) Nums[i] = nums[i]; + sort(Nums.begin(), Nums.end()); + + while (1) + { + unordered_set results = DFS(Nums,0,3); + for (auto a:results) + { + if (abs(a-24)<1e-10) + return true; + } + if (next_permutation(Nums.begin(), Nums.end()) == false) + break; + } + return false; + } + + unordered_set DFS(vector &nums, int a, int b) + { + if (a==b) return {nums[a]}; + + unordered_setresults; + + for (int i=a; iA = DFS(nums,a,i); + unordered_setB = DFS(nums,i+1,b); + for (double x:A) + for (double y:B) + { + results.insert(x+y); + results.insert(x-y); + results.insert(x*y); + if (y!=0) + results.insert(x/y); + } + } + return results; + } +}; From 8051ce64d0d19e120b4af60235b33f2bc2f5267d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Oct 2021 13:46:12 -0700 Subject: [PATCH 0029/2729] Update 679.24-Game_v3.cpp --- Recursion/679.24-Game/679.24-Game_v3.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Recursion/679.24-Game/679.24-Game_v3.cpp b/Recursion/679.24-Game/679.24-Game_v3.cpp index 939d636d2..348ce59da 100644 --- a/Recursion/679.24-Game/679.24-Game_v3.cpp +++ b/Recursion/679.24-Game/679.24-Game_v3.cpp @@ -1,20 +1,20 @@ class Solution { public: - bool judgePoint24(vector& nums) + bool judgePoint24(vector& cards) { - vectorNums(4); - for (int i=0; i<4; i++) Nums[i] = nums[i]; - sort(Nums.begin(), Nums.end()); + vectornums(4); + for (int i=0; i<4; i++) nums[i] = cards[i]; + sort(nums.begin(), nums.end()); while (1) { - unordered_set results = DFS(Nums,0,3); + unordered_set results = DFS(nums,0,3); for (auto a:results) { if (abs(a-24)<1e-10) return true; } - if (next_permutation(Nums.begin(), Nums.end()) == false) + if (next_permutation(nums.begin(), nums.end()) == false) break; } return false; From 9986e5386848f3b67bd5168157359d8eb1d5a8dc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Oct 2021 14:28:49 -0700 Subject: [PATCH 0030/2729] Update Readme.md --- Recursion/679.24-Game/Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Recursion/679.24-Game/Readme.md b/Recursion/679.24-Game/Readme.md index c7d60a823..09a12c6d3 100644 --- a/Recursion/679.24-Game/Readme.md +++ b/Recursion/679.24-Game/Readme.md @@ -1,10 +1,12 @@ ### 679.24-Game -回想一下平时24点是怎么玩的。不管最终的策略是什么,都是要先选两张牌做运算,算出一个数值,然后和剩下的两张牌一起考虑。于是接下来就等于三张牌算24点。OK,递归的思路就这么出来了。所以,那些乘除法、括号的优先结合法则,都是障眼法,其实都不需要考虑。 +此题和```LC 241 Different Ways to Add Parentheses```与```LC 2019 The Score of Students Solving Math Expression```类似的套路。 -总结一下:手头有N张牌的时候(K<=4),要随机选出两张(有序),剩下的就不用管顺序了。这样的排列组成了一个排列的集合```vector>permuations```。对于其中的每一种排列,我们对于那两张有序的牌分别做加减乘除的运算,将得到的结果再放回剩下的N-2张牌里面,相当于变成N-1张牌.于是我们发现这是一个递归任务,我们下一步就是在N-1牌里算24点,同样需要先随机挑两张,重复上面的步骤。手头的牌只有一张了,那查看它是否为24即可。 +我们遍历这个四个数字的permutaion。对于任意一种permuation ```A B C D```,我们本质上需要做的就是任意添加运算符(加减乘除)和括号(改变运算顺序),查看整个式子eval的结果是否包含24. + +具体的做法就是递归。我们将某个permutation拆解为两部分分别递归处理,再将每个部分eval出来的结果两两组合,配上加减乘除,就得到对于这个permutation我们所能计算出的所有可能值。 需要注意,所有的牌必须处理成浮点,因为涉及到除法。 -[Leetcode Link](https://leetcode.com/problems/24-game) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/24-game) From 3fd24ad560869fe9937efa890f1d1b8b8189e10f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Oct 2021 14:30:42 -0700 Subject: [PATCH 0031/2729] Update Readme.md --- Recursion/679.24-Game/Readme.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Recursion/679.24-Game/Readme.md b/Recursion/679.24-Game/Readme.md index 09a12c6d3..c610af63e 100644 --- a/Recursion/679.24-Game/Readme.md +++ b/Recursion/679.24-Game/Readme.md @@ -4,7 +4,12 @@ 我们遍历这个四个数字的permutaion。对于任意一种permuation ```A B C D```,我们本质上需要做的就是任意添加运算符(加减乘除)和括号(改变运算顺序),查看整个式子eval的结果是否包含24. -具体的做法就是递归。我们将某个permutation拆解为两部分分别递归处理,再将每个部分eval出来的结果两两组合,配上加减乘除,就得到对于这个permutation我们所能计算出的所有可能值。 +具体的做法就是递归。我们将某个permutation拆解为两部分分别递归处理,再将两个部分eval出来的结果两两组合,配上加减乘除,就得到对于这个permutation我们所能计算出的所有可能值。大致的代码是 +``` +for x: eval(AB) + for y: eval(CD) + rets.insert({x+y, x-y, x*y, x/y}); +``` 需要注意,所有的牌必须处理成浮点,因为涉及到除法。 From 05e69a455d0a25184306374c16e762844273f14f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Oct 2021 15:52:45 -0700 Subject: [PATCH 0032/2729] Create 2029.Stone-Game-IX.cpp --- .../2029.Stone-Game-IX/2029.Stone-Game-IX.cpp | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Others/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp diff --git a/Others/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp b/Others/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp new file mode 100644 index 000000000..c73ae2849 --- /dev/null +++ b/Others/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp @@ -0,0 +1,65 @@ +class Solution { +public: + bool stoneGameIX(vector& stones) + { + vectorcount(3); + for (int x: stones) + count[x%3]+=1; + + auto temp = count; + if (temp[1]>0) + { + temp[1]-=1; + if (!win(temp, 1, 1)) + return true; + } + + temp = count; + if (temp[2]>0) + { + temp[2]-=1; + if (!win(temp, 2, 1)) + return true; + } + + return false; + } + + bool win(vector&count, int sum, int turn) + { + if (count[0]+count[1]+count[2]==0) + { + if (turn == 1) + return true; + else + return false; + } + + if (count[0]>0) + { + count[0]-=1; + return 1-win(count, sum, 1-turn); + } + + if (sum%3==1) + { + if (count[1]>0) + { + count[1]--; + return 1-win(count, sum+1, 1-turn); + } + else + return false; + } + else + { + if (count[2]>0) + { + count[2]--; + return 1 - win(count, sum+2, 1-turn); + } + else + return false; + } + } +}; From 448c24f9e3b84648dbfe2066342b61159fbe7bf4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Oct 2021 15:53:12 -0700 Subject: [PATCH 0033/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8b7639b7e..e65062058 100644 --- a/Readme.md +++ b/Readme.md @@ -1088,6 +1088,7 @@ [1904.The-Number-of-Full-Rounds-You-Have-Played](https://github.com/wisdompeak/LeetCode/tree/master/Others/1904.The-Number-of-Full-Rounds-You-Have-Played) (M) [1997.First-Day-Where-You-Have-Been-in-All-the-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/1997.First-Day-Where-You-Have-Been-in-All-the-Rooms) (H) [2018.Check-if-Word-Can-Be-Placed-In-Crossword](https://github.com/wisdompeak/LeetCode/tree/master/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword) (M+) +[2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 718ed494b961c51eb5721bdf7d02b97b4d06a1c4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 20:06:37 -0700 Subject: [PATCH 0034/2729] Create Readme.md --- Others/2029.Stone-Game-IX/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/2029.Stone-Game-IX/Readme.md diff --git a/Others/2029.Stone-Game-IX/Readme.md b/Others/2029.Stone-Game-IX/Readme.md new file mode 100644 index 000000000..c5747774f --- /dev/null +++ b/Others/2029.Stone-Game-IX/Readme.md @@ -0,0 +1,13 @@ +### 2029.Stone-Game-IX + +本题其实是决策推理。我们要分析出以下几种对策。 + +1. 如果存在被3整除的元素,一定选它。对于当前需要做决策的选手而言,显然目前的sum不会被3整除(否则上一轮对手决策完就输了)。此时如果剩下有被3整除的元素X,那么选它总不会错。如果你选了,你就可以安全地把问题转移给对手。如果你不选,侥幸你能通过其他方法把问题转移给对手,对手依然可以通过选X从而把问题安全地转移给你。所以优先选择X,既可以保证自己该轮安全,也可以让对手少一个自保安全的机会,何乐而不为? + +2. 如果当前的sum被3除余1,在排除了方案1的可能性后,当前选手只能在剩下的元素里也找一个被3除余1的;否则选被3除余2的元素的话,一定会导致sum被3整除,从而失败。显然,如果剩下的元素里没有被3除1的,那么必败。 + +3. 同上,如果当前的sum被3除余2,在排除了方案1的可能性后,当前选手只能在剩下的元素里也找一个被3除余2的;否则选被3除余1的元素的话,一定会导致sum被3整除,从而失败。显然,如果剩下的元素里没有被3除2的,那么必败。 + +4. 此外还有一条规则。如果当前做决策的选手没有剩余元素可选,无论该轮是谁,都宣告Alice获胜。 + +综上所述,Alice作为先手,它的第一步只可能是选一个被3除余1,或者被3除余2的元素。一旦第一步确定后,接下来双方的所有决策,其实都是确定性的,不存在分叉。所以我们可以一步步地推断出最终的赢家会是谁。 From 41dbf89554e1f6a6963f2038bef5452824a84d05 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 20:08:37 -0700 Subject: [PATCH 0035/2729] Update Readme.md --- Others/2029.Stone-Game-IX/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2029.Stone-Game-IX/Readme.md b/Others/2029.Stone-Game-IX/Readme.md index c5747774f..0ea92ab75 100644 --- a/Others/2029.Stone-Game-IX/Readme.md +++ b/Others/2029.Stone-Game-IX/Readme.md @@ -10,4 +10,4 @@ 4. 此外还有一条规则。如果当前做决策的选手没有剩余元素可选,无论该轮是谁,都宣告Alice获胜。 -综上所述,Alice作为先手,它的第一步只可能是选一个被3除余1,或者被3除余2的元素。一旦第一步确定后,接下来双方的所有决策,其实都是确定性的,不存在分叉。所以我们可以一步步地推断出最终的赢家会是谁。 +综上所述,Alice作为先手,它的第一步只可能是选一个被3除余1,或者被3除余2的元素。一旦第一步确定后,接下来双方的所有决策,其实都是确定性的,不存在分叉。即选完被3整除的元素之后,只能一直取余数固定的一类元素,直至该元素取完:此时如果还有其他元素,则判当前选手失败;否则判Alice赢。 From 097fdbcb3394131fbd1741067dfe64150b41561c Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Mon, 4 Oct 2021 21:43:54 -0700 Subject: [PATCH 0036/2729] mv 2029 --- {Others => Recursion}/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp | 0 {Others => Recursion}/2029.Stone-Game-IX/Readme.md | 0 Template/{IO => CPP_LANG}/istringstream.cpp | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {Others => Recursion}/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp (100%) rename {Others => Recursion}/2029.Stone-Game-IX/Readme.md (100%) rename Template/{IO => CPP_LANG}/istringstream.cpp (100%) diff --git a/Others/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp b/Recursion/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp similarity index 100% rename from Others/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp rename to Recursion/2029.Stone-Game-IX/2029.Stone-Game-IX.cpp diff --git a/Others/2029.Stone-Game-IX/Readme.md b/Recursion/2029.Stone-Game-IX/Readme.md similarity index 100% rename from Others/2029.Stone-Game-IX/Readme.md rename to Recursion/2029.Stone-Game-IX/Readme.md diff --git a/Template/IO/istringstream.cpp b/Template/CPP_LANG/istringstream.cpp similarity index 100% rename from Template/IO/istringstream.cpp rename to Template/CPP_LANG/istringstream.cpp From 766d210b96a509d8a9f427b8e5775c9b01d2f92a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 21:44:40 -0700 Subject: [PATCH 0037/2729] Update Readme.md --- Readme.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e65062058..a9c0aa69c 100644 --- a/Readme.md +++ b/Readme.md @@ -841,6 +841,7 @@ [1406.Stone-Game-III](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1406.Stone-Game-III) (M+) [1510.Stone-Game-IV](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1510.Stone-Game-IV) (M) [1563.Stone-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1563.Stone-Game-V) (H-) +[2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) @@ -1088,7 +1089,6 @@ [1904.The-Number-of-Full-Rounds-You-Have-Played](https://github.com/wisdompeak/LeetCode/tree/master/Others/1904.The-Number-of-Full-Rounds-You-Have-Played) (M) [1997.First-Day-Where-You-Have-Been-in-All-the-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/1997.First-Day-Where-You-Have-Been-in-All-the-Rooms) (H) [2018.Check-if-Word-Can-Be-Placed-In-Crossword](https://github.com/wisdompeak/LeetCode/tree/master/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword) (M+) -[2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) @@ -1142,5 +1142,4 @@ [Bit_Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Template/Bit_manipulation) [Combination-Number](https://github.com/wisdompeak/LeetCode/tree/master/Template/Combination-Number) [RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) -[IO](https://github.com/wisdompeak/LeetCode/tree/master/Template/IO) [CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) From 84c8fa3d520f8165160f4bfe6371b67c00047233 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 21:46:16 -0700 Subject: [PATCH 0038/2729] Create 2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp --- ...bsequence-With-Occurrences-of-a-Letter.cpp | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp diff --git a/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp b/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp new file mode 100644 index 000000000..83f52d73a --- /dev/null +++ b/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp @@ -0,0 +1,78 @@ +class Solution { +public: + string smallestSubsequence(string s, int k, char letter, int repetition) + { + int count = 0; + for (auto ch:s) + { + if (ch==letter) + count++; + } + + int k1 = count - repetition; + int k0 = s.size() - k; + + stackStack; + int count0 = 0; + int count1 = 0; + + for (int i=0; i=Stack.top()) + { + Stack.push(s[i]); + } + else if (s[i]=0; i--) + { + if (count0 == k0) + ans.push_back(result[i]); + else + { + if (result[i]==letter) + { + if (count1 == k1) + ans.push_back(result[i]); + else + { + count0++; + count1++; + } + } + else + { + count0++; + } + } + } + + reverse(ans.begin(), ans.end()); + + return ans; + + } +}; From ae78396a746503aa06846a37fe01e3b58cc49849 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 21:48:01 -0700 Subject: [PATCH 0039/2729] Update Readme.md --- Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index a9c0aa69c..342ac3b8b 100644 --- a/Readme.md +++ b/Readme.md @@ -298,8 +298,6 @@ [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [255.Verify-Preorder-Sequence-in-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/255.Verify-Preorder-Sequence-in-Binary-Search-Tree) (H) -[402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) -[316.Remove-Duplicate-Letters](https://github.com/wisdompeak/LeetCode/tree/master/Stack/316.Remove-Duplicate-Letters) (H) [496.Next-Greater-Element-I](https://github.com/wisdompeak/LeetCode/tree/master/Stack/496.Next-Greater-Element-I) (H-) [503.Next-Greater-Element-II](https://github.com/wisdompeak/LeetCode/blob/master/Stack/503.Next-Greater-Element-II) (H-) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) @@ -313,10 +311,14 @@ [1063.Number-of-Valid-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1063.Number-of-Valid-Subarrays) (M+) [1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) -[1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [1950.Maximum-of-Minimum-Values-in-All=Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) +* ``form smallest sequence`` +[402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) +[1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) +[2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter) (H) +[316.Remove-Duplicate-Letters](https://github.com/wisdompeak/LeetCode/tree/master/Stack/316.Remove-Duplicate-Letters) (H) * ``parse expression`` [071.Simplify-Path](https://github.com/wisdompeak/LeetCode/tree/master/Stack/071.Simplify-Path) (M) [224.Basic-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Stack/224.Basic-Calculator)(H-) From 9338ba1c728a3cae93cac01ab3a87a03a8909349 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 21:59:09 -0700 Subject: [PATCH 0040/2729] Update 2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp --- ...bsequence-With-Occurrences-of-a-Letter.cpp | 25 +++++-------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp b/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp index 83f52d73a..4da01ad6e 100644 --- a/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp +++ b/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp @@ -24,7 +24,7 @@ class Solution { } else if (s[i]=0; i--) + for (int i=0; i Date: Mon, 4 Oct 2021 22:00:47 -0700 Subject: [PATCH 0041/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/Readme.md diff --git a/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/Readme.md b/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/Readme.md new file mode 100644 index 000000000..55e3274da --- /dev/null +++ b/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/Readme.md @@ -0,0 +1,5 @@ +### 2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter + +本题本质和```402.Remove-K-Digits```差不多。只不过多在单调栈的维护递增序列的过程中需要注意两个条件:1. 删除的字符总数不能超过k0,即```s.size()-k```;并且删除的letter数目不能超过k1,即letter出现的总频次减去repetition. + +我们用单调栈构建了一个递增序列之后,可能它的长度太长,即删减的字符不够多。此时我们必须继续从尾部开始删字符。删除尾部的操作同样延续之前的两个条件:1. 删除的字符总数不能超过k0;2. 删除的letter数目不能超过k1。如果不能删除,就保留该字符,处理下一个。 From 8bb7c804510ba16de12e1ee4cc532c04c09ffd5e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 23:13:20 -0700 Subject: [PATCH 0042/2729] Create 1081.Smallest-Subsequence-of-Distinct-Characters.cpp --- ...est-Subsequence-of-Distinct-Characters.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Stack/1081.Smallest-Subsequence-of-Distinct-Characters/1081.Smallest-Subsequence-of-Distinct-Characters.cpp diff --git a/Stack/1081.Smallest-Subsequence-of-Distinct-Characters/1081.Smallest-Subsequence-of-Distinct-Characters.cpp b/Stack/1081.Smallest-Subsequence-of-Distinct-Characters/1081.Smallest-Subsequence-of-Distinct-Characters.cpp new file mode 100644 index 000000000..4000851ea --- /dev/null +++ b/Stack/1081.Smallest-Subsequence-of-Distinct-Characters/1081.Smallest-Subsequence-of-Distinct-Characters.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + string smallestSubsequence(string text) + { + string str; + vectorcount(26); + for (auto ch: text) + count[ch-'a']++; + unordered_setvisited; + + for (auto ch: text) + { + if (visited.find(ch)!=visited.end()) + { + count[ch-'a']--; + } + else + { + while (str.size()>0 && str.back()>ch && count[str.back()-'a']>0) + { + visited.erase(str.back()); + str.pop_back(); + } + str.push_back(ch); + count[ch-'a']--; + visited.insert(ch); + } + } + + return str; + } +}; From abc9995962525c610a8756e95e4d45555790530e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 23:13:59 -0700 Subject: [PATCH 0043/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 342ac3b8b..938cce86e 100644 --- a/Readme.md +++ b/Readme.md @@ -319,6 +319,7 @@ [1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) [2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter) (H) [316.Remove-Duplicate-Letters](https://github.com/wisdompeak/LeetCode/tree/master/Stack/316.Remove-Duplicate-Letters) (H) +[1081.Smallest-Subsequence-of-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1081.Smallest-Subsequence-of-Distinct-Characters) (M+) * ``parse expression`` [071.Simplify-Path](https://github.com/wisdompeak/LeetCode/tree/master/Stack/071.Simplify-Path) (M) [224.Basic-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Stack/224.Basic-Calculator)(H-) From 423e668d77ac94b867afead112222640b754fa45 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Oct 2021 23:15:18 -0700 Subject: [PATCH 0044/2729] Create Readme.md --- .../1081.Smallest-Subsequence-of-Distinct-Characters/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Stack/1081.Smallest-Subsequence-of-Distinct-Characters/Readme.md diff --git a/Stack/1081.Smallest-Subsequence-of-Distinct-Characters/Readme.md b/Stack/1081.Smallest-Subsequence-of-Distinct-Characters/Readme.md new file mode 100644 index 000000000..4e15c5ac2 --- /dev/null +++ b/Stack/1081.Smallest-Subsequence-of-Distinct-Characters/Readme.md @@ -0,0 +1,3 @@ +### 1081.Smallest-Subsequence-of-Distinct-Characters + +这道题和```316.Remove-Duplicate-Letters```一模一样。 From 871192afa18373f1db9f08d5d2408407e7824092 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Oct 2021 22:17:49 -0700 Subject: [PATCH 0045/2729] Update 2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp --- ...bsequence-With-Occurrences-of-a-Letter.cpp | 53 +++++++------------ 1 file changed, 19 insertions(+), 34 deletions(-) diff --git a/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp b/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp index 4da01ad6e..3c195b0f2 100644 --- a/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp +++ b/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter.cpp @@ -1,65 +1,50 @@ class Solution { public: string smallestSubsequence(string s, int k, char letter, int repetition) - { + { + int k0 = s.size() - k; int count = 0; - for (auto ch:s) - { - if (ch==letter) - count++; - } - + for (auto ch: s) + if (ch==letter) count++; int k1 = count - repetition; - int k0 = s.size() - k; - stackStack; - int count0 = 0; - int count1 = 0; - + int count0 = 0; //the total number of letters deleted + int count1 = 0; // the total number of "letter" deleted + + stackStack; for (int i=0; i=Stack.top()) + { + while (!Stack.empty() && s[i] Date: Wed, 6 Oct 2021 22:32:44 -0700 Subject: [PATCH 0046/2729] Update 843.Guess-the-Word.cpp --- Others/843.Guess-the-Word/843.Guess-the-Word.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Others/843.Guess-the-Word/843.Guess-the-Word.cpp b/Others/843.Guess-the-Word/843.Guess-the-Word.cpp index c111fe99e..0f4dc04da 100644 --- a/Others/843.Guess-the-Word/843.Guess-the-Word.cpp +++ b/Others/843.Guess-the-Word/843.Guess-the-Word.cpp @@ -4,6 +4,7 @@ class Solution { { for (int i=0; i<10; i++) { + srand(1); int r = rand() % wordlist.size(); string x = wordlist[r]; int count = master.guess(x); From 47b9d866766412b211bbd426a79534d925482d51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Oct 2021 23:30:40 -0700 Subject: [PATCH 0047/2729] Create 1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp --- ...er-of-People-That-Can-Be-Caught-in-Tag.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp diff --git a/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp b/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp new file mode 100644 index 000000000..6d642f46b --- /dev/null +++ b/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int catchMaximumAmountofPeople(vector& team, int dist) + { + int n = team.size(); + int j = 0; + int ret = 0; + for (int i=0; i Date: Fri, 8 Oct 2021 23:31:06 -0700 Subject: [PATCH 0048/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 938cce86e..9e66dc552 100644 --- a/Readme.md +++ b/Readme.md @@ -30,6 +30,7 @@ [1687.Delivering-Boxes-from-Storage-to-Ports](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1687.Delivering-Boxes-from-Storage-to-Ports) (H) [1793.Maximum-Score-of-a-Good-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1793.Maximum-Score-of-a-Good-Subarray) (M+) [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make/Readme.md](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) +[1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag) (M+) * ``Sliding window`` [532.K-diff-Pairs-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/532.K-diff-Pairs-in-an-Array) (H-) [611.Valid-Triangle-Number](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/611.Valid-Triangle-Number) (M+) From 65da1f8e267ff1e6a5d521c5f411b2389ddb4b65 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Oct 2021 23:49:05 -0700 Subject: [PATCH 0049/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/Readme.md diff --git a/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/Readme.md b/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/Readme.md new file mode 100644 index 000000000..a78c711a8 --- /dev/null +++ b/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/Readme.md @@ -0,0 +1,5 @@ +### 1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag + +贪心的思想。我们用一个指针i从小到大依次遍历每一个0。对于第一个0而言,我们只要找离它最近(即最靠左边)的、满足距离条件的那个1与之配对即可。这一定是最优策略。因为这个0如果与其他更远的1配对的话,距离条件可能更难满足,并且也可能会浪费掉这个最近的1. 同理,对于每个0而言,必然贪心地与最左边的1配对最合算。 + +本题有趣的地方是,指向1的指针j虽然是单向右移的,但不一定永远在i的右边,也有可能在i的左边。所以每当考察一个新的i时,j指针需要调整到```max(j, i-dist)```处开始寻找1.因为此时比该点更左边的1不会给匹配带来任何帮助了。 From 701ac3b6ced37fa69110256c5cdb17a48a138bd5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Oct 2021 23:49:12 -0700 Subject: [PATCH 0050/2729] Update 1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp --- .../1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp b/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp index 6d642f46b..aef1f194a 100644 --- a/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp +++ b/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag.cpp @@ -14,7 +14,7 @@ class Solution { if (j Date: Sun, 10 Oct 2021 13:48:33 -0700 Subject: [PATCH 0051/2729] Create 2033.Minimum-Operations-to-Make-a-Uni-Value-Grid.cpp --- ...um-Operations-to-Make-a-Uni-Value-Grid.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid.cpp diff --git a/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid.cpp b/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid.cpp new file mode 100644 index 000000000..90b2c7fc6 --- /dev/null +++ b/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int minOperations(vector>& grid, int x) + { + int m = grid.size(); + int n = grid[0].size(); + int mn = INT_MAX; + for (int i=0; inums; + for (int i=0; i Date: Sun, 10 Oct 2021 13:49:11 -0700 Subject: [PATCH 0052/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9e66dc552..f42aa1b70 100644 --- a/Readme.md +++ b/Readme.md @@ -892,6 +892,7 @@ [1969.Minimum-Non-Zero-Product-of-the-Array-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/1969.Minimum-Non-Zero-Product-of-the-Array-Elements) (M+) * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) +[2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) From 28a068a7ec169fa2be3115e7658258cf55810699 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Oct 2021 13:51:20 -0700 Subject: [PATCH 0053/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index f42aa1b70..0ebd74d17 100644 --- a/Readme.md +++ b/Readme.md @@ -893,9 +893,10 @@ * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) +[1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) +[1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) -[1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) From 98b2c8ef4206e6715a1bcd7ea5d291457a6877ed Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Oct 2021 14:08:35 -0700 Subject: [PATCH 0054/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md diff --git a/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md b/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md new file mode 100644 index 000000000..5db4fd411 --- /dev/null +++ b/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md @@ -0,0 +1,5 @@ +### 2033.Minimum-Operations-to-Make-a-Uni-Value-Grid + +首先,满足最终结果的前提条件是,所有矩阵元素与最小值之间的差值必须都是x的倍数。 + +其次,满足了上面的条件之后,那么这个uni-value是什么呢?我们希望所有元素变换成uni-value的操作总数最小,也就是希望这个uni-value能和大家都“接近”。将这个操作总数乘以x后不难发现,也就是希望这个uni-value到所有元素的距离之和最小。显然,和```296.Best-Meeting-Point```一样的数学结论,这个数一定是所有元素的中位数(median)。 From 861b497cfc80e603e419ac687525aa2ca4822f7a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Oct 2021 14:09:33 -0700 Subject: [PATCH 0055/2729] Update Readme.md --- Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md b/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md index 5db4fd411..c139f4492 100644 --- a/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md +++ b/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid/Readme.md @@ -3,3 +3,5 @@ 首先,满足最终结果的前提条件是,所有矩阵元素与最小值之间的差值必须都是x的倍数。 其次,满足了上面的条件之后,那么这个uni-value是什么呢?我们希望所有元素变换成uni-value的操作总数最小,也就是希望这个uni-value能和大家都“接近”。将这个操作总数乘以x后不难发现,也就是希望这个uni-value到所有元素的距离之和最小。显然,和```296.Best-Meeting-Point```一样的数学结论,这个数一定是所有元素的中位数(median)。 + +此题的进阶版有:```1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones```, ```1478.Allocate-Mailboxes``` From 61ed7e7ac4d386479470e77d4ed1df3bc40dd786 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Oct 2021 14:20:48 -0700 Subject: [PATCH 0056/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0ebd74d17..09291ab3d 100644 --- a/Readme.md +++ b/Readme.md @@ -313,7 +313,7 @@ [1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) -[1950.Maximum-of-Minimum-Values-in-All=Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) +[1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) From 75707dc95bb19312fe70d48d52d097e15fb95b50 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Oct 2021 15:16:13 -0700 Subject: [PATCH 0057/2729] Create 2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp --- ...-Two-Arrays-to-Minimize-Sum-Difference.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp diff --git a/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp b/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp new file mode 100644 index 000000000..fa747d2d3 --- /dev/null +++ b/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp @@ -0,0 +1,58 @@ +using LL = long long; +class Solution { +public: + unordered_map> helper(vector&nums) + { + unordered_map>Map; + int n = nums.size(); + for (int state=0; state<(1<>i)&1) + sum += (LL)nums[i]; + } + Map[k].push_back(sum); + } + for (auto& x: Map) + sort(x.second.begin(), x.second.end()); + return Map; + } + + + int minimumDifference(vector& nums) + { + int n = nums.size()/2; + vectornums1; + vectornums2; + for (int i=0; i>Map1 = helper(nums1); + unordered_map>Map2 = helper(nums2); + + LL sum = accumulate(nums.begin(), nums.end(), 0LL); + LL ret = LLONG_MAX; + + for (int i=0; i<=n; i++) + { + int j = n-i; + for (LL x: Map1[i]) + { + auto iter = lower_bound(Map2[j].begin(), Map2[j].end(), sum/2-x); + if (iter!=Map2[j].end()) + ret = min(ret, abs(*iter*2+2*x-sum)); + if (iter!=Map2[j].begin()) + { + iter = prev(iter); + ret = min(ret, abs(*iter*2+2*x-sum)); + } + } + } + return ret; + } +}; From 35c3150b7f621571474ea98e72d2815888485c7e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Oct 2021 15:16:53 -0700 Subject: [PATCH 0058/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 09291ab3d..fd1a53147 100644 --- a/Readme.md +++ b/Readme.md @@ -722,6 +722,7 @@ [1452.People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1452.People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List) (H-) [1601.Maximum-Number-of-Achievable-Transfer-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1601.Maximum-Number-of-Achievable-Transfer-Requests) (H-) [1755.Closest-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1755.Closest-Subsequence-Sum) (H) +[2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) [1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) From 075c4e60d8af629943b6b41f4348d41d85976430 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Oct 2021 16:17:36 -0700 Subject: [PATCH 0059/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/Readme.md diff --git a/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/Readme.md b/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/Readme.md new file mode 100644 index 000000000..19ba80b68 --- /dev/null +++ b/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/Readme.md @@ -0,0 +1,11 @@ +### 2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference + +本题的思路来自于```1755.Closest-Subsequence-Sum``` + +本题要将最多30个数平均分成两组。这个规模暗示我们其实并没有贪心或者高效的算法,本题是指数级别的暴力搜索NPC问题。但是从30个里面遍历15个数的组合,是一个非常大的数字,这是无法暴力完成。怎么办呢? + +我们发现如果只考虑一半的规模即n=15时,2^15=32768是一个可以接受的规模。这就提醒我们类似的1755,将数组分成两部分来处理。对于前半部分数组,我们可以遍历所有的组合(每个组合代表选取哪些元素),将每个组合的sum记录下来。假设前半部分的某个组合有i个元素,该组合的元素之和是x,那么我们自然希望在后半部分数组里挑选n-j个元素(记该组合的元素之和是y)使得x+y尽量接近sum-(x+y)。稍微变化一下,就知道我们需要找这样一个y,使得y尽量接近```sum/2-x```. + +所以看出来,我们需要对后半部分数组进行预处理,构造一个Hash表,令Map[j]表示在后半部分数组里取j个元素的组合时,元素之和可能是哪些。对于前述的任何一个i和x,我们对应直接在Map[j]里面找最接近```sum/2-x```的数值(记做y)。那么```|x+y-(sum-x-y)|```就是一个可能的最优解。 + +所以总的时间复杂度是:1. 预处理部分,需要```O(2^n*n)```,其中乘以n表示遍历该state的每一个bit来计算sum。2. 遍历左边部分的所有组合(对应的i和x),然后在右边的Map[n-j]里面用二分来挑选最接近的数值,故是```o(2^n*log(2^n)) = o(2^n*n)``` From fb4b9b92eeb9d85f6272b5a32377b7ce1929c517 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Oct 2021 16:26:00 -0700 Subject: [PATCH 0060/2729] Update 2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp --- ...-Two-Arrays-to-Minimize-Sum-Difference.cpp | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp b/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp index fa747d2d3..c727cecd8 100644 --- a/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp +++ b/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference.cpp @@ -32,27 +32,31 @@ class Solution { for (int i=n; i<2*n; i++) nums2.push_back(nums[i]); - unordered_map>Map1 = helper(nums1); unordered_map>Map2 = helper(nums2); LL sum = accumulate(nums.begin(), nums.end(), 0LL); LL ret = LLONG_MAX; - - for (int i=0; i<=n; i++) + + for (int state=0; state<(1<>k)&1) + x += (LL)nums1[k]; + } + int j = n - i; + auto iter = lower_bound(Map2[j].begin(), Map2[j].end(), sum/2-x); + if (iter!=Map2[j].end()) + ret = min(ret, abs(*iter*2+2*x-sum)); + if (iter!=Map2[j].begin()) { - auto iter = lower_bound(Map2[j].begin(), Map2[j].end(), sum/2-x); - if (iter!=Map2[j].end()) - ret = min(ret, abs(*iter*2+2*x-sum)); - if (iter!=Map2[j].begin()) - { - iter = prev(iter); - ret = min(ret, abs(*iter*2+2*x-sum)); - } + iter = prev(iter); + ret = min(ret, abs(*iter*2+2*x-sum)); } + } - return ret; + return ret; } }; From ad7ffd2960513a3fbe8ede3d9a2582e8fd48288e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 15 Oct 2021 23:04:25 -0700 Subject: [PATCH 0061/2729] Create 1004.Max-Consecutive-Ones-III_v2.cpp --- .../1004.Max-Consecutive-Ones-III_v2.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Two_Pointers/1004.Max-Consecutive-Ones-III/1004.Max-Consecutive-Ones-III_v2.cpp diff --git a/Two_Pointers/1004.Max-Consecutive-Ones-III/1004.Max-Consecutive-Ones-III_v2.cpp b/Two_Pointers/1004.Max-Consecutive-Ones-III/1004.Max-Consecutive-Ones-III_v2.cpp new file mode 100644 index 000000000..84c7e39e8 --- /dev/null +++ b/Two_Pointers/1004.Max-Consecutive-Ones-III/1004.Max-Consecutive-Ones-III_v2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int longestOnes(vector& A, int K) + { + int n = A.size(); + int j = 0; + int ret = 0; + int count = 0; + for (int i=0; i Date: Sat, 16 Oct 2021 15:13:39 -0400 Subject: [PATCH 0062/2729] Update Readme.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 应是把无向图变成有向图 --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph/Readme.md b/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph/Readme.md index ce69927fd..b78ebf66a 100644 --- a/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph/Readme.md +++ b/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph/Readme.md @@ -11,4 +11,4 @@ for A in range(1,n): ret += inDegree[A] + inDegree[B] + inDegree[C] - 6 ``` -以上的方法会TLE。如何改进呢?我们发现,根据A找(B,C),等价于根据B找(A,C),根据C找(A,B)。所以整体的时间复杂度浪费了三倍。如何避免这个问题呢?解决方法是:把有向图变成无向图。也就是说,从A能找到(B,C),但是让B不会找到(A,C),因此我们可以令AB为单向边,即只允许A->B. 同理如果也令A->C为单向边的话,那么C就不会找到(A,B)。由这个技巧,我们可以将整体o(N^3)的复杂度降低至1/3。 +以上的方法会TLE。如何改进呢?我们发现,根据A找(B,C),等价于根据B找(A,C),根据C找(A,B)。所以整体的时间复杂度浪费了三倍。如何避免这个问题呢?解决方法是:把无向图变成有向图。也就是说,从A能找到(B,C),但是让B不会找到(A,C),因此我们可以令AB为单向边,即只允许A->B. 同理如果也令A->C为单向边的话,那么C就不会找到(A,B)。由这个技巧,我们可以将整体o(N^3)的复杂度降低至1/3。 From 0a899e627c519038cceeae4fc95dc70b0215ebec Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 15:13:55 -0700 Subject: [PATCH 0063/2729] Update Readme.md --- Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md b/Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md index e859721f0..e564722ec 100644 --- a/Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md +++ b/Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md @@ -1,7 +1,9 @@ ### 1918.Kth-Smallest-Subarray-Sum -此题的二维版本就是```1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows```. +此题本质等同于```719. Find K-th Smallest Pair Distance```. 我们用二分搜索猜测这个target。设计检验函数checkOK来判断if # of subarrays whose sum <= target is at least k. 如果是的话,那么这个target可以再小一些(但可能就是第k小的sum);如果不是的话,说明target一定偏小,需要往大里猜。本题一定有解,所以收链解就是最终解。 在写checkOK(nums, target, k)的时候,用的是快慢指针。从左往右遍历慢指针i,然后调整快指针j使得sum[i:j]恰好大于target,于是j-i就是以i为左端点的合法subarray的数目(即subarray sum <= target)。然后我们将i移动一位,j继续单调地向右移动,同样直至恰好```sum[i:j]>target```,同样将j-i加入count里。一旦count的数目大于等于k了,就可以停止双指针的搜索了。 + +此题有一个更难的二维版本```1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows```. From 42e8a2dec9702275fbc638c70c46dba24c7e16e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 15:15:48 -0700 Subject: [PATCH 0064/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index fd1a53147..c9a9bbdd7 100644 --- a/Readme.md +++ b/Readme.md @@ -90,6 +90,8 @@ [373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums) (H) [668.Kth-Smallest-Number-in-Multiplication-Table](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table) (H-) [719.Find-K-th-Smallest-Pair-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/719.Find-K-th-Smallest-Pair-Distance) (H-) +[1918.Kth-Smallest-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1918.Kth-Smallest-Subarray-Sum) (M+) +[1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows) (H) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [786.K-th-Smallest-Prime-Fraction](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/786.K-th%20Smallest-Prime-Fraction) (H-) [793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) @@ -102,7 +104,6 @@ [1283.Find-the-Smallest-Divisor-Given-a-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1283.Find-the-Smallest-Divisor-Given-a-Threshold) (M) [1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold) (H-) [1300.Sum-of-Mutated-Array-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1300.Sum-of-Mutated-Array-Closest-to-Target) (M+) -[1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows) (H) [1482.Minimum-Number-of-Days-to-Make-m-Bouquets](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets) (M) [1508.Range-Sum-of-Sorted-Subarray-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1508.Range-Sum-of-Sorted-Subarray-Sums) (M+) [1552.Magnetic-Force-Between-Two-Balls](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1552.Magnetic-Force-Between-Two-Balls) (M) @@ -112,7 +113,6 @@ [1870.Minimum-Speed-to-Arrive-on-Time](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1870.Minimum-Speed-to-Arrive-on-Time) (M) [1898.Maximum-Number-of-Removable-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1898.Maximum-Number-of-Removable-Characters) (H-) [1891.Cutting-Ribbons](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1891.Cutting-Ribbons) (E) -[1918.Kth-Smallest-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1918.Kth-Smallest-Subarray-Sum) (M+) #### [Hash Table](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From d6562467de7bc4bc5548b8963e1d19b79ecf893c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 16:19:38 -0700 Subject: [PATCH 0065/2729] Update 1918.Kth-Smallest-Subarray-Sum.cpp --- .../1918.Kth-Smallest-Subarray-Sum.cpp | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/Binary_Search/1918.Kth-Smallest-Subarray-Sum/1918.Kth-Smallest-Subarray-Sum.cpp b/Binary_Search/1918.Kth-Smallest-Subarray-Sum/1918.Kth-Smallest-Subarray-Sum.cpp index b96400adb..b1fc35c06 100644 --- a/Binary_Search/1918.Kth-Smallest-Subarray-Sum/1918.Kth-Smallest-Subarray-Sum.cpp +++ b/Binary_Search/1918.Kth-Smallest-Subarray-Sum/1918.Kth-Smallest-Subarray-Sum.cpp @@ -2,11 +2,18 @@ class Solution { public: int kthSmallestSubarraySum(vector& nums, int k) { + vectorpresum(nums.size()+1); + for (int i=0; i= k) right = mid; else left = mid+1; @@ -14,23 +21,21 @@ class Solution { return left; } - bool countOK(vector&nums, long long target, int k) + int countSmallerOrEqual(int t, vector&presum) { - int count = 0; - long long sum = 0; + int ret = 0; + // for (int i=0; i=k) return true; + ret+=j-(i+1); } - return false; + return ret; } }; From dcacfa5297a2af41e2e89001935dfdcbf477ebcb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 16:31:40 -0700 Subject: [PATCH 0066/2729] Update Readme.md --- Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md b/Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md index e564722ec..78bf7cd93 100644 --- a/Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md +++ b/Binary_Search/1918.Kth-Smallest-Subarray-Sum/Readme.md @@ -1,9 +1,10 @@ ### 1918.Kth-Smallest-Subarray-Sum -此题本质等同于```719. Find K-th Smallest Pair Distance```. +此题本质等同于```719. Find K-th Smallest Pair Distance```. 在719中我们要寻找第k小的pair diff。在本题中,如果我们转成前缀和数组presum,那么本质上也就是在presum里找第k小的pair diff. -我们用二分搜索猜测这个target。设计检验函数checkOK来判断if # of subarrays whose sum <= target is at least k. 如果是的话,那么这个target可以再小一些(但可能就是第k小的sum);如果不是的话,说明target一定偏小,需要往大里猜。本题一定有解,所以收链解就是最终解。 +对于"k-th"的题型,二分搜值是一个固定的套路。我们假设第k小的diff的数值是mid,那么我们就计算presum里有多少diff<=mid的pairs。我们期望这个数量至少要是k个。如果count=k,那么mid本身可能是正解(因为可能多有个diff的数值是mid),同时也可能我们猜的比较大,可以往更小的数值猜(即right=mid). -在写checkOK(nums, target, k)的时候,用的是快慢指针。从左往右遍历慢指针i,然后调整快指针j使得sum[i:j]恰好大于target,于是j-i就是以i为左端点的合法subarray的数目(即subarray sum <= target)。然后我们将i移动一位,j继续单调地向右移动,同样直至恰好```sum[i:j]>target```,同样将j-i加入count里。一旦count的数目大于等于k了,就可以停止双指针的搜索了。 +那么我们如何在所有的diff里计算```countSmallerOrEqual(mid)```呢?两种思路: -此题有一个更难的二维版本```1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows```. +1. 固定presum[i],在presum里找多少个j,使得```presum[j]-presum[i]<=mid```,变化得到```presum[j]<=mid+presum[i]```,所以可以用upper_bound定位j的邻接位置j'。从```[i+1, j')```都是可行解。 +2. 双指针。同样固定presum[i],探索presum[j]。但是我们发现随着i的增大,j的临界位置也是单调变大的。所以j'可以用o(N)的算法找到。 From a35865464a4f4890097b11f1786966ea5449092c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 18:24:00 -0700 Subject: [PATCH 0067/2729] Create 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp --- ...-Smallest-Product-of-Two-Sorted-Arrays.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp diff --git a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp new file mode 100644 index 000000000..92cd4275a --- /dev/null +++ b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp @@ -0,0 +1,49 @@ +using LL = long long; +class Solution { +public: + long long kthSmallestProduct(vector& nums1, vector& nums2, long long k) + { + if (nums1.size() > nums2.size()) + return kthSmallestProduct(nums2, nums1, k); + + LL left = -1e10, right = 1e10; + while (left < right) + { + LL mid = left+(right-left)/2; + if (checkNums(mid, nums1, nums2) >= k) + right = mid; + else + left = mid+1; + } + return left; + } + + LL checkNums(LL mid, vector& nums1, vector& nums2) + { + LL ret = 0; + for (int i=0; i 0) + { + LL yy = floor(mid*1.0/x); + auto iter = upper_bound(nums2.begin(), nums2.end(), yy); + ret += (iter-nums2.begin()); + } + else + { + LL yy = ceil(mid*1.0/x); + auto iter = lower_bound(nums2.begin(), nums2.end(), yy); + ret += nums2.size() - (iter-nums2.begin()); + } + } + + return ret; + } +}; From 25c3e9fd9ca428617c6d3546393982c5e798347b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 18:24:32 -0700 Subject: [PATCH 0068/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c9a9bbdd7..d17a7e2aa 100644 --- a/Readme.md +++ b/Readme.md @@ -91,6 +91,7 @@ [668.Kth-Smallest-Number-in-Multiplication-Table](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table) (H-) [719.Find-K-th-Smallest-Pair-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/719.Find-K-th-Smallest-Pair-Distance) (H-) [1918.Kth-Smallest-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1918.Kth-Smallest-Subarray-Sum) (M+) +[2040.Kth-Smallest-Product-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays) (H-) [1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows) (H) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [786.K-th-Smallest-Prime-Fraction](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/786.K-th%20Smallest-Prime-Fraction) (H-) From c5aeb890e61d0d39a87915e7aecde6d9e85e7ca4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 23:39:12 -0700 Subject: [PATCH 0069/2729] Create 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp --- ...allest-Product-of-Two-Sorted-Arrays_v2.cpp | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp diff --git a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp new file mode 100644 index 000000000..4c8a0186e --- /dev/null +++ b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v2.cpp @@ -0,0 +1,75 @@ +using LL = long long; +class Solution { +public: + long long kthSmallestProduct(vector& nums1, vector& nums2, long long k) + { + if (nums1.size() > nums2.size()) + return kthSmallestProduct(nums2, nums1, k); + + LL left = -1e10, right = 1e10; + while (left < right) + { + LL mid = left+(right-left)/2; + LL count = countSmallerOrEqual(mid, nums1, nums2); + if (count < k) + left = mid+1; + else + right = mid; + } + return left; + } + + LL countSmallerOrEqual(LL mid, vector& nums1, vector& nums2) + { + LL ret = 0; + + if (mid >= 0) + { + int j0 = nums2.size()-1; + int j1 = nums2.size()-1; + + for (int i=0; i0) + { + while (j0>=0 && (LL)nums1[i]*(LL)nums2[j0] > mid) + j0--; + ret += j0+1; + } + else if (nums1[i]==0) + ret += nums2.size(); + else + { + while (j1>=0 && (LL)nums1[i]*(LL)nums2[j1] <= mid) + j1--; + ret += nums2.size()-1-j1; + } + } + } + else + { + int j0 = 0; + int j1 = 0; + + for (int i=0; i0) + { + while (j0 mid) + j1++; + ret += nums2.size()-j1; + } + } + } + + return ret; + } +}; From 38d671e1b0da5d2573dc4e0350d8a438ad6c6e85 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Oct 2021 23:39:22 -0700 Subject: [PATCH 0070/2729] Rename 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp to 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v1.cpp --- ....cpp => 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/{2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp => 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v1.cpp} (100%) diff --git a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v1.cpp similarity index 100% rename from Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays.cpp rename to Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays_v1.cpp From f9ae020ac2a61df334eef11fa22ab521f1c9485e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 00:09:25 -0700 Subject: [PATCH 0071/2729] Create Readme.md --- .../Readme.md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md diff --git a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md new file mode 100644 index 000000000..7ff2270d4 --- /dev/null +++ b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md @@ -0,0 +1,29 @@ +### 2040.Kth-Smallest-Product-of-Two-Sorted-Arrays + +本题是类似```1918.Kth-Smallest-Subarray-Sum```的套路题,采用二分搜值来猜测答案。 + +我们令```count = countSmallerOrEqual(m)```来计算有多少对乘积小于或等于m。如果这个数目小于k,那么说明m肯定不是答案,并且易知k太小,所以应该尝试更大的数(即lower = m+1)。如果count大于等于k,说明m可能是答案(因为允许有若干对成绩都等于m)或者m可能猜大了,所以接下来尝试更小的数(即upper = m)。利用二分搜值的模板,直至收敛到```left==right```,就是最终的解。 + +如果实现函数```countSmallerOrEqual(m)```呢? + +#### 方法1: +最简单的方法就是遍历nums1[i],在有序数组nums2里面用二分法找一个临界位置j,使得```nums1[i]*nums2[j]<=m```. 这个临界位置j的确定需要分类讨论。 + +如果nums1[i]>0,那么我们有```nums[j] <= m/nums1[i]```,当m/nums1[i]不能整除时,我们必须保守地取floor(). 这样我们可以用upper_bound求得第一个大于m/nums1[i]的位置j,那么[0,j-1]都是满足条件的解。 + +如果nums1[i]<0,那么根据不等式性质,移项需要变号,所以我们有```nums[j] >= m/nums1[i]```,当m/nums1[i]不能整除时,我们必须保守地取ceil(). 这样我们可以用lower_bound求得第一个大于等于m/nums1[i]的位置j,那么[j,n-1]都是满足条件的解。 + +特殊地nums1[i]==0,那么有多少j满足```0*nums[j]<=m```呢?这个其实取决于m。如果m是负数,无解。如果m是非负数,所有的nums2都是解。 + +#### 方法2: +类似1918,我们也可以用双指针的单调性来实现o(n)的```countSmallerOrEqual(m)```,不过讨论起来就更复杂了。 + +1. m>=0 +(i) nums[i]>0: 我们有 nums2[j] <= m/nums1[i]。可以知道nums2[j]有个上界,且随着nums1[i]的增大,这个上界越来越小。所以我们从大到小单调地移动j,找到与i对应的临界位置j,那么[0:j]都是合法的解。 +(ii) nums[i]==0: 所有的nums2都是解。 +(iii) nums[i]<0: 我们有 nums2[j] >= m/nums1[i]。可以知道nums2[j]有个下界,且随着nums1[i]的增大,这个上界越来越小。所以我们从大到小单调地移动j,找到与i对应的临界位置j,那么[j:n-1]都是合法的解。 + +2. m<0 +(i) nums[i]>0: 我们有 nums2[j] <= m/nums1[i]。可以知道nums2[j]有个上界,且随着nums1[i]的增大,这个上界越来越大。所以我们从小到大单调地移动j,找到与i对应的临界位置j,那么[0:j]都是合法的解。 +(ii) nums[i]==0: 所有的nums2都不会是解 (因为不可能 ```0*nums[j] < m```)。 +(iii) nums[i]<0: 我们有 nums2[j] >= m/nums1[i]。可以知道nums2[j]有个下界,且随着nums1[i]的增大,这个上界越来越大。所以我们从小到大单调地移动j,找到与i对应的临界位置j,那么[j:n-1]都是合法的解。 From 795e9a427788e85e29959d1fb9020ce2c7fc07ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 01:20:24 -0700 Subject: [PATCH 0072/2729] Update Readme.md --- .../2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md index 7ff2270d4..40ff07d56 100644 --- a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md +++ b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md @@ -18,6 +18,8 @@ #### 方法2: 类似1918,我们也可以用双指针的单调性来实现o(n)的```countSmallerOrEqual(m)```,不过讨论起来就更复杂了。 +```nums[i]* nums[j] <= m``` + 1. m>=0 (i) nums[i]>0: 我们有 nums2[j] <= m/nums1[i]。可以知道nums2[j]有个上界,且随着nums1[i]的增大,这个上界越来越小。所以我们从大到小单调地移动j,找到与i对应的临界位置j,那么[0:j]都是合法的解。 (ii) nums[i]==0: 所有的nums2都是解。 From 55852deda073162f01ed329db7162f162123cddf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 01:20:41 -0700 Subject: [PATCH 0073/2729] Update Readme.md --- .../2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md index 40ff07d56..067937133 100644 --- a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md +++ b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md @@ -18,7 +18,7 @@ #### 方法2: 类似1918,我们也可以用双指针的单调性来实现o(n)的```countSmallerOrEqual(m)```,不过讨论起来就更复杂了。 -```nums[i]* nums[j] <= m``` +```nums1[i]* nums2[j] <= m``` 1. m>=0 (i) nums[i]>0: 我们有 nums2[j] <= m/nums1[i]。可以知道nums2[j]有个上界,且随着nums1[i]的增大,这个上界越来越小。所以我们从大到小单调地移动j,找到与i对应的临界位置j,那么[0:j]都是合法的解。 From 13adc36c95996c9352221583e20fbac4184014a6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 01:24:12 -0700 Subject: [PATCH 0074/2729] Update Readme.md --- .../2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md index 067937133..d3918ea3b 100644 --- a/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md +++ b/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays/Readme.md @@ -23,9 +23,9 @@ 1. m>=0 (i) nums[i]>0: 我们有 nums2[j] <= m/nums1[i]。可以知道nums2[j]有个上界,且随着nums1[i]的增大,这个上界越来越小。所以我们从大到小单调地移动j,找到与i对应的临界位置j,那么[0:j]都是合法的解。 (ii) nums[i]==0: 所有的nums2都是解。 -(iii) nums[i]<0: 我们有 nums2[j] >= m/nums1[i]。可以知道nums2[j]有个下界,且随着nums1[i]的增大,这个上界越来越小。所以我们从大到小单调地移动j,找到与i对应的临界位置j,那么[j:n-1]都是合法的解。 +(iii) nums[i]<0: 我们有 nums2[j] >= m/nums1[i]。可以知道nums2[j]有个下界,且随着nums1[i]的增大,这个下界越来越小。所以我们从大到小单调地移动j,找到与i对应的临界位置j,那么[j:n-1]都是合法的解。 2. m<0 (i) nums[i]>0: 我们有 nums2[j] <= m/nums1[i]。可以知道nums2[j]有个上界,且随着nums1[i]的增大,这个上界越来越大。所以我们从小到大单调地移动j,找到与i对应的临界位置j,那么[0:j]都是合法的解。 (ii) nums[i]==0: 所有的nums2都不会是解 (因为不可能 ```0*nums[j] < m```)。 -(iii) nums[i]<0: 我们有 nums2[j] >= m/nums1[i]。可以知道nums2[j]有个下界,且随着nums1[i]的增大,这个上界越来越大。所以我们从小到大单调地移动j,找到与i对应的临界位置j,那么[j:n-1]都是合法的解。 +(iii) nums[i]<0: 我们有 nums2[j] >= m/nums1[i]。可以知道nums2[j]有个下界,且随着nums1[i]的增大,这个下界越来越大。所以我们从小到大单调地移动j,找到与i对应的临界位置j,那么[j:n-1]都是合法的解。 From 63beedfdc8aac813af8a9ed562a1bae5912559ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 14:37:40 -0700 Subject: [PATCH 0075/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d17a7e2aa..a3a977169 100644 --- a/Readme.md +++ b/Readme.md @@ -322,6 +322,7 @@ [2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2030.Smallest-K-Length-Subsequence-With-Occurrences-of-a-Letter) (H) [316.Remove-Duplicate-Letters](https://github.com/wisdompeak/LeetCode/tree/master/Stack/316.Remove-Duplicate-Letters) (H) [1081.Smallest-Subsequence-of-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1081.Smallest-Subsequence-of-Distinct-Characters) (M+) +[321.Create-Maximum-Number](https://github.com/wisdompeak/LeetCode/tree/master/Stack/321.Create-Maximum-Number) (H) * ``parse expression`` [071.Simplify-Path](https://github.com/wisdompeak/LeetCode/tree/master/Stack/071.Simplify-Path) (M) [224.Basic-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Stack/224.Basic-Calculator)(H-) @@ -951,7 +952,6 @@ 624.Maximum-Distance-in-Arrays (M) [665.Non-decreasing-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/665.Non-decreasing-Array) (H) 670.Maximum-Swap (M+) -[321.Create-Maximum-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/321.Create-Maximum-Number) (H) 649.Dota2-Senate (H) [330.Patching-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/330.Patching-Array) (H) [683.K-Empty-Slots](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/683.K-Empty-Slots) (H) From 0ec192b3d9db9f98213f7882450c8d0d699289c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 14:38:59 -0700 Subject: [PATCH 0076/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a3a977169..a08e022c0 100644 --- a/Readme.md +++ b/Readme.md @@ -174,6 +174,7 @@ [1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1825.Finding-MK-Average) (H) [1847.Closest-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1847.Closest-Room) (M+) [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) +2034.Stock Price Fluctuation (M) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From 5bafe188f7bbab394f3522bd477e142471d03fa4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 15:22:39 -0700 Subject: [PATCH 0077/2729] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index a08e022c0..d4a8e3683 100644 --- a/Readme.md +++ b/Readme.md @@ -350,7 +350,6 @@ #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) -[378.Kth-Smallest-Element-in-a-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/378.Kth-Smallest-Element-in-a-Sorted-Matrix) (H-) [373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums) (H) [642.Design-Search-Autocomplete-System](https://github.com/wisdompeak/LeetCode/tree/master/Design/642.Design-Search-Autocomplete-System) (M+) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From 5b7b9e36ba017044f962088efbe92d93a1c23e4d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 15:35:16 -0700 Subject: [PATCH 0078/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index d4a8e3683..dd1f5488b 100644 --- a/Readme.md +++ b/Readme.md @@ -86,8 +86,8 @@ * ``Binary Search by Value`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) -[378.Kth-Smallest-Element-in-a-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/378.Kth-Smallest-Element-in-a-Sorted-Matrix) (H-) -[373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums) (H) +[378.Kth-Smallest-Element-in-a-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix) (H-) +[373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums) (H) [668.Kth-Smallest-Number-in-Multiplication-Table](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table) (H-) [719.Find-K-th-Smallest-Pair-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/719.Find-K-th-Smallest-Pair-Distance) (H-) [1918.Kth-Smallest-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1918.Kth-Smallest-Subarray-Sum) (M+) From 8864bd3579fd4068bdcd30ea8f4360d2d5982157 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 15:35:35 -0700 Subject: [PATCH 0079/2729] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index dd1f5488b..82d8bd64b 100644 --- a/Readme.md +++ b/Readme.md @@ -350,7 +350,6 @@ #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) -[373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums) (H) [642.Design-Search-Autocomplete-System](https://github.com/wisdompeak/LeetCode/tree/master/Design/642.Design-Search-Autocomplete-System) (M+) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [871.Minimum-Number-of-Refueling-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/871.Minimum-Number-of-Refueling-Stops) (H-) From 502d0edd35bb1f2cc47036f4914b0b848415c7d8 Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Sun, 17 Oct 2021 15:39:06 -0700 Subject: [PATCH 0080/2729] mv 373 378 321 --- .../373.Find-K-Pairs-with-Smallest-Sums.cpp | 0 .../373.Find-K-Pairs-with-Smallest-Sums_v2.cpp | 0 .../373.Find-K-Pairs-with-Smallest-Sums/Readme.md | 0 .../378.Kth Smallest Element in a Sorted Matrix.cpp | 0 .../378.Kth-Smallest-Element-in-a-Sorted-Matrix_v2.cpp | 0 .../378.Kth-Smallest-Element-in-a-Sorted-Matrix/Readme.md | 0 .../321.Create-Maximum-Number/321.Create-Maximum-Number.cpp | 0 .../321.Create-Maximum-Number/321.Create-Maximum-Number_dp.cpp | 0 {Greedy => Stack}/321.Create-Maximum-Number/Readme.md | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename {Priority_Queue => Binary_Search}/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp (100%) rename {Priority_Queue => Binary_Search}/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp (100%) rename {Priority_Queue => Binary_Search}/373.Find-K-Pairs-with-Smallest-Sums/Readme.md (100%) rename {Priority_Queue => Binary_Search}/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth Smallest Element in a Sorted Matrix.cpp (100%) rename {Priority_Queue => Binary_Search}/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth-Smallest-Element-in-a-Sorted-Matrix_v2.cpp (100%) rename {Priority_Queue => Binary_Search}/378.Kth-Smallest-Element-in-a-Sorted-Matrix/Readme.md (100%) rename {Greedy => Stack}/321.Create-Maximum-Number/321.Create-Maximum-Number.cpp (100%) rename {Greedy => Stack}/321.Create-Maximum-Number/321.Create-Maximum-Number_dp.cpp (100%) rename {Greedy => Stack}/321.Create-Maximum-Number/Readme.md (100%) diff --git a/Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp similarity index 100% rename from Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp rename to Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp diff --git a/Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp similarity index 100% rename from Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp rename to Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp diff --git a/Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums/Readme.md b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md similarity index 100% rename from Priority_Queue/373.Find-K-Pairs-with-Smallest-Sums/Readme.md rename to Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md diff --git a/Priority_Queue/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth Smallest Element in a Sorted Matrix.cpp b/Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth Smallest Element in a Sorted Matrix.cpp similarity index 100% rename from Priority_Queue/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth Smallest Element in a Sorted Matrix.cpp rename to Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth Smallest Element in a Sorted Matrix.cpp diff --git a/Priority_Queue/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth-Smallest-Element-in-a-Sorted-Matrix_v2.cpp b/Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth-Smallest-Element-in-a-Sorted-Matrix_v2.cpp similarity index 100% rename from Priority_Queue/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth-Smallest-Element-in-a-Sorted-Matrix_v2.cpp rename to Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix/378.Kth-Smallest-Element-in-a-Sorted-Matrix_v2.cpp diff --git a/Priority_Queue/378.Kth-Smallest-Element-in-a-Sorted-Matrix/Readme.md b/Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix/Readme.md similarity index 100% rename from Priority_Queue/378.Kth-Smallest-Element-in-a-Sorted-Matrix/Readme.md rename to Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix/Readme.md diff --git a/Greedy/321.Create-Maximum-Number/321.Create-Maximum-Number.cpp b/Stack/321.Create-Maximum-Number/321.Create-Maximum-Number.cpp similarity index 100% rename from Greedy/321.Create-Maximum-Number/321.Create-Maximum-Number.cpp rename to Stack/321.Create-Maximum-Number/321.Create-Maximum-Number.cpp diff --git a/Greedy/321.Create-Maximum-Number/321.Create-Maximum-Number_dp.cpp b/Stack/321.Create-Maximum-Number/321.Create-Maximum-Number_dp.cpp similarity index 100% rename from Greedy/321.Create-Maximum-Number/321.Create-Maximum-Number_dp.cpp rename to Stack/321.Create-Maximum-Number/321.Create-Maximum-Number_dp.cpp diff --git a/Greedy/321.Create-Maximum-Number/Readme.md b/Stack/321.Create-Maximum-Number/Readme.md similarity index 100% rename from Greedy/321.Create-Maximum-Number/Readme.md rename to Stack/321.Create-Maximum-Number/Readme.md From cf76c36f7b184bb6c87cc6a5594007ceb8258ce0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 16:23:11 -0700 Subject: [PATCH 0081/2729] Update 373.Find-K-Pairs-with-Smallest-Sums_v2.cpp --- ...373.Find-K-Pairs-with-Smallest-Sums_v2.cpp | 83 +++++++------------ 1 file changed, 32 insertions(+), 51 deletions(-) diff --git a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp index 03ab002a9..bc577cb5c 100644 --- a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp +++ b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp @@ -1,69 +1,50 @@ -class Solution { - static bool cmp(vector&a, vector&b) - { - return a[0]+a[1]> kSmallestPairs(vector& nums1, vector& nums2, int k) { - int M = nums1.size(); - int N = nums2.size(); - if (M==0 || N==0) return {}; - - auto matrix = vector>(M,vector(N)); - for (int i=0; i>results; - int i = M-1, j = 0; - while (i>=0 && j>rets1; + vector>rets2; + for (int i=0; i=0; k--) - results.push_back({nums1[k],nums2[j]}); + if (nums1[i]+nums2[j]>& matrix, int x) + + long countSmallerOrEqual(int m, vector& nums1, vector& nums2) { - int M = matrix.size(); - int N = matrix[0].size(); - int i = M-1, j = 0; - int count = 0; - while (i>=0 && j=0 && nums1[i]+nums2[j]>m) + j--; + ret += j+1; } - return count; + return ret; } }; From e79b35102d260466a69057931bd9a9ce58c71e20 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 16:27:50 -0700 Subject: [PATCH 0082/2729] Update Readme.md --- .../373.Find-K-Pairs-with-Smallest-Sums/Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md index f54abedd8..ee5e98eca 100644 --- a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md +++ b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md @@ -8,9 +8,11 @@ 用BFS的方法进行搜索。每次弹出一个PQ里最小的元素,然后新加入该元素相邻(右边和下边)的两个元素。最先弹出的k个元素就是答案。 #### 解法2:binary search + sorted matrix property -此题和378. Kth Smallest Element in a Sorted Matrix非常相似。 +此题和378, 668, 719, 1918都是一样的套路。 -用binary search的方法先确定按从小到大顺序第k个元素是多少,令它为x。然后打印出matrix里面所有小于等于x的元素。注意,这样的元素可能会超过k个,也可能会小于k个。最终只要输出k个。 +用binary search的方法先确定k-th smalletst elsment是多少,令它为x。然后遍历所有的nums1[i],单调寻找满足```nums1[i]+nums2[j]<=x```的配对。 +注意,这样的元素可能会超过k个,也可能会小于k个。最终只要输出k个。 -[Leetcode Link](https://leetcode.com/problems/find-k-pairs-with-smallest-sums) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/find-k-pairs-with-smallest-sums) From db04fcede2f88001a6a8725cc33cf0d778dad0b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 17:23:23 -0700 Subject: [PATCH 0083/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 82d8bd64b..858c8a9a4 100644 --- a/Readme.md +++ b/Readme.md @@ -89,12 +89,12 @@ [378.Kth-Smallest-Element-in-a-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix) (H-) [373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums) (H) [668.Kth-Smallest-Number-in-Multiplication-Table](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table) (H-) -[719.Find-K-th-Smallest-Pair-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/719.Find-K-th-Smallest-Pair-Distance) (H-) +[719.Find-Kth-Smallest-Pair-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/719.Find-K-th-Smallest-Pair-Distance) (H-) [1918.Kth-Smallest-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1918.Kth-Smallest-Subarray-Sum) (M+) [2040.Kth-Smallest-Product-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays) (H-) [1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows) (H) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) -[786.K-th-Smallest-Prime-Fraction](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/786.K-th%20Smallest-Prime-Fraction) (H-) +[786.Kth-Smallest-Prime-Fraction](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/786.K-th%20Smallest-Prime-Fraction) (H-) [793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) [1011.Capacity-To-Ship-Packages-Within-D-Days](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1011.Capacity-To-Ship-Packages-Within-D-Days) (M) [1060.Missing-Element-in-Sorted-Array](https://github.com/wisdompeak/LeetCode/blob/master/Binary_Search/1060.Missing-Element-in-Sorted-Array) (H) From 4dc9c5e1d5feb2adb15d0a92b438bfd43a767c36 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 17:24:20 -0700 Subject: [PATCH 0084/2729] Create 2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp --- ...t-Number-of-Maximum-Bitwise-OR-Subsets.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp diff --git a/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp b/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp new file mode 100644 index 000000000..77edc5dd7 --- /dev/null +++ b/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int countMaxOrSubsets(vector& nums) + { + int n = nums.size(); + int k = 17; + vectordp(1<=0; s--) + { + if (dp[s]>0) + return dp[s]; + } + + return 0; + } +}; From f4c7425fb7bdadb767e6cfddd2e00346a87b2f3d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 17:25:57 -0700 Subject: [PATCH 0085/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 858c8a9a4..bd297c615 100644 --- a/Readme.md +++ b/Readme.md @@ -697,7 +697,8 @@ [629.K-Inverse-Pairs-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/629.K-Inverse-Pairs-Array) (H) [903.Valid-Permutations-for-DI-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence) (H) [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) - +* ``Infer future from current`` +[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From 7434572719ba0a6da79206bdecdae456a461d1c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 17:44:47 -0700 Subject: [PATCH 0086/2729] Update 2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp --- .../2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp b/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp index 77edc5dd7..ce2d7d441 100644 --- a/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp +++ b/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets.cpp @@ -3,21 +3,21 @@ class Solution { int countMaxOrSubsets(vector& nums) { int n = nums.size(); - int k = 17; - vectordp(1<dp(M+1); dp[0] = 1; for (int x : nums) { auto dp2 = dp; - for (int s = 0; s<(1<=0; s--) + for (int s=M; s>=0; s--) { if (dp[s]>0) return dp[s]; From 65535236fc851fbac76f4a27cd90ce80ca0df115 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 18:06:13 -0700 Subject: [PATCH 0087/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/Readme.md diff --git a/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/Readme.md b/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/Readme.md new file mode 100644 index 000000000..99e54d678 --- /dev/null +++ b/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets/Readme.md @@ -0,0 +1,7 @@ +### 2044.Count-Number-of-Maximum-Bitwise-OR-Subsets + +因为所有的元素都小于1e5,它们只需要17个bit即可表达。而且不管OR的操作进行多少次,都不会溢出2^17的范围。所以我们可以枚举所有可能的bitwise OR的结果,令dp[val]表示得到val的方案数。类似背包问题,我们每得到一个新的数字x,就可以考虑它的作用,更新一遍所有的dp[val]. + +注意,本题中的状态转移是从现在转移到未来。也就是已知上一轮的dp[i-1][val],那么我们此次使用x的话,可以知道这一轮dp[i][val|x]的实现至少能有dp[i-1][val]种方案(就是在原先dp[val]所对应的方案基础上都使用x)。 + +如果状态转移的策略反过来的话就很难做。因为如果我们想知道本轮的dp[i][val],就需要穷举上一轮的所有满足```v|x == val```的状态v,这样才能有```dp[i][val] = sum(dp[i-1][v]```. From b4b3171f6a00970f8851e847c17e6a2103510d85 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 23:38:09 -0700 Subject: [PATCH 0088/2729] Create 2045.Second-Minimum-Time-to-Reach-Destination.cpp --- ...cond-Minimum-Time-to-Reach-Destination.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 BFS/2045.Second-Minimum-Time-to-Reach-Destination/2045.Second-Minimum-Time-to-Reach-Destination.cpp diff --git a/BFS/2045.Second-Minimum-Time-to-Reach-Destination/2045.Second-Minimum-Time-to-Reach-Destination.cpp b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/2045.Second-Minimum-Time-to-Reach-Destination.cpp new file mode 100644 index 000000000..bded4be9e --- /dev/null +++ b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/2045.Second-Minimum-Time-to-Reach-Destination.cpp @@ -0,0 +1,48 @@ +using PII = pair; +class Solution { +public: + int secondMinimum(int n, vector>& edges, int time, int change) + { + vector>next(n+1); + for (auto edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + + priority_queue, greater<>>pq; + pq.push({0,1}); + vectorarrival1(n+1, -1); + vectorarrival2(n+1, -1); + + while (!pq.empty()) + { + auto [t, cur] = pq.top(); + pq.pop(); + if (arrival2[cur]!=-1) + continue; + else if (arrival1[cur]!=-1 && t > arrival1[cur]) + arrival2[cur] = t; + else if (arrival1[cur]==-1) + arrival1[cur] = t; + + if (cur==n && arrival2[cur]!=-1) + return arrival2[cur]; + + int tt; + if ((t/change)%2 == 0) + tt = t+time; + else + tt = ((t-1)/(2*change)+1)*(2*change) + time; + + for (int nxt: next[cur]) + { + if (arrival2[nxt]!=-1) continue; + pq.push({tt, nxt}); + } + } + + return -1; + } +}; From 4389eccc25ff6148c3c3e831799f7adccbbbee2a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 23:38:36 -0700 Subject: [PATCH 0089/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bd297c615..08b136128 100644 --- a/Readme.md +++ b/Readme.md @@ -477,6 +477,7 @@ [1786.Number-of-Restricted-Paths-From-First-to-Last-Node](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1786.Number-of-Restricted-Paths-From-First-to-Last-Node) (H-) [1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (H-) +[2045.Second-Minimum-Time-to-Reach-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2045.Second-Minimum-Time-to-Reach-Destination) (M+) #### [Trie](https://github.com/wisdompeak/LeetCode/tree/master/Trie) [208.Implement-Trie--Prefix-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Trie/208.Implement-Trie--Prefix-Tree) (M+) From c3e1798f47cb5da1483fb3594f79cd02fcb6b924 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 23:47:34 -0700 Subject: [PATCH 0090/2729] Create Readme.md --- BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md diff --git a/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md new file mode 100644 index 000000000..85b731397 --- /dev/null +++ b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md @@ -0,0 +1,5 @@ +### 2045.Second-Minimum-Time-to-Reach-Destination + +Dijkstra算用可以用来求最短路径,自然也可以用来求第二短路径。我们只要在算法中略作改动:第一次从pq里弹出某节点node时对应的路径是最短路径arrival1[node],此时我们一切照旧进行BFS;直到该节点被第二次从pq里弹出并且能更新为arrival2[node]之后,我们才禁止在pq里再加入node。 + +另外根据题意,假设当前cur被到达的时刻是t,那么有两种可能:t落在了绿灯时段,那么我们就可以在t+time时候到达nxt。如果t落在了红灯时段,那么我们必须在下一个绿灯时段开始后time再到达nxt。判断是否落在绿灯时段,就看t/change是否是偶数。判断合适是下一个绿灯时段的开始,我们就以```2*change```为一个周期,故计算t的下一个周期开始的时候。 From 2e0a41c602ae2791b7e596084a16af9f86c9f827 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Oct 2021 23:49:23 -0700 Subject: [PATCH 0091/2729] Update Readme.md --- BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md index 85b731397..3a6080d50 100644 --- a/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md +++ b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md @@ -2,4 +2,4 @@ Dijkstra算用可以用来求最短路径,自然也可以用来求第二短路径。我们只要在算法中略作改动:第一次从pq里弹出某节点node时对应的路径是最短路径arrival1[node],此时我们一切照旧进行BFS;直到该节点被第二次从pq里弹出并且能更新为arrival2[node]之后,我们才禁止在pq里再加入node。 -另外根据题意,假设当前cur被到达的时刻是t,那么有两种可能:t落在了绿灯时段,那么我们就可以在t+time时候到达nxt。如果t落在了红灯时段,那么我们必须在下一个绿灯时段开始后time再到达nxt。判断是否落在绿灯时段,就看t/change是否是偶数。判断合适是下一个绿灯时段的开始,我们就以```2*change```为一个周期,故计算t的下一个周期开始的时候。 +另外根据题意,假设当前cur被到达的时刻是t,那么有两种可能:t落在了绿灯时段,那么我们就可以在t+time时候到达nxt。如果t落在了红灯时段,那么我们必须在下一个绿灯时段开始后time再到达nxt。判断是否落在绿灯时段,就看t/change是否是偶数。判断何时是下一个绿灯时段的开始,我们就以```2*change```为一个周期,计算t落在了哪个周期```k=(t-1)/(2*change)+1```,那么```k*2*change```就是该周期结束、新周期开始的时刻。 From 17f17ba6c0248eb8ba5da8074600c4aa46b588a3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Oct 2021 01:17:09 -0700 Subject: [PATCH 0092/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/1617.Count-Subtrees-With-Max-Distance-Between-Cities/Readme.md b/BFS/1617.Count-Subtrees-With-Max-Distance-Between-Cities/Readme.md index d36254aca..1a11f3c1d 100644 --- a/BFS/1617.Count-Subtrees-With-Max-Distance-Between-Cities/Readme.md +++ b/BFS/1617.Count-Subtrees-With-Max-Distance-Between-Cities/Readme.md @@ -2,7 +2,7 @@ 本题要求统计:对于每一种长度d,有多少个subtree的最大直径等于d。根据长度来“构造”满足条件的树,其实是比较困难的。我们可以反过来想,对于每个subtree,我们查看它的最大直径是多少,然后做统计的aggregation。根据一个固定的subtree,求最大直径,这是一个确定性的问题,通常比构造性的问题简单的多。另外这个题目中节点数目小于等于15,穷举所有subtree(包括非法的不连通的图),也就是2^15=32768种,这是可以接受的。 -给定了一棵树的拓扑结构,如何计算它的最长直径呢?这是一个经典的问题,有着经典的o(N)的解法: +给定了一棵树的拓扑结构,如何计算它的最长直径呢?这是一个经典的问题,有着经典的o(N)的解法:(参见 LC 1245.Tree-Diameter) 1. 以图里的任意一个节点作为起始点A(看做根),往外做BFS遍历,能够到达的最远的节点B,那么B一定是最大直径的一个端点。 2. 我们以B作为起始点(看做根),往外做BFS遍历,能够到达的最远的节点C,那么BC的路径就是最大直径的距离。 From 63981f7428814301807bfc4dfc0c5989e702dcf6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Oct 2021 01:34:39 -0700 Subject: [PATCH 0093/2729] Update 2045.Second-Minimum-Time-to-Reach-Destination.cpp --- ...cond-Minimum-Time-to-Reach-Destination.cpp | 47 +++++++++---------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/BFS/2045.Second-Minimum-Time-to-Reach-Destination/2045.Second-Minimum-Time-to-Reach-Destination.cpp b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/2045.Second-Minimum-Time-to-Reach-Destination.cpp index bded4be9e..85c8515fa 100644 --- a/BFS/2045.Second-Minimum-Time-to-Reach-Destination/2045.Second-Minimum-Time-to-Reach-Destination.cpp +++ b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/2045.Second-Minimum-Time-to-Reach-Destination.cpp @@ -3,46 +3,45 @@ class Solution { public: int secondMinimum(int n, vector>& edges, int time, int change) { - vector>next(n+1); + vectornext[n+1]; for (auto edge: edges) { int a = edge[0], b = edge[1]; next[a].push_back(b); next[b].push_back(a); - } - - priority_queue, greater<>>pq; - pq.push({0,1}); - vectorarrival1(n+1, -1); - vectorarrival2(n+1, -1); + } + + vectorvisited(n+1,0); + vectordist(n+1,-1); + queueq; + q.push({1,0}); + dist[1] = 0; - while (!pq.empty()) + while (!q.empty()) { - auto [t, cur] = pq.top(); - pq.pop(); - if (arrival2[cur]!=-1) - continue; - else if (arrival1[cur]!=-1 && t > arrival1[cur]) - arrival2[cur] = t; - else if (arrival1[cur]==-1) - arrival1[cur] = t; - - if (cur==n && arrival2[cur]!=-1) - return arrival2[cur]; + auto [cur, t] = q.front(); + q.pop(); int tt; - if ((t/change)%2 == 0) + int round = t/change; + if (round%2==0) tt = t+time; else - tt = ((t-1)/(2*change)+1)*(2*change) + time; + tt = (round+1)*change + time; for (int nxt: next[cur]) { - if (arrival2[nxt]!=-1) continue; - pq.push({tt, nxt}); + if (visited[nxt]<2 && dist[nxt] < tt) + { + dist[nxt] = tt; + visited[nxt]+=1; + q.push({nxt, tt}); + + if (visited[nxt]==2 && nxt==n) + return tt; + } } } - return -1; } }; From 825a18c8a10d69924a018d09b013f0d1f491f1b2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Oct 2021 01:35:12 -0700 Subject: [PATCH 0094/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 08b136128..1a2d60ae7 100644 --- a/Readme.md +++ b/Readme.md @@ -446,6 +446,7 @@ [1617.Count-Subtrees-With-Max-Distance-Between-Cities](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1617.Count-Subtrees-With-Max-Distance-Between-Cities) (H-) [1654.Minimum-Jumps-to-Reach-Home](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1654.Minimum-Jumps-to-Reach-Home) (H-) [1905.Count-Sub-Islands](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1905.Count-Sub-Islands) (M+) +[2045.Second-Minimum-Time-to-Reach-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2045.Second-Minimum-Time-to-Reach-Destination) (M+) * ``Multi State`` [913.Cat-and-Mouse](https://github.com/wisdompeak/LeetCode/tree/master/BFS/913.Cat-and-Mouse) (H+) [1728.Cat-and-Mouse-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1728.Cat-and-Mouse-II) (H+) @@ -477,7 +478,6 @@ [1786.Number-of-Restricted-Paths-From-First-to-Last-Node](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1786.Number-of-Restricted-Paths-From-First-to-Last-Node) (H-) [1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (H-) -[2045.Second-Minimum-Time-to-Reach-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2045.Second-Minimum-Time-to-Reach-Destination) (M+) #### [Trie](https://github.com/wisdompeak/LeetCode/tree/master/Trie) [208.Implement-Trie--Prefix-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Trie/208.Implement-Trie--Prefix-Tree) (M+) From 04784d6c0691e566ccc8f165a36b5fed353fe8f5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Oct 2021 01:52:12 -0700 Subject: [PATCH 0095/2729] Update Readme.md --- Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index 1a2d60ae7..60694ce9c 100644 --- a/Readme.md +++ b/Readme.md @@ -431,13 +431,10 @@ [785.Is-Graph-Bipartite](https://github.com/wisdompeak/LeetCode/tree/master/BFS/785.Is-Graph-Bipartite) (M+) [815.Bus-Routes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/815.Bus-Routes) (M+) [838.Push-Dominoes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/838.Push-Dominoes) (M+) -[847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) -[864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) [928.Minimize-Malware-Spread-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/928.Minimize-Malware-Spread-II) (H-) [1036.Escape-a-Large-Maze](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1036.Escape-a-Large-Maze) (H) [1245.Tree-Diameter](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1245.Tree-Diameter) (H) [1263.Minimum-Moves-to-Move-a-Box-to-Their-Target-Location](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1263.Minimum-Moves-to-Move-a-Box-to-Their-Target-Location) (H) -[1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination) (H-) [1298.Maximum-Candies-You-Can-Get-from-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1298.Maximum-Candies-You-Can-Get-from-Boxes) (M+) [1311.Get-Watched-Videos-by-Your-Friends](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1311.Get-Watched-Videos-by-Your-Friends) (M) [1345.Jump-Game-IV](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1345.Jump-Game-IV) (M+) @@ -448,8 +445,11 @@ [1905.Count-Sub-Islands](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1905.Count-Sub-Islands) (M+) [2045.Second-Minimum-Time-to-Reach-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2045.Second-Minimum-Time-to-Reach-Destination) (M+) * ``Multi State`` +[847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) +[864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) [913.Cat-and-Mouse](https://github.com/wisdompeak/LeetCode/tree/master/BFS/913.Cat-and-Mouse) (H+) [1728.Cat-and-Mouse-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1728.Cat-and-Mouse-II) (H+) +[1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination) (H-) [1928.Minimum-Cost-to-Reach-Destination-in-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1928.Minimum-Cost-to-Reach-Destination-in-Time) (H-) * ``拓扑排序`` [207.Course-Schedule](https://github.com/wisdompeak/LeetCode/tree/master/BFS/207.Course-Schedule) (H-) From 72b6cd58320d7524f7a89a0ba54003e6315de626 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Oct 2021 02:13:59 -0700 Subject: [PATCH 0096/2729] Update Readme.md --- .../Readme.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md index 3a6080d50..50f40e69f 100644 --- a/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md +++ b/BFS/2045.Second-Minimum-Time-to-Reach-Destination/Readme.md @@ -1,5 +1,9 @@ ### 2045.Second-Minimum-Time-to-Reach-Destination -Dijkstra算用可以用来求最短路径,自然也可以用来求第二短路径。我们只要在算法中略作改动:第一次从pq里弹出某节点node时对应的路径是最短路径arrival1[node],此时我们一切照旧进行BFS;直到该节点被第二次从pq里弹出并且能更新为arrival2[node]之后,我们才禁止在pq里再加入node。 +这道题很多人看到最短路径就下意识地用Dijkstra算法。事实上这是不必要的,否则还会造成TLE。 -另外根据题意,假设当前cur被到达的时刻是t,那么有两种可能:t落在了绿灯时段,那么我们就可以在t+time时候到达nxt。如果t落在了红灯时段,那么我们必须在下一个绿灯时段开始后time再到达nxt。判断是否落在绿灯时段,就看t/change是否是偶数。判断何时是下一个绿灯时段的开始,我们就以```2*change```为一个周期,计算t落在了哪个周期```k=(t-1)/(2*change)+1```,那么```k*2*change```就是该周期结束、新周期开始的时刻。 +很多最短路径问题需要使用Dijkstra算法的原因,在于各个边的权重并不一致。传统的BFS算法里,弹出队首元素cur -> 扩展至若干相邻元素```nxt = cur + edge(cur->nxt)``` -> 将nxt放入队尾,这个流程会因为edge长度的不同,造成队列里面的节点所对应的路径并不保证递增。因此当我们从队列里第一次弹出终点时,并不能保证就是最短距离。于是Dijkstra就利用了贪心的思想,实时把当前最优(某个节点)的解弹出,直到我们遇到终点。 + +在本题中,虽然有了红绿灯的干扰,但是我们仔细想一想,无论什么情况下,后加入的节点时间一定会比先加入的节点时间晚。不可能出现这种情况:A先弹出可到达C,B后弹出可到达D,结果D比C的到达时间反而早。这是因为即使A被红灯耽搁了出发,那么B必然不会赶在那个红灯前出发。无论如何D不会早C。 + +基于以上分析,传统的BFS就可以解这道题了。本题tricky的地方在于求到达终点的第二最短路径(时间)。传统的BFS求最短路径,每个节点我们只需要访问一次,任何路径如果访问了二次相同的节点必然不会是最短距离。但本题中,我们BFS需要遍历每个节点两次,即得到它的最早到达和次早到达时间。但也仅此而已。因为在从起点到终点的第二最短路径所经过的所有节点里,肯定不会有某个节点被走了3次或以上。这个可以反证。假设从起点到终点的第二最短路径经过了```A->...->B1->...->B2->...->B3->...->C```,那么我们只要把多绕的圈子去掉,必然有两条更短的路径```A->...->B1->...->B2->...-->C```和```A->...->B1->...->C```。 From 2c6b41f3a609a17916336158f4adb5b43c814e49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Oct 2021 00:38:44 -0700 Subject: [PATCH 0097/2729] Create 2015.Average-Height-of-Buildings-in-Each-Segment.cpp --- ...ge-Height-of-Buildings-in-Each-Segment.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp diff --git a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp new file mode 100644 index 000000000..28700cdd3 --- /dev/null +++ b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + vector> averageHeightOfBuildings(vector>& buildings) + { + vector>p; + for (auto build: buildings) + { + int start = build[0], end = build[1], height = build[2]; + p.push_back({start, height}); + p.push_back({end, -height}); + } + + sort(p.begin(), p.end()); + int count = 0; + int sum = 0; + + vector>temp; + for (int i=0; i>rets; + for (int i=0; i Date: Sat, 23 Oct 2021 00:39:14 -0700 Subject: [PATCH 0098/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 60694ce9c..08dd1fb0d 100644 --- a/Readme.md +++ b/Readme.md @@ -1115,6 +1115,7 @@ 1893.Check if All the Integers in a Range Are Covered (E) [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [1943.Describe-the-Painting](https://github.com/wisdompeak/LeetCode/tree/master/Others/1943.Describe-the-Painting) (H-) +[2015.Average-Height-of-Buildings-in-Each-Segment](https://github.com/wisdompeak/LeetCode/tree/master/Others/2015.Average-Height-of-Buildings-in-Each-Segment) (H-) * ``Enumeration`` [479.Largest-Palindrome-Product](https://github.com/wisdompeak/LeetCode/tree/master/Others/479.Largest-Palindrome-Product) (M+) [866.Prime-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Others/866.Prime-Palindrome) (H-) From 7a22ee7f773b5d802dd9f4d221c3edb73fcad21c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Oct 2021 00:45:36 -0700 Subject: [PATCH 0099/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md diff --git a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md new file mode 100644 index 000000000..6b4dcfa68 --- /dev/null +++ b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md @@ -0,0 +1,9 @@ +### 2015.Average-Height-of-Buildings-in-Each-Segment + +对于给出若干个区间、涉及到区间合并的问题,扫描线是比较自然的想法。 + +我们只关注那些建筑两边的边缘线位置。将所有的边缘线按照位置从小到大排序之后,我们逐个遍历一遍。维护一个集合,遇到左边缘就插入h,遇到右边缘就删除h。于是,我们在每一个边缘线位置pos,都可以通过这个集合得到一个平均值avg,这意味着从pos往右直至下一个边缘线位置pos2,中间这部分区间[pos, pos2]就是一个输出为avg的线段。 + +我们将这些琐碎的线段收集起来,合并输出相同的线段,并且剔除输出为0的线段,这剩余的这些线段就是答案。 + +另外,事实上我们不需要真正维护一个multiset。我们只关心集合的sum和count,因此用两个变量即可。 From 9ba34b32c75bb208f2ca13470da86d82b1d02da4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Oct 2021 00:46:16 -0700 Subject: [PATCH 0100/2729] Update Readme.md --- .../2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md index 6b4dcfa68..7bd96cafc 100644 --- a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md +++ b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md @@ -2,7 +2,7 @@ 对于给出若干个区间、涉及到区间合并的问题,扫描线是比较自然的想法。 -我们只关注那些建筑两边的边缘线位置。将所有的边缘线按照位置从小到大排序之后,我们逐个遍历一遍。维护一个集合,遇到左边缘就插入h,遇到右边缘就删除h。于是,我们在每一个边缘线位置pos,都可以通过这个集合得到一个平均值avg,这意味着从pos往右直至下一个边缘线位置pos2,中间这部分区间[pos, pos2]就是一个输出为avg的线段。 +我们只关注那些建筑两边的边缘线位置。将所有的边缘线按照位置从小到大排序之后,我们逐个遍历一遍。维护一个集合,遇到左边缘就插入h,遇到右边缘就删除h。于是,我们在每一个边缘线位置pos,都可以通过当前集合得到一个平均值avg,这意味着从pos往右直至下一个边缘线位置pos2,中间这部分区间[pos, pos2]就是一个输出恒为avg的线段。 我们将这些琐碎的线段收集起来,合并输出相同的线段,并且剔除输出为0的线段,这剩余的这些线段就是答案。 From 3e8921d7ea9a1a2d99266c4b26c5b48ba3f5c0cb Mon Sep 17 00:00:00 2001 From: refinedcoding <63949022+refinedcoding@users.noreply.github.com> Date: Sat, 23 Oct 2021 11:39:49 -0700 Subject: [PATCH 0101/2729] Update 373.Find-K-Pairs-with-Smallest-Sums_v2.cpp --- ...373.Find-K-Pairs-with-Smallest-Sums_v2.cpp | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp index bc577cb5c..380ab2781 100644 --- a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp +++ b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums_v2.cpp @@ -14,25 +14,28 @@ class Solution { } int m = left; - vector>rets1; - vector>rets2; + // TODO-TLE: nums1 = [1] * 100000, nums2 = [1] * 100000, k = 2 + vector>rets; for (int i=0; i 148ms/43.01% + for (int i=0; i& nums1, vector& nums2) From 2a82716329e3a38456f33e63473a09c6e05312a8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 00:29:29 -0700 Subject: [PATCH 0102/2729] Create 638.Shopping-Offers_v3.cpp --- .../638.Shopping-Offers_v3.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 DFS/638.Shopping-Offers/638.Shopping-Offers_v3.cpp diff --git a/DFS/638.Shopping-Offers/638.Shopping-Offers_v3.cpp b/DFS/638.Shopping-Offers/638.Shopping-Offers_v3.cpp new file mode 100644 index 000000000..faaa970ef --- /dev/null +++ b/DFS/638.Shopping-Offers/638.Shopping-Offers_v3.cpp @@ -0,0 +1,55 @@ +class Solution { + int memo[1<<24]; + int N; +public: + int shoppingOffers(vector& price, vector>& special, vector& needs) + { + N=price.size(); + vector>specials; + for (int i=0; ispecial[i].back()) + specials.push_back(special[i]); + } + + int state = 0; + for (int i=0; i& price, vector>& specials) + { + if (memo[state]!=0) return memo[state]; + + int ret = 0; + for (int i=0; i>(i*4))%16 * price[i]; + + for (auto comb: specials) + { + int flag = 1; + for (int i=0; i>(i*4))%16 < comb[i]) + { + flag = 0; + break; + } + } + if (flag==0) continue; + + int state2 = state; + for (int i=0; i Date: Sun, 24 Oct 2021 00:30:56 -0700 Subject: [PATCH 0103/2729] Update Readme.md --- DFS/638.Shopping-Offers/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DFS/638.Shopping-Offers/Readme.md b/DFS/638.Shopping-Offers/Readme.md index b37f43899..49eec9589 100644 --- a/DFS/638.Shopping-Offers/Readme.md +++ b/DFS/638.Shopping-Offers/Readme.md @@ -10,5 +10,7 @@ 1. 有些offer是不合算的,可以提前从special里排除掉; 2. 在dfs(state)里,除了尝试offer,还可以直接从prices里面按原价采购每一件物品。 +PS: 最新的题目里把每种物品的数量放宽到了10件,所以需要```4*6=24```个bit的二进制数来表示状态。 + [Leetcode Link](https://leetcode.com/problems/shopping-offers) From a90a3e2396be15e588b0cf4ff1f19dda61a073d8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 11:25:39 -0700 Subject: [PATCH 0104/2729] Update 687.Longest-Univalue-Path.cpp --- .../687.Longest-Univalue-Path.cpp | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Tree/687.Longest-Univalue-Path/687.Longest-Univalue-Path.cpp b/Tree/687.Longest-Univalue-Path/687.Longest-Univalue-Path.cpp index 5b025c50d..0880f0b52 100644 --- a/Tree/687.Longest-Univalue-Path/687.Longest-Univalue-Path.cpp +++ b/Tree/687.Longest-Univalue-Path/687.Longest-Univalue-Path.cpp @@ -4,31 +4,31 @@ * int val; * TreeNode *left; * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * 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 { - int result=0; + int ret = 0; public: int longestUnivaluePath(TreeNode* root) { - int temp = DFS(root); - return max(0,result-1); + dfs(root); + return max(0, ret-1); } - - int DFS(TreeNode* root) + int dfs(TreeNode* node) { - if (root==NULL) return 0; - int L = DFS(root->left); - int R = DFS(root->right); - - int LL=0; - int RR=0; - if (root->left!=NULL && root->left->val==root->val) - LL = L; - if (root->right!=NULL && root->right->val==root->val) - RR = R; - result = max(result, LL+RR+1); - return max(LL+1,RR+1); + if (node==NULL) return 0; + int len1 = dfs(node->left); + int len2 = dfs(node->right); + + int L = 0, R = 0; + if (node->left && node->left->val == node->val) + L = len1; + if (node->right && node->right->val == node->val) + R = len2; + ret = max(ret, L+1+R); + return 1+max(L,R); } }; From 4c57cd0df8d18e2b2d7057191a02c9ef086731c5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 12:20:30 -0700 Subject: [PATCH 0105/2729] Create 2049.Count-Nodes-With-the-Highest-Score.cpp --- ...049.Count-Nodes-With-the-Highest-Score.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Tree/2049.Count-Nodes-With-the-Highest-Score/2049.Count-Nodes-With-the-Highest-Score.cpp diff --git a/Tree/2049.Count-Nodes-With-the-Highest-Score/2049.Count-Nodes-With-the-Highest-Score.cpp b/Tree/2049.Count-Nodes-With-the-Highest-Score/2049.Count-Nodes-With-the-Highest-Score.cpp new file mode 100644 index 000000000..0d6a59ba2 --- /dev/null +++ b/Tree/2049.Count-Nodes-With-the-Highest-Score/2049.Count-Nodes-With-the-Highest-Score.cpp @@ -0,0 +1,50 @@ +using LL = long long; +class Solution { + unordered_mapMap; + vector>children; +public: + int countHighestScoreNodes(vector& parents) + { + int n = parents.size(); + children.resize(n); + for (int i=1; i maxVal) + { + maxVal = x.first; + num = x.second; + } + } + + return num; + } + + int dfs(int node) + { + int n = children.size(); + vectorsub; + int sub_total = 0; + for (auto child: children[node]) + { + sub.push_back(dfs(child)); + sub_total += sub.back(); + } + int U = n - (sub_total+1); + LL ret = 1; + if (U!=0) ret *= U; + for (auto x: sub) + if (x!=0) ret *= x; + Map[ret]++; + + return sub_total+1; + } +}; From c8f8ca358ab536109be4b47dd020afa3ed29e18e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 12:21:52 -0700 Subject: [PATCH 0106/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 08dd1fb0d..057a3b9b4 100644 --- a/Readme.md +++ b/Readme.md @@ -195,7 +195,9 @@ [450.Delete-Node-in-a-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/450.Delete-Node-in-a-BST) (H) [437.Path-Sum-III](https://github.com/wisdompeak/LeetCode/tree/master/Tree/437.Path-Sum-III) (H-) [333.Largest-BST-Subtree](https://github.com/wisdompeak/LeetCode/blob/master/Tree/333.Largest-BST-Subtree) (H) -[543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M+) +[543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) +[687.Longest-Univalue-Path](https://github.com/wisdompeak/LeetCode/tree/master/Tree/687.Longest-Univalue-Path) (M+) +[2049.Count-Nodes-With-the-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2049.Count-Nodes-With-the-Highest-Score) (M+) [572.Subtree-of-Another-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/572.Subtree-of-Another-Tree) (M) [549.Binary-Tree-Longest-Consecutive-Sequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/549.Binary-Tree-Longest-Consecutive-Sequence-II) (M) [173.Binary-Search-Tree-Iterator](https://github.com/wisdompeak/LeetCode/tree/master/Stack/173.Binary-Search-Tree-Iterator) (M) @@ -208,7 +210,6 @@ 501.Find-Mode-in-Binary-Search-Tree (M+) 558.Quad-Tree-Intersection (M+) [662.Maximum-Width-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/662.Maximum-Width-of-Binary-Tree) (H-) -[687.Longest-Univalue-Path](https://github.com/wisdompeak/LeetCode/tree/master/Tree/687.Longest-Univalue-Path) (M+) 742.Closest-Leaf-in-a-Binary-Tree (H) 834.Sum-of-Distances-in-Tree (H) [863.All-Nodes-Distance-K-in-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/863.All-Nodes-Distance-K-in-Binary-Tree) (H-) From d5f742d58919818a44ed81af787f0c12975679ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 19:46:18 -0700 Subject: [PATCH 0107/2729] Update and rename 543.Diameter of Binary Tree.cpp to 543.Diameter-of-Binary-Tree.cpp --- .../543.Diameter of Binary Tree.cpp | 29 ------------------ .../543.Diameter-of-Binary-Tree.cpp | 30 +++++++++++++++++++ 2 files changed, 30 insertions(+), 29 deletions(-) delete mode 100644 Tree/543.Diameter-of-Binary-Tree/543.Diameter of Binary Tree.cpp create mode 100644 Tree/543.Diameter-of-Binary-Tree/543.Diameter-of-Binary-Tree.cpp diff --git a/Tree/543.Diameter-of-Binary-Tree/543.Diameter of Binary Tree.cpp b/Tree/543.Diameter-of-Binary-Tree/543.Diameter of Binary Tree.cpp deleted file mode 100644 index 506f279d2..000000000 --- a/Tree/543.Diameter-of-Binary-Tree/543.Diameter of Binary Tree.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int result; -public: - int diameterOfBinaryTree(TreeNode* root) - { - if (root==NULL) return 0; - int temp = LongestPathToLeaf(root); - return result-1; - } - - int LongestPathToLeaf(TreeNode* root) - { - if (root==NULL) return 0; - - int left = LongestPathToLeaf(root->left); - int right = LongestPathToLeaf(root->right); - result = max(result,left+right+1); - return max(left,right)+1; - } -}; diff --git a/Tree/543.Diameter-of-Binary-Tree/543.Diameter-of-Binary-Tree.cpp b/Tree/543.Diameter-of-Binary-Tree/543.Diameter-of-Binary-Tree.cpp new file mode 100644 index 000000000..8e714fad2 --- /dev/null +++ b/Tree/543.Diameter-of-Binary-Tree/543.Diameter-of-Binary-Tree.cpp @@ -0,0 +1,30 @@ +/** + * 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 { + int ret = 0; +public: + int diameterOfBinaryTree(TreeNode* root) + { + LongestPathToLeaf(root); + return ret-1; + } + + int LongestPathToLeaf(TreeNode* node) + { + if (node == NULL) return 0; + + int leftPath = LongestPathToLeaf(node->left); + int rightPath = LongestPathToLeaf(node->right); + ret = max(ret, leftPath+1+rightPath); + return max(leftPath, rightPath) + 1; + } +}; From f1313d4182aada997059f5ccf32e9f452f988e40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 20:01:00 -0700 Subject: [PATCH 0108/2729] Update Readme.md --- Tree/687.Longest-Univalue-Path/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tree/687.Longest-Univalue-Path/Readme.md b/Tree/687.Longest-Univalue-Path/Readme.md index 571f33b6e..2124a83bc 100644 --- a/Tree/687.Longest-Univalue-Path/Readme.md +++ b/Tree/687.Longest-Univalue-Path/Readme.md @@ -1,6 +1,6 @@ ### 687.Longest-Univalue-Path -设计DFS(node)函数,返回的是以node为起点,朝某个单向下行最长的Univalue path +此题和```543. Diameter of Binary Tree```很相似。设计DFS(node)函数,返回的是以node为起点,朝某个单向下行最长的Univalue path 每一次调用DFS(node),都要先调用L=DFS(node->left)和R=DFS(node->right),将左右节点都递归遍历完毕。 @@ -9,4 +9,4 @@ 那么考虑DFS(node)自己的返回值是什么呢?显然是1,或L+1(如果根与左节点相同),或R+1(如果根与右节点相同) -[Leetcode Link](https://leetcode.com/problems/longest-univalue-path) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/longest-univalue-path) From 86451c7ce33732ac956c88389a52d1b5c4e84a82 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 20:23:40 -0700 Subject: [PATCH 0109/2729] Create Readme.md --- Tree/2049.Count-Nodes-With-the-Highest-Score/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Tree/2049.Count-Nodes-With-the-Highest-Score/Readme.md diff --git a/Tree/2049.Count-Nodes-With-the-Highest-Score/Readme.md b/Tree/2049.Count-Nodes-With-the-Highest-Score/Readme.md new file mode 100644 index 000000000..71ecfbf6e --- /dev/null +++ b/Tree/2049.Count-Nodes-With-the-Highest-Score/Readme.md @@ -0,0 +1,3 @@ +### 2049.Count-Nodes-With-the-Highest-Score + +本题本质只要设计一个递归函数dfs(node)来计算以node为跟的子树包含的元素个数即可。这样的话,如果删除掉node节点本身,那么剩下的三部分就是```dfs(node->left), dfs(node->right), n - 1 - dfs(node->left) - dfs(node->right)```. 只要把这三部分的非零元素相乘,就是一个score。所以在dfs(node)的同时,就可以把对应的score算出来。而实现整棵树的dfs,只要o(n)时间,均摊起来每个节点只需要o(1)。 From ad72f75b4d183dabdd6d5a2d6c6d9117f582c5dd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 22:55:15 -0700 Subject: [PATCH 0110/2729] Create 2050.Parallel-Courses-III.cpp --- .../2050.Parallel-Courses-III.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 BFS/2050.Parallel-Courses-III/2050.Parallel-Courses-III.cpp diff --git a/BFS/2050.Parallel-Courses-III/2050.Parallel-Courses-III.cpp b/BFS/2050.Parallel-Courses-III/2050.Parallel-Courses-III.cpp new file mode 100644 index 000000000..e5a531cc8 --- /dev/null +++ b/BFS/2050.Parallel-Courses-III/2050.Parallel-Courses-III.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int minimumTime(int n, vector>& relations, vector& time) + { + vector>next(n+1); + vectorindegree(n+1); + for (auto relation: relations) + { + int a = relation[0], b = relation[1]; + next[a].push_back(b); + indegree[b]++; + } + queueq; + vectort(n+1); + for (int i=1; i<=n; i++) + if (indegree[i]==0) + { + q.push(i); + t[i] = time[i-1]; + } + + int ret = 0; + while (!q.empty()) + { + int cur = q.front(); + q.pop(); + ret = max(ret, t[cur]); + for (int nxt: next[cur]) + { + t[nxt] = max(t[nxt], t[cur]+time[nxt-1]); + indegree[nxt]--; + if (indegree[nxt]==0) + q.push(nxt); + } + } + + return ret; + } +}; From bd656d4ee9f8e5767aaa80b02d3108cd62072906 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 22:55:43 -0700 Subject: [PATCH 0111/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 057a3b9b4..f0544b979 100644 --- a/Readme.md +++ b/Readme.md @@ -464,6 +464,7 @@ [1462.Course-Schedule-IV](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1462.Course-Schedule-IV) (M) [1591.Strange-Printer-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1591.Strange-Printer-II) (H-) [1857.Largest-Color-Value-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1857.Largest-Color-Value-in-a-Directed-Graph) (H-) +[2050.Parallel-Courses-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2050.Parallel-Courses-III) (M+) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From 35fd5335fd5c10f25b17581276ef3ba2b0f3b270 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Oct 2021 23:42:06 -0700 Subject: [PATCH 0112/2729] Create Readme.md --- BFS/2050.Parallel-Courses-III/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 BFS/2050.Parallel-Courses-III/Readme.md diff --git a/BFS/2050.Parallel-Courses-III/Readme.md b/BFS/2050.Parallel-Courses-III/Readme.md new file mode 100644 index 000000000..fa0326ed7 --- /dev/null +++ b/BFS/2050.Parallel-Courses-III/Readme.md @@ -0,0 +1,9 @@ +### 2050.Parallel-Courses-III + +本题本质是求有向无环图里的最长路径。图论里有各种基于松弛的算法,但是本题最容易理解的其实就是拓扑排序。 + +对于任何一门课程a,它的最早完成时间t(a)取决于它的所有先修课程的完成时间里最长的那个,即```t(a) = max{t(bi)+time[a]}```,其中bi是a的先修课程。因为本题给出的是有向无环图,所以不会有循坏依赖,即t(bi)不会依赖于t(a)本身。那么我们什么时候知道可以t(a)更新完毕了呢?很简单,只要每确定了一个t(bi),我们就把a的入度减一。当发现a的入度为0时,说明t(a)已经被更新完毕。 + +实现拓扑排序一般会用BFS。队列初始时刻加入那些入度为0的课程。每次弹出一门课程,它的所以后续课程就有机会更新一次。发现某个后续课程的入度减至了零,说明它的所有先修课程已经都确定了,那么这么后续课程也就确定了,就可以加入队列。 + +本题输出的结果是所有课程的完成时刻里的最大值。 From d408fdfcc87ef980ca2c2ec87048ef7966582bd7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Oct 2021 12:00:12 -0700 Subject: [PATCH 0113/2729] Update Readme.md --- Readme.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index f0544b979..d8a331748 100644 --- a/Readme.md +++ b/Readme.md @@ -183,7 +183,6 @@ [095.Unique-Binary-Search-Trees-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/095.Unique-Binary-Search-Trees-II) (H) [094.Binary Tree Inorder Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/094.Binary-Tree-Inorder-Traversal) (H-) [110.Balanced-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/110.Balanced-Binary-Tree) (M+) -[124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M+) [222.Count-Complete-Tree-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/222.Count-Complete-Tree-Nodes) (M+) [099.Recover-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/099.Recover-Binary-Search-Tree) (H) [114.Flatten-Binary-Tree-to-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Tree/114.Flatten-Binary-Tree-to-Linked-List) (M+) @@ -195,9 +194,6 @@ [450.Delete-Node-in-a-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/450.Delete-Node-in-a-BST) (H) [437.Path-Sum-III](https://github.com/wisdompeak/LeetCode/tree/master/Tree/437.Path-Sum-III) (H-) [333.Largest-BST-Subtree](https://github.com/wisdompeak/LeetCode/blob/master/Tree/333.Largest-BST-Subtree) (H) -[543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) -[687.Longest-Univalue-Path](https://github.com/wisdompeak/LeetCode/tree/master/Tree/687.Longest-Univalue-Path) (M+) -[2049.Count-Nodes-With-the-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2049.Count-Nodes-With-the-Highest-Score) (M+) [572.Subtree-of-Another-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/572.Subtree-of-Another-Tree) (M) [549.Binary-Tree-Longest-Consecutive-Sequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/549.Binary-Tree-Longest-Consecutive-Sequence-II) (M) [173.Binary-Search-Tree-Iterator](https://github.com/wisdompeak/LeetCode/tree/master/Stack/173.Binary-Search-Tree-Iterator) (M) @@ -220,6 +216,11 @@ [1666.Change-the-Root-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1666.Change-the-Root-of-a-Binary-Tree) (H-) [1932.Merge-BSTs-to-Create-Single-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1932.Merge-BSTs-to-Create-Single-BST) (H) [2003.Smallest-Missing-Genetic-Value-in-Each-Subtree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2003.Smallest-Missing-Genetic-Value-in-Each-Subtree) (H) +* ``Path in a tree`` +[543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) +[124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) +[687.Longest-Univalue-Path](https://github.com/wisdompeak/LeetCode/tree/master/Tree/687.Longest-Univalue-Path) (M+) +[2049.Count-Nodes-With-the-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2049.Count-Nodes-With-the-Highest-Score) (M+) * ``Serialization & Hashing`` [297.Serialize-and-Deserialize-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/297.Serialize-and-Deserialize-Binary-Tree) (H-) [652.Find-Duplicate-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/652.Find-Duplicate-Subtrees) (H) From 7a8f6582f1c3ed4e53abe48a079460301370b9c8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Oct 2021 12:01:02 -0700 Subject: [PATCH 0114/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d8a331748..3028c0eef 100644 --- a/Readme.md +++ b/Readme.md @@ -216,7 +216,7 @@ [1666.Change-the-Root-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1666.Change-the-Root-of-a-Binary-Tree) (H-) [1932.Merge-BSTs-to-Create-Single-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1932.Merge-BSTs-to-Create-Single-BST) (H) [2003.Smallest-Missing-Genetic-Value-in-Each-Subtree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2003.Smallest-Missing-Genetic-Value-in-Each-Subtree) (H) -* ``Path in a tree`` +* ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) [687.Longest-Univalue-Path](https://github.com/wisdompeak/LeetCode/tree/master/Tree/687.Longest-Univalue-Path) (M+) From c46de0fb8c3291b47286c38b758428cabe25e962 Mon Sep 17 00:00:00 2001 From: refinedcoding <63949022+refinedcoding@users.noreply.github.com> Date: Tue, 26 Oct 2021 08:39:00 -0700 Subject: [PATCH 0115/2729] Update 668.Kth-Smallest-Number-in-Multiplication-Table.cpp --- .../668.Kth-Smallest-Number-in-Multiplication-Table.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table/668.Kth-Smallest-Number-in-Multiplication-Table.cpp b/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table/668.Kth-Smallest-Number-in-Multiplication-Table.cpp index 07ac794dc..2a5e49c90 100644 --- a/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table/668.Kth-Smallest-Number-in-Multiplication-Table.cpp +++ b/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table/668.Kth-Smallest-Number-in-Multiplication-Table.cpp @@ -4,11 +4,13 @@ class Solution { { int left=1; int right=m*n; - int mid; + if (m > n) { + m ^= n ^ (n = m); + } while (left Date: Tue, 26 Oct 2021 21:54:04 -0700 Subject: [PATCH 0116/2729] Rename 222.Count-Complete-Tree-Nodes_v2.cpp to 222.Count-Complete-Tree-Nodes_v0.cpp --- ...ete-Tree-Nodes_v2.cpp => 222.Count-Complete-Tree-Nodes_v0.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/222.Count-Complete-Tree-Nodes/{222.Count-Complete-Tree-Nodes_v2.cpp => 222.Count-Complete-Tree-Nodes_v0.cpp} (100%) diff --git a/Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v2.cpp b/Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v0.cpp similarity index 100% rename from Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v2.cpp rename to Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v0.cpp From bc5375416f19a8d5ef03613f15be3f61b8a21bcc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Oct 2021 21:54:17 -0700 Subject: [PATCH 0117/2729] Rename 222.Count-Complete-Tree-Nodes_v1.cpp to 222.Count-Complete-Tree-Nodes_v2.cpp --- ...ete-Tree-Nodes_v1.cpp => 222.Count-Complete-Tree-Nodes_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/222.Count-Complete-Tree-Nodes/{222.Count-Complete-Tree-Nodes_v1.cpp => 222.Count-Complete-Tree-Nodes_v2.cpp} (100%) diff --git a/Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v1.cpp b/Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v2.cpp similarity index 100% rename from Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v1.cpp rename to Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v2.cpp From 6ca7dc023ca0b58916fb29342555f364f3f233af Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Oct 2021 21:54:28 -0700 Subject: [PATCH 0118/2729] Rename 222.Count-Complete-Tree-Nodes_v0.cpp to 222.Count-Complete-Tree-Nodes_v1.cpp --- ...ete-Tree-Nodes_v0.cpp => 222.Count-Complete-Tree-Nodes_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/222.Count-Complete-Tree-Nodes/{222.Count-Complete-Tree-Nodes_v0.cpp => 222.Count-Complete-Tree-Nodes_v1.cpp} (100%) diff --git a/Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v0.cpp b/Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v1.cpp similarity index 100% rename from Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v0.cpp rename to Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v1.cpp From d3e3cf59c2923ec9a8a1d2cf27dd93fea293d827 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Oct 2021 21:58:53 -0700 Subject: [PATCH 0119/2729] Update Readme.md --- Tree/222.Count-Complete-Tree-Nodes/Readme.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Tree/222.Count-Complete-Tree-Nodes/Readme.md b/Tree/222.Count-Complete-Tree-Nodes/Readme.md index cf2e28e23..28d2a12c8 100644 --- a/Tree/222.Count-Complete-Tree-Nodes/Readme.md +++ b/Tree/222.Count-Complete-Tree-Nodes/Readme.md @@ -8,11 +8,12 @@ #### 解法2: 需要观察得到如下的重要性质:对于一个完全二叉树,root的左子树和右子树里面,必然有一个是满二叉树。 -对于高度为h的满二叉树,其节点个数可以直接计算为2^h-1。所以我们对于root,先判断左右哪一个是满二叉树,然后再递归处理另外一部分就行了。比如 ```f(root) = 1 + pow(2,h)-1 + f(root->left)```,其中h是右子树这棵满二叉树的高度。 - -如何判断是否一棵满二叉树呢?只要递归计算它的左深度和有深度,查看两者是否相等就行了。 +对于高度为h的满二叉树,其节点个数可以直接计算为2^h-1。所以我们对于root,先判断左子树是否是一个满二叉树。如果不是的话,递归处理左子树,否则就递归处理右子树。如何判断一棵树是否为满二叉树呢?只要递归计算它的左深度和有深度,查看两者是否相等就行了。 这个总算法复杂度是logN\*logN。可以这么考虑:每次计算满二叉树的高度需要o(logN),不停二分递归处理非满二叉树又需要o(logN)次。 +#### 解法3: +对于每一棵子树,只要考察它左子树的“左深度”h1、右子树的“左深度”h2.如果二者相等,那么递归处理右子树,即```count(node) = 2^h1-1+1+count(node->right)```,否则就递归处理左子树```count(node) = 2^h2-1+1+count(node->left)``` + -[Leetcode Link](https://leetcode.com/problems/count-complete-tree-nodes) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/count-complete-tree-nodes) From 1143325f45dd0b3e6b8d9f01bc2a9b1ed4be677a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 15:42:33 -0700 Subject: [PATCH 0120/2729] Create 2056.Number-of-Valid-Move-Combinations-On-Chessboard.cpp --- ...-Valid-Move-Combinations-On-Chessboard.cpp | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard/2056.Number-of-Valid-Move-Combinations-On-Chessboard.cpp diff --git a/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard/2056.Number-of-Valid-Move-Combinations-On-Chessboard.cpp b/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard/2056.Number-of-Valid-Move-Combinations-On-Chessboard.cpp new file mode 100644 index 000000000..05c75772e --- /dev/null +++ b/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard/2056.Number-of-Valid-Move-Combinations-On-Chessboard.cpp @@ -0,0 +1,74 @@ +class Solution { + vector>dir{{-1,0},{1,0},{0,-1},{0,1},{1,1},{1,-1},{-1,1},{-1,-1}}; + int n; + unordered_setrets; +public: + int countCombinations(vector& pieces, vector>& positions) + { + this->n = pieces.size(); + + for (int state= 0 ; state<(1<<(3*n)); state++) + { + int flag =1; + vectordirs(n); + for (int k=0; k>(3*k))%8; + if (pieces[k]=="rook" && d>3) {flag=0; break;} + if (pieces[k]=="bishop" && d<4) {flag=0; break;} + dirs[k] = d; + } + if (flag) + dfs(positions, dirs, (1<>& positions, vector& dirs, int state) + { + for (int subset=state; subset>0; subset=(subset-1)&state) + { + vector>pos2 = positions; + int flag = 1; + for (int i=0; i>i)&1) + { + pos2[i][0] += dir[dirs[i]].first; + pos2[i][1] += dir[dirs[i]].second; + if (pos2[i][0]<1 || pos2[i][0]>8) {flag = 0; break;} + if (pos2[i][1]<1 || pos2[i][1]>8) {flag = 0; break;} + } + } + if (flag==0) continue; + if (duplicate(pos2)) continue; + + long long hash = getHash(pos2); + if (rets.find(hash)!=rets.end()) + continue; + rets.insert(hash); + dfs(pos2, dirs, subset); + } + } + + bool duplicate(vector>&pos) + { + for (int i=0; i>&pos) + { + long long ret = 0; + for (int k=0; k Date: Sun, 31 Oct 2021 15:43:05 -0700 Subject: [PATCH 0121/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3028c0eef..e2d46b573 100644 --- a/Readme.md +++ b/Readme.md @@ -402,6 +402,7 @@ [1766.Tree-of-Coprimes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1766.Tree-of-Coprimes) (H-) [1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) [2014.Longest-Subsequence-Repeated-k-Times](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2014.Longest-Subsequence-Repeated-k-Times) (H) +[2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) * ``search in an array`` [090.Subsets-II](https://github.com/wisdompeak/LeetCode/tree/master/DFS/090.Subsets-II) (M+) [301.Remove-Invalid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/DFS/301.Remove-Invalid-Parentheses) (H) From d8ee01de9b2e2d37f1c806c1e3d10f10467c4635 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 16:16:17 -0700 Subject: [PATCH 0122/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard/Readme.md diff --git a/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard/Readme.md b/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard/Readme.md new file mode 100644 index 000000000..868564121 --- /dev/null +++ b/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard/Readme.md @@ -0,0 +1,15 @@ +### 2056.Number-of-Valid-Move-Combinations-On-Chessboard + +首先这道题的题意描述比较迷惑。本质上是,确定了每个棋子的移动方向之后,每一个回合,所有的棋子都必须朝各自约定的方向移动一步(除非它决定以后不再移动)。走多少个回合不限,但约束是所有的棋子不能碰撞或者出界。问盘面上有多少种棋子摆放的组合。 + +此时再看这道题,思路就会清晰很多。因为只有最多四个棋子,里面只有最多一个皇后,所以方向组合的可能性只有```4*4*4*8=512```种,似乎可以枚举考虑。 + +在固定了所有棋子的各自方向之后,我们就模拟他们共同前进的轨迹。在每一个回合,我们都需要考虑其中某些棋子停止前进的情况。很想然,停止前进(或者继续前进)的棋子必然是上一个回合前进的棋子的子集,所以这就是一个遍历子集的问题。具体的说,我们在刚出发的时候标注1111,表示所有棋子都可以前进。在第一个回合的时候,有些棋子可能就不走了(认为已经到了它的终点),能继续走的就有```2^4-1=15```种情况,即可以写成1111,1110,1101,1011,0111,1100,1001,0011... 有了这个状态变量,我们就可以在推进的时候,时刻知道哪些棋子可以继续走下去。比如说0110,那么我们就只对第2和第3个棋子在它们的方向上加1. 有了棋子们的新位置和新状态,就可以继续递归下去。 + +递归的终结就是:任意两个棋子相撞了,或者任意一个棋子出界了。 + +最终的答案是把盘面上所有出现的棋子位置组合都统计。这里需要特别注意,我们需要hash来去重。不是说每次走到一个新的棋子组合都是unique的。这是因为有一类特殊的情况。假设“A向上走0步,B向右走一步”,等同于“A向下走0步,B向右走一步”。这两种前进模式是出现在两个不同的方向组合里面的,我们在某个方向组合的DFS过程中无法避免,必须靠全局的去重。 + +因为棋子的数目比较少,盘面也不大,Hash的方法可以就是将所有棋子的坐标拼接起来。 + +另外一个优化的地方,Hash不仅可以去重,而且可以避免重复搜索。还是上面的例子,“A向上走0步,B向右走一步”及其后续都被探访过之后,那么“A向下走0步,B向右走一步”及其后续就是一模一样的路径了。这是因为在两种情况里,A都约定不再移动。 From 3142bc6a349a859b24e97d37ae85ffd4208da302 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 17:34:48 -0700 Subject: [PATCH 0123/2729] Create 2055.Plates-Between-Candles.cpp --- .../2055.Plates-Between-Candles.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Greedy/2055.Plates-Between-Candles/2055.Plates-Between-Candles.cpp diff --git a/Greedy/2055.Plates-Between-Candles/2055.Plates-Between-Candles.cpp b/Greedy/2055.Plates-Between-Candles/2055.Plates-Between-Candles.cpp new file mode 100644 index 000000000..362060176 --- /dev/null +++ b/Greedy/2055.Plates-Between-Candles/2055.Plates-Between-Candles.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + vector platesBetweenCandles(string s, vector>& queries) + { + int n = s.size(); + vectorpresum(n); + int count = 0; + for (int i=0; ilast(n); + int t = -1; + for (int i=0; inext(n); + t = n; + for (int i=n-1; i>=0; i--) + { + if (s[i]=='|') + t = i; + next[i] = t; + } + + vectorrets; + for (auto q: queries) + { + int a = q[0], b = q[1]; + int x = next[a], y = last[b]; + + if (x<=y && x>=a && y<=b) + rets.push_back(presum[y] - presum[x]); + else + rets.push_back(0); + } + + return rets; + } +}; From 6d70a82fd0d16220475885df0f56961d65898b1f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 17:35:15 -0700 Subject: [PATCH 0124/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e2d46b573..6748c0f34 100644 --- a/Readme.md +++ b/Readme.md @@ -1020,6 +1020,7 @@ [727.Minimum-Window-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/727.Minimum-Window-Subsequence) (H-) [792.Number-of-Matching-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/792.Number-of-Matching-Subsequences) (H-) [1055.Shortest-Way-to-Form-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1055.Shortest-Way-to-Form-String) (M+) +[2055.Plates-Between-Candles](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2055.Plates-Between-Candles) (M+) * ``Sort`` 164.Maximum-Gap (H) [179.Largest-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/179.Largest-Number) (H-) From da895f62c78e7effb339ad69eff6166b6cb431fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 17:49:20 -0700 Subject: [PATCH 0125/2729] Create Readme.md --- Greedy/2055.Plates-Between-Candles/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2055.Plates-Between-Candles/Readme.md diff --git a/Greedy/2055.Plates-Between-Candles/Readme.md b/Greedy/2055.Plates-Between-Candles/Readme.md new file mode 100644 index 000000000..d4426edda --- /dev/null +++ b/Greedy/2055.Plates-Between-Candles/Readme.md @@ -0,0 +1,5 @@ +### 2055.Plates-Between-Candles + +很显然,对于给定的区间[a,b]里,我希望知道a右边最近的蜡烛位置x,和b左边最近的蜡烛位置y。显然,我们可以用状态机的思想提前准备好next和last数组。next[i]表示i的下一个(可以是自身)出现蜡烛的位置;last[i]表示i的前一个(可以是自身)出现蜡烛的位置。这些都可以用o(n)实现。 + +知道了x和y,想求区间[x,y]内的盘子数量,显然用前缀和最方便。 From 8657c1f3e7922a71305f632f01beaee264b250bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 19:56:12 -0700 Subject: [PATCH 0126/2729] Create 2054.Two-Best-Non-Overlapping-Events.cpp --- .../2054.Two-Best-Non-Overlapping-Events.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/2054.Two-Best-Non-Overlapping-Events/2054.Two-Best-Non-Overlapping-Events.cpp diff --git a/Greedy/2054.Two-Best-Non-Overlapping-Events/2054.Two-Best-Non-Overlapping-Events.cpp b/Greedy/2054.Two-Best-Non-Overlapping-Events/2054.Two-Best-Non-Overlapping-Events.cpp new file mode 100644 index 000000000..3c55fc9d7 --- /dev/null +++ b/Greedy/2054.Two-Best-Non-Overlapping-Events/2054.Two-Best-Non-Overlapping-Events.cpp @@ -0,0 +1,37 @@ +class Solution { + static bool cmp(vector&a, vector&b) + { + return a[1] < b[1]; + } +public: + int maxTwoEvents(vector>& events) + { + int n = events.size(); + sort(events.begin(), events.end(), cmp); + + vector>dp; // {time, value} + dp.push_back({events[0][1], events[0][2]}); + int rollingMax = events[0][2]; + + int ret = events[0][2]; + + for (int i=1; isecond; + } + ret = max(ret, lastMax + v); + + rollingMax = max(rollingMax, v); + dp.push_back({b, rollingMax}); + } + + return ret; + } +}; From a9ea08235ce72c90e3463ec68de3f66d7cf86030 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 19:56:46 -0700 Subject: [PATCH 0127/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6748c0f34..a2f08d7f2 100644 --- a/Readme.md +++ b/Readme.md @@ -1060,6 +1060,7 @@ [1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) +[2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From ef99cfe27e9693afca8633bee61a447b82b0d542 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 20:27:17 -0700 Subject: [PATCH 0128/2729] Create Readme.md --- Greedy/2054.Two-Best-Non-Overlapping-Events/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2054.Two-Best-Non-Overlapping-Events/Readme.md diff --git a/Greedy/2054.Two-Best-Non-Overlapping-Events/Readme.md b/Greedy/2054.Two-Best-Non-Overlapping-Events/Readme.md new file mode 100644 index 000000000..a81abd124 --- /dev/null +++ b/Greedy/2054.Two-Best-Non-Overlapping-Events/Readme.md @@ -0,0 +1,7 @@ +### 2054.Two-Best-Non-Overlapping-Events + +本题就是```1235. Maximum Profit in Job Scheduling```的简化版。在1235中,要求所有non-overlapping的区间的最大权重和。本题中,只需要求两个non-overlapping的区间的最大权重和。 + +思路差不多。将所有的区间按照endTime排序。我们考察第i个区间[a,b,v]的时候,需要考虑在a时刻之前的那些完整区间里,我们可以收获的“单个区间”的最大收益。为了方便的得到这个数据,我们设计dp数组,里面放入一系列的{time, value},表示截止到time为止的完整区间里最大的一个value值。于是我们可以利用二分,在dp里找到最后一个小于等于a的时间戳,它所对应value值加上第i个区间本身的v,就是一对可行的解。依次类推,每处理一个区间,我们都利用这个方法找它之前的最大值与之配对。由此我们做到了所有可能配对不重不漏的枚举。 + +注意,处理完第i个区间后,我们需要将第i个区间的信息也加入dp数组。因为随着时间的推移,dp必然是递增的。所以当我们考虑所有前i个区间的最大值时,必然就是在dp的最后一个值与v之间取较大值vv。然后将{b,v}加入dp数组。 From f2048fd66c88e810f5bca3e3cee3282cb0d4930e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Oct 2021 20:50:34 -0700 Subject: [PATCH 0129/2729] Update 2054.Two-Best-Non-Overlapping-Events.cpp --- .../2054.Two-Best-Non-Overlapping-Events.cpp | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/Greedy/2054.Two-Best-Non-Overlapping-Events/2054.Two-Best-Non-Overlapping-Events.cpp b/Greedy/2054.Two-Best-Non-Overlapping-Events/2054.Two-Best-Non-Overlapping-Events.cpp index 3c55fc9d7..558fd8b4d 100644 --- a/Greedy/2054.Two-Best-Non-Overlapping-Events/2054.Two-Best-Non-Overlapping-Events.cpp +++ b/Greedy/2054.Two-Best-Non-Overlapping-Events/2054.Two-Best-Non-Overlapping-Events.cpp @@ -3,33 +3,38 @@ class Solution { { return a[1] < b[1]; } + public: int maxTwoEvents(vector>& events) { int n = events.size(); sort(events.begin(), events.end(), cmp); - vector>dp; // {time, value} - dp.push_back({events[0][1], events[0][2]}); - int rollingMax = events[0][2]; - - int ret = events[0][2]; + vectorrollingMax(n); + int m = 0; + for (int i=0; iendTimes; + int ret = 0; - for (int i=1; isecond; - } - ret = max(ret, lastMax + v); + int idx = iter - endTimes.begin(); + ret = max(ret, rollingMax[idx] + v); + } - rollingMax = max(rollingMax, v); - dp.push_back({b, rollingMax}); + endTimes.push_back(b); } return ret; From cdeecaad6040260f0f85818007ee4212c12b2cb5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Nov 2021 02:14:59 -0700 Subject: [PATCH 0130/2729] Create 2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp --- ...tring-Exists-Given-Two-Encoded-Strings.cpp | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp diff --git a/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp b/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp new file mode 100644 index 000000000..e30c6a741 --- /dev/null +++ b/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp @@ -0,0 +1,108 @@ +using LL = long long; +class Solution { + unordered_setvisited; +public: + bool possiblyEquals(string s1, string s2) + { + vectort1 = parse(s1); + vectort2 = parse(s2); + return dfs(t1, 0, 0, t2, 0, 0); + } + + vectorparse(string s) + { + vectort; + for (int i=0; i&t1, int i, int num1, vector&t2, int j, int num2) + { + if (i==t1.size() && j==t2.size()) + return num1==num2; + + if (i==t1.size() && num1==0) return false; + if (j==t2.size() && num2==0) return false; + + LL hash = i*1e9 + num1*1e6+ j*1e3+ num2; + if (visited.find(hash)!=visited.end()) return false; + + if (inums = getNum(t1[i]); + for (int x: nums) + { + if (dfs(t1, i+1, num1+x, t2, j, num2)) + return true; + } + visited.insert(hash); + return false; + } + else if (jnums = getNum(t2[j]); + for (int x: nums) + { + if (dfs(t1, i, num1, t2, j+1, num2+x)) + return true; + } + visited.insert(hash); + return false; + } + + if (num1!=0 && num2!=0) + { + int common = min(num1, num2); + return dfs(t1, i, num1-common, t2, j, num2-common); + } + else if (num1!=0 && num2==0) + { + return dfs(t1, i, num1-1, t2, j+1, 0); + } + else if (num1==0 && num2!=0) + { + return dfs(t1, i+1, 0, t2, j, num2-1); + } + else + { + visited.insert(hash); + if (t1[i]!=t2[j]) return false; + return dfs(t1, i+1, 0, t2, j+1, 0); + } + } + + unordered_setgetNum(string t) + { + int d = stoi(t); + if (t.size()==1) + return {d}; + else if (t.size()==2) + { + int a = d/10; + int b = d%10; + return {a+b, d}; + } + else + { + int a = d/100; + int b = (d/10)%10; + int c = d%10; + return {a+b+c, a+b*10+c, a*10+b+c, d}; + + } + } +}; From 45e19aec0ed0babd847b1db868fa2154b30568b4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Nov 2021 02:15:25 -0700 Subject: [PATCH 0131/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a2f08d7f2..b06424cda 100644 --- a/Readme.md +++ b/Readme.md @@ -842,6 +842,7 @@ 1545. Find Kth Bit in Nth Binary String (TBD) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) +[2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings) (H) * ``Evaluate Expressions`` [241.Different-Ways-to-Add-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/241.Different-Ways-to-Add-Parentheses) (M+) [2019.The-Score-of-Students-Solving-Math-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2019.The-Score-of-Students-Solving-Math-Expression) (H-) From 7384304938613146b222d04c1c4178b29b093c51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 2 Nov 2021 18:24:55 -0700 Subject: [PATCH 0132/2729] Create Readme.md --- .../Readme.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/Readme.md diff --git a/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/Readme.md b/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/Readme.md new file mode 100644 index 000000000..6ac47e04f --- /dev/null +++ b/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/Readme.md @@ -0,0 +1,25 @@ +### 2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings + +我们来看一个简单的例子。假设s1="3b3c", s2="2b3",那么我们会怎么判定两个字符串是否可能等效? + +第一步,我们发现s1开头有三个待定,s2开头有两个待定,所以显然我们可以消去两个。所以转化为 s1="1b3c", s2="b3" + +第二步,我们发现s1开头有一个待定,但s2开头是确定的字母,所以显然我们会将s1开头的待定匹配给s2开头的那个b。所以转化为 s1="b3c", s2="b3" + +第三步,我们发现s1开头是b,s2开头是b,二者恰好匹配可以共同消去。所以转化为 s1="3c", s2="3" + +第四步,类似地我们对消两者开头的三个待定。所以转化为 s1="c", s2="" + +最终,s2已经考察完,但是s1还有一个字符。所以匹配失败。 + +综上,我们发现,如果所有的待定的数目都是固定的,那么本题的本质就是一步步消减两个字符串开头能匹配的部分,然后递归处理后续。本题增加的难点其实就是针对数字串的处理,例如"123a",那么针对“123”的拆解,其实对应的可能其实是六种可能“123a”,“15a”,“24a”,“6a”。我们只要挨个将他们递归处理就行啦。 + +所以本题的递归函数可以设计为```bool dfs(vector&t1, int i, int num1, vector&t2, int j, int num2)```. 其中t1是将原s1按数字/字母进行拆解后的字符串数组,例如"s1=23ab111c",那么t就是{23,a,b,111,c}. i表示在t1数组里我们当前处理第几项。num1表示在处理当前项之前手头还有多少个“待定”可以用。t2,j,num2同理定义。 + +我们的算法步骤是: + +1. 无论对于t1还是t2,如果当前项是一个数字,那么我们拆解这个数字(分为四种可能)并叠加到当前的num上去,直至当前项是字母为止。 +2. 如果num1和num2都不为零,我们必然对消直至其中一个变为0 +3. 如果num1和num2只有一个为零,那么说明一方的字母可以匹配另一方的待定。 +4. 如果num1和num2都为零,说明我们必须比较两个字母。如果匹配就继续,否则就返回false +5. 只有t1和t2都恰好对消完全(包括待定),才能说明二者匹配。 From 26118d40e68f57c6f99121c5ab47c3c72159a4c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 11:18:48 -0700 Subject: [PATCH 0133/2729] Update Readme.md --- Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index b06424cda..ccf4d33c8 100644 --- a/Readme.md +++ b/Readme.md @@ -744,8 +744,6 @@ [006.ZigZag-Conversion](https://github.com/wisdompeak/LeetCode/tree/master/String/006.ZigZag-Conversion) (M+) [336.Palindrome-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/String/336.Palindrome-Pairs) (H-) [388.Longest-Absolute-File-Path](https://github.com/wisdompeak/LeetCode/tree/master/String/388.Longest-Absolute-File-Path) (M+) -[408.Valid-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/408.Valid-Word-Abbreviation) (M) -411.Minimum-Unique-Word-Abbreviation (H) [418.Sentence-Screen-Fitting](https://github.com/wisdompeak/LeetCode/tree/master/String/418.Sentence-Screen-Fitting) (M+) [423.Reconstruct-Original-Digits-from-English](https://github.com/wisdompeak/LeetCode/tree/master/Others/423.Reconstruct-Original-Digits-from-English) (H-) [527.Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/527.Word-Abbreviation) (M+) @@ -760,6 +758,11 @@ [1616.Split-Two-Strings-to-Make-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/String/1616.Split-Two-Strings-to-Make-Palindrome) (M+) [1754.Largest-Merge-Of-Two-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/1754.Largest-Merge-Of-Two-Strings) (M+) [1849.Splitting-a-String-Into-Descending-Consecutive-Values](https://github.com/wisdompeak/LeetCode/tree/master/String/1849.Splitting-a-String-Into-Descending-Consecutive-Values) (M+) +* ``Abbreviation`` +320. Generalized Abbreviation (M) +[408.Valid-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/408.Valid-Word-Abbreviation) (M) +411.Minimum-Unique-Word-Abbreviation (H) +[2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings) (H) * ``Rolling Hash`` [1044.Longest-Duplicate-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/1044.Longest-Duplicate-Substring) (H) [1062.Longest-Repeating-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/1062.Longest-Repeating-Substring) (H-) @@ -842,7 +845,6 @@ 1545. Find Kth Bit in Nth Binary String (TBD) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) -[2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings) (H) * ``Evaluate Expressions`` [241.Different-Ways-to-Add-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/241.Different-Ways-to-Add-Parentheses) (M+) [2019.The-Score-of-Students-Solving-Math-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2019.The-Score-of-Students-Solving-Math-Expression) (H-) From 3c538f959772d6ad418f5dd064195f5df176f796 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 11:19:11 -0700 Subject: [PATCH 0134/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ccf4d33c8..3189f5ff4 100644 --- a/Readme.md +++ b/Readme.md @@ -759,7 +759,7 @@ [1754.Largest-Merge-Of-Two-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/1754.Largest-Merge-Of-Two-Strings) (M+) [1849.Splitting-a-String-Into-Descending-Consecutive-Values](https://github.com/wisdompeak/LeetCode/tree/master/String/1849.Splitting-a-String-Into-Descending-Consecutive-Values) (M+) * ``Abbreviation`` -320. Generalized Abbreviation (M) +320.Generalized Abbreviation (M) [408.Valid-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/408.Valid-Word-Abbreviation) (M) 411.Minimum-Unique-Word-Abbreviation (H) [2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings) (H) From 18a8af4e1fb739ede1a1587a806309e065065e99 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 11:39:03 -0700 Subject: [PATCH 0135/2729] Create 320.Generalized-Abbreviation.cpp --- .../320.Generalized-Abbreviation.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 String/320.Generalized-Abbreviation/320.Generalized-Abbreviation.cpp diff --git a/String/320.Generalized-Abbreviation/320.Generalized-Abbreviation.cpp b/String/320.Generalized-Abbreviation/320.Generalized-Abbreviation.cpp new file mode 100644 index 000000000..acd5696cc --- /dev/null +++ b/String/320.Generalized-Abbreviation/320.Generalized-Abbreviation.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector generateAbbreviations(string word) + { + int n = word.size(); + vectorrets; + for (int state = 0; state < (1<>i)&1) + { + s.push_back(word[i]); + } + else + { + int j = i; + while (j>j)&1)==0) + j++; + s += to_string(j-i); + i = j-1; + } + } + rets.push_back(s); + } + return rets; + } +}; From a8d03adb1d3c88b8e7b8ff6ef1e1e42c17f27b7d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 11:39:29 -0700 Subject: [PATCH 0136/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3189f5ff4..630473dd8 100644 --- a/Readme.md +++ b/Readme.md @@ -759,7 +759,7 @@ [1754.Largest-Merge-Of-Two-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/1754.Largest-Merge-Of-Two-Strings) (M+) [1849.Splitting-a-String-Into-Descending-Consecutive-Values](https://github.com/wisdompeak/LeetCode/tree/master/String/1849.Splitting-a-String-Into-Descending-Consecutive-Values) (M+) * ``Abbreviation`` -320.Generalized Abbreviation (M) +[320.Generalized-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/320.Generalized-Abbreviation) (M) [408.Valid-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/408.Valid-Word-Abbreviation) (M) 411.Minimum-Unique-Word-Abbreviation (H) [2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings) (H) From 49837539645f2e360503184b0b0f4234b146e419 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 11:41:20 -0700 Subject: [PATCH 0137/2729] Update Readme.md --- String/408.Valid-Word-Abbreviation/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/String/408.Valid-Word-Abbreviation/Readme.md b/String/408.Valid-Word-Abbreviation/Readme.md index 496fff01d..f5b94ad70 100644 --- a/String/408.Valid-Word-Abbreviation/Readme.md +++ b/String/408.Valid-Word-Abbreviation/Readme.md @@ -1,10 +1,10 @@ ### 408.Valid-Word-Abbreviation -思路非常直接,遍历一遍abbr,移动abbr的同时也移动word的指针,看看每一步都是否对应。 +典型的双指针。遍历一遍abbr,移动abbr的指针的同时,也相应地移动word的指针,看看每一步都是否对应。具体地说,就是abbr的字母和word字母对应,abbr的数字和word里相同数目的字母对应。 需要注意的细节: 1. 数字不能有前导0. 比如word=ab, abbr=02就应该输出false. 2. abbr遍历完之后,word的遍历也应该恰好结束。即if (i!=word.size()) return false; -[Leetcode Link](https://leetcode.com/problems/valid-word-abbreviation) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/valid-word-abbreviation) From 0c8b9cff52fe9cca753e2f5a840f34a70b86c48d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 11:50:02 -0700 Subject: [PATCH 0138/2729] Create Readme.md --- String/320.Generalized-Abbreviation/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 String/320.Generalized-Abbreviation/Readme.md diff --git a/String/320.Generalized-Abbreviation/Readme.md b/String/320.Generalized-Abbreviation/Readme.md new file mode 100644 index 000000000..37e8f9088 --- /dev/null +++ b/String/320.Generalized-Abbreviation/Readme.md @@ -0,0 +1,5 @@ +### 320.Generalized-Abbreviation + +本题需要穷举所有的可能,可以考虑DFS用递归处理。但是因为本题不需要剪枝,并且每个位置上的字符都有且只有两种可能:要么被缩略,要么不被缩略。所以用bitmask来实现穷举写起来更方便。 + +我们遍历```00..0```到```11..1```的所有n位二进制状态。如果某位上是1,那么对应位置的字符就保留。如果某位上是0,那么对应位置上的字符就要被缩略:具体所谓的方法就是查看周围是否有连续的0,将这些连续0的数目改写成数字串即可。 From c578f8be69ab9f3ea2a608e56b20a91ba700776b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 11:50:47 -0700 Subject: [PATCH 0139/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 630473dd8..9989e8e5a 100644 --- a/Readme.md +++ b/Readme.md @@ -761,7 +761,7 @@ * ``Abbreviation`` [320.Generalized-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/320.Generalized-Abbreviation) (M) [408.Valid-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/408.Valid-Word-Abbreviation) (M) -411.Minimum-Unique-Word-Abbreviation (H) +[411.Minimum-Unique-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/411.Minimum-Unique-Word-Abbreviation) (H) [2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings) (H) * ``Rolling Hash`` [1044.Longest-Duplicate-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/1044.Longest-Duplicate-Substring) (H) From 7376f612a86b4bf4bf84d1ad8cdbd5e3ab823d3b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 14:38:10 -0700 Subject: [PATCH 0140/2729] Update Readme.md --- String/411.Minimum-Unique-Word-Abbreviation/Readme.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/String/411.Minimum-Unique-Word-Abbreviation/Readme.md b/String/411.Minimum-Unique-Word-Abbreviation/Readme.md index 8388878fe..b9be9ef83 100644 --- a/String/411.Minimum-Unique-Word-Abbreviation/Readme.md +++ b/String/411.Minimum-Unique-Word-Abbreviation/Readme.md @@ -2,11 +2,12 @@ 此题不需要遍历所有的字典里的单词的缩写形式. -首先,我们应该注意到,如果字典里的单词和target的长度不一致,那么永远不会有冲突.所以一下子将范围缩小到那些与target等长的单词了. +首先,我们应该注意到,缩写不会改变长度,所以两个长度不同的单词,他们的任何形式的缩写都不可能相同。所以对于字典里的那些与target的长度不一致的单词,完全可以忽略。 -其次,缩写的方案怎么确定呢?其实就是任意一个字符可以选择取或不取.所以就是2^N次方,用一个N位的二进制数(作为mask)就可以表示了.有0的bit表示改成数字,有1的bit表示保留字母.这样一个mask就表示一种缩写方案. +其次,targe的缩写方案有多少呢?不难判断,每一个字符只有两种选择:被缩写或者不被缩写。所以target的缩写形式只有2^m种可能。考虑到m是21,最多有2e6种缩写,是可以遍历过来的。对于无需剪枝的无脑遍历,使用bitmask来穷举所有缩写方式是最方便的,这与```LC 320.Generalized-Abbreviation```是一样的做法。当然,我们肯定先尝试长度短的缩写方法,再尝试长的缩写方法。所以需要将所有的缩写方法按照长度排序。 -因此,我们不需要用DFS显式地穷尽字典或target的所有缩写字符串,只要逐个查验缩写方案即可.我们将所有mask按照题目中定义的长度按从小到大排序.每尝试一个mask,就查看依照这种缩写方案得到的target,是否与字典里的单词依靠同样一种缩写方案得到的字符串相同.如果没有冲突的,那么我们就可以立马选用这种缩写方案. +最后,我们对于target的每一种缩写方式abbr,都要与字典里的每一个单词word进行匹配,看是否abbr是否也是word的一个缩写。这个算法和```LC 408.Valid-Word-Abbreviation```是一样的。 +所以总的时间复杂度是```o(2^m*n)```. 因为题目给出了m+log(n)<=21,所以```2^m*n<=2^21```,即时间复杂度是2e6级别,是可行的。 -[Leetcode Link](https://leetcode.com/problems/minimum-unique-word-abbreviation) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/minimum-unique-word-abbreviation) From 181cb7408a3253e9161a29aa21ac93bbf6ccde3d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 15:07:37 -0700 Subject: [PATCH 0141/2729] Update 411.Minimum-Unique-Word-Abbreviation.cpp --- .../411.Minimum-Unique-Word-Abbreviation.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp b/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp index d9a8d9650..026acb11a 100644 --- a/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp +++ b/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp @@ -24,7 +24,7 @@ class Solution { int mask = masks[i].second; string a = abbr(target,mask); int flag = 1; - + for (auto word:Set) { string b = abbr(word, mask); @@ -36,6 +36,7 @@ class Solution { } if (flag == 1) return a; } + return ""; } @@ -44,12 +45,12 @@ class Solution { int count = 0; for (int i=0; i>(N-1-i))&1)==1) + if (((mask>>i)&1)==1) count++; else { int j = i+1; - while (j>(N-1-j))&1)==0) + while (j>j)&1)==0) j++; count++; i = j-1; @@ -65,12 +66,12 @@ class Solution { for (int i=0; i>(N-1-i))&1)==1) + if (((mask>>i)&1)==1) result.push_back(A[i]); else { int j = i+1; - while (j>(N-1-j))&1)==0) + while (j>j)&1)==0) j++; result += to_string(j-i); i = j-1; From 63f8056b8da76423747f686bb3065ac33c7c65d9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Nov 2021 15:50:03 -0700 Subject: [PATCH 0142/2729] Update 411.Minimum-Unique-Word-Abbreviation.cpp --- .../411.Minimum-Unique-Word-Abbreviation.cpp | 94 +++++++++---------- 1 file changed, 46 insertions(+), 48 deletions(-) diff --git a/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp b/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp index 026acb11a..07c736893 100644 --- a/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp +++ b/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp @@ -1,83 +1,81 @@ class Solution { + int m; public: string minAbbreviation(string target, vector& dictionary) { if (dictionary.size()==0) - return to_string(target.size()); - - unordered_setSet; - int N = target.size(); + return to_string(target.size()); + this->m = target.size(); - for (auto str:dictionary) + unordered_setSet; + for (auto word: dictionary) { - if (str.size()==N) - Set.insert(str); - } - - vector>masks; - for (int i=0; i<(1<>masks; + for (int state = 0; state < (1<>i)&1)==1) - count++; + if ((mask>>i)&1) + ret.push_back(word[i]); else { - int j = i+1; - while (j>j)&1)==0) + int j = i; + while (j>j)&1)==0) j++; - count++; + ret += to_string(j-i); i = j-1; } - } - return count; + } + return ret; } - string abbr(string A, int mask) - { - string result; - int N = A.size(); - - for (int i=0; i>i)&1)==1) - result.push_back(A[i]); + if ((mask>>i)&1) + count++; else { - int j = i+1; - while (j>j)&1)==0) + int j = i; + while (j>j)&1)==0) j++; - result += to_string(j-i); + count += to_string(j-i).size(); i = j-1; } } - return result; + return count; + } - }; From 4d61a6b1a6d2f0ba9121dd2d2a4b9994ac14aa14 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Nov 2021 23:24:46 -0800 Subject: [PATCH 0143/2729] Create 2065.Maximum-Path-Quality-of-a-Graph.cpp --- .../2065.Maximum-Path-Quality-of-a-Graph.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 DFS/2065.Maximum-Path-Quality-of-a-Graph/2065.Maximum-Path-Quality-of-a-Graph.cpp diff --git a/DFS/2065.Maximum-Path-Quality-of-a-Graph/2065.Maximum-Path-Quality-of-a-Graph.cpp b/DFS/2065.Maximum-Path-Quality-of-a-Graph/2065.Maximum-Path-Quality-of-a-Graph.cpp new file mode 100644 index 000000000..8ef06c6af --- /dev/null +++ b/DFS/2065.Maximum-Path-Quality-of-a-Graph/2065.Maximum-Path-Quality-of-a-Graph.cpp @@ -0,0 +1,39 @@ +class Solution { + int ret = 0; + int maxTime; + vector>next[1000]; + int visited[1000]; + vectorvalues; +public: + int maximalPathQuality(vector& values, vector>& edges, int maxTime) + { + this->maxTime = maxTime; + this->values = values; + + int n = values.size(); + for (auto edge: edges) + { + int a = edge[0], b = edge[1], t = edge[2]; + next[a].push_back({b,t}); + next[b].push_back({a,t}); + } + + visited[0] = 1; + dfs(0, values[0], 0); + return ret; + } + + void dfs(int cur, int totalVal, int totalTime) + { + if (totalTime > maxTime) return; + if (cur==0) ret = max(ret, totalVal); + + for (auto x: next[cur]) + { + int nxt = x.first, t = x.second; + visited[nxt]++; + dfs(nxt, totalVal + (visited[nxt]==1?values[nxt]:0), totalTime+t); + visited[nxt]--; + } + } +}; From 9511544975d14868fffb14d217270dd4a42ff250 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Nov 2021 23:25:18 -0800 Subject: [PATCH 0144/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9989e8e5a..36ca77d38 100644 --- a/Readme.md +++ b/Readme.md @@ -403,6 +403,7 @@ [1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) [2014.Longest-Subsequence-Repeated-k-Times](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2014.Longest-Subsequence-Repeated-k-Times) (H) [2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) +[2065.Maximum-Path-Quality-of-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2065.Maximum-Path-Quality-of-a-Graph) (M) * ``search in an array`` [090.Subsets-II](https://github.com/wisdompeak/LeetCode/tree/master/DFS/090.Subsets-II) (M+) [301.Remove-Invalid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/DFS/301.Remove-Invalid-Parentheses) (H) From ca1d77a9efa52d30cb9afb1d92c4588df8a41be8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Nov 2021 23:34:52 -0800 Subject: [PATCH 0145/2729] Create Readme.md --- DFS/2065.Maximum-Path-Quality-of-a-Graph/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 DFS/2065.Maximum-Path-Quality-of-a-Graph/Readme.md diff --git a/DFS/2065.Maximum-Path-Quality-of-a-Graph/Readme.md b/DFS/2065.Maximum-Path-Quality-of-a-Graph/Readme.md new file mode 100644 index 000000000..f59b6f745 --- /dev/null +++ b/DFS/2065.Maximum-Path-Quality-of-a-Graph/Readme.md @@ -0,0 +1,3 @@ +### 2065.Maximum-Path-Quality-of-a-Graph + +题意的约束中给出了```10 <= timej, maxTime <= 100```,这说明最多只能走10步。又因为There are at most four edges connected to each node,每一步出发最多只有四种选择,所以无脑搜索的话最多也只有4^10=1e6种可能。全部本题只要穷举所有的路径选择即可。 From df93126e65da5434cd8e5c159b069fa6cbc9ef75 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 10 Nov 2021 01:29:23 -0800 Subject: [PATCH 0146/2729] Update 1354.Construct-Target-Array-With-Multiple-Sums.cpp --- ...struct-Target-Array-With-Multiple-Sums.cpp | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Greedy/1354.Construct-Target-Array-With-Multiple-Sums/1354.Construct-Target-Array-With-Multiple-Sums.cpp b/Greedy/1354.Construct-Target-Array-With-Multiple-Sums/1354.Construct-Target-Array-With-Multiple-Sums.cpp index f49535913..1c699a31a 100644 --- a/Greedy/1354.Construct-Target-Array-With-Multiple-Sums/1354.Construct-Target-Array-With-Multiple-Sums.cpp +++ b/Greedy/1354.Construct-Target-Array-With-Multiple-Sums/1354.Construct-Target-Array-With-Multiple-Sums.cpp @@ -2,27 +2,27 @@ class Solution { public: bool isPossible(vector& target) { - long long sum = 0; priority_queuepq; - for (int i=0; i Date: Wed, 10 Nov 2021 01:31:20 -0800 Subject: [PATCH 0147/2729] Update Readme.md --- Greedy/1354.Construct-Target-Array-With-Multiple-Sums/Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Greedy/1354.Construct-Target-Array-With-Multiple-Sums/Readme.md b/Greedy/1354.Construct-Target-Array-With-Multiple-Sums/Readme.md index 76ddeb378..e5ffb0412 100644 --- a/Greedy/1354.Construct-Target-Array-With-Multiple-Sums/Readme.md +++ b/Greedy/1354.Construct-Target-Array-With-Multiple-Sums/Readme.md @@ -41,3 +41,4 @@ while (pq.top()!=1) pq.push(b); } ``` +但是以上还有一个bug。那就是b在取余运算之后的结果可能是零。但是题目中要求的所有元素的初始状态是1。这说明我们不能把b降到0。也就是说,如果a能被other整除,我们就只能把b降到others。 From 73c37de5b634eda22ca71566fae5b53dbcfb4b50 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 Nov 2021 05:39:59 -0800 Subject: [PATCH 0148/2729] Update 411.Minimum-Unique-Word-Abbreviation.cpp --- .../411.Minimum-Unique-Word-Abbreviation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp b/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp index 07c736893..29c03870e 100644 --- a/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp +++ b/String/411.Minimum-Unique-Word-Abbreviation/411.Minimum-Unique-Word-Abbreviation.cpp @@ -71,7 +71,7 @@ class Solution { int j = i; while (j>j)&1)==0) j++; - count += to_string(j-i).size(); + count += 1; i = j-1; } } From ef25f2689cdcc6e24e4787ca59ccd1a4bedf92ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 Nov 2021 12:04:34 -0800 Subject: [PATCH 0149/2729] Create 2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store.cpp --- ...m-of-Products-Distributed-to-Any-Store.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store.cpp diff --git a/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store.cpp b/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store.cpp new file mode 100644 index 000000000..1aea7e8eb --- /dev/null +++ b/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minimizedMaximum(int n, vector& quantities) + { + int left = 1, right = INT_MAX/2; + while (left < right) + { + int mid = left+(right-left)/2; + if (checkOK(quantities, n, mid)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool checkOK(vector& quantities, int n, int limit) + { + int count = 0; + for (int x: quantities) + { + if (x%limit == 0) + count += x/limit; + else + count += x/limit+1; + } + return count <=n; + } +}; From f7499f73a52c999752480dd7c91acd02e724c141 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 Nov 2021 12:04:57 -0800 Subject: [PATCH 0150/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 36ca77d38..bf1fa8309 100644 --- a/Readme.md +++ b/Readme.md @@ -114,6 +114,7 @@ [1870.Minimum-Speed-to-Arrive-on-Time](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1870.Minimum-Speed-to-Arrive-on-Time) (M) [1898.Maximum-Number-of-Removable-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1898.Maximum-Number-of-Removable-Characters) (H-) [1891.Cutting-Ribbons](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1891.Cutting-Ribbons) (E) +[2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store) (M) #### [Hash Table](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From 78fbabd1f8ca78ab6ad62b3e1b3a7536800845b7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 Nov 2021 12:40:22 -0800 Subject: [PATCH 0151/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store/Readme.md diff --git a/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store/Readme.md b/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store/Readme.md new file mode 100644 index 000000000..cf0916a7f --- /dev/null +++ b/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store/Readme.md @@ -0,0 +1,5 @@ +### 2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store + +我们不想让每个store存放的物品的太多,那么只好多征用store的数目。但是总的store数目是有限的,这就可能导致冲突。想要解决这个冲突,只能允许让每个store存更多的东西。至此,我们不难想到二分搜值就是一个显然易见的算法。 + +我们尝试每个store存放物品个数的上限是limit,那么对于每一种物品,我们能算出至少需要多少store来存放。遍历所有的物品种类,就可以得出总共需要的store数目n',然后与实际的store数目n比较。根据如果n'<=n,说明上限可以往下降(还可以占用更多的store);反之说明上限必须提升(减少需要占用的store)。 From c22c6f536e366476b88fc16660bd9c08f6b7f5f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 06:22:16 -0800 Subject: [PATCH 0152/2729] Create 1049.Last-Stone-Weight-II_v2.cpp --- .../1049.Last-Stone-Weight-II_v2.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Dynamic_Programming/1049.Last-Stone-Weight-II/1049.Last-Stone-Weight-II_v2.cpp diff --git a/Dynamic_Programming/1049.Last-Stone-Weight-II/1049.Last-Stone-Weight-II_v2.cpp b/Dynamic_Programming/1049.Last-Stone-Weight-II/1049.Last-Stone-Weight-II_v2.cpp new file mode 100644 index 000000000..f556093b7 --- /dev/null +++ b/Dynamic_Programming/1049.Last-Stone-Weight-II/1049.Last-Stone-Weight-II_v2.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int lastStoneWeightII(vector& stones) + { + int sum = accumulate(stones.begin(), stones.end(), 0); + vectordp(2*sum+2, false); + int offset = sum; + + dp[stones[0]+offset] = 1; + dp[-stones[0]+offset] = 1; + + for (int i=1; idp2(2*sum+2, false); + for (int s = -sum; s<= sum; s++) + { + if (s-stones[i] >= -sum && s-stones[i] <= sum) + dp2[s+offset] = dp2[s+offset] || dp[s-stones[i]+offset]; + if (s+stones[i] >= -sum && s+stones[i] <= sum) + dp2[s+offset] = dp2[s+offset] || dp[s+stones[i]+offset]; + } + dp = std::move(dp2); + } + + for (int s = 0; s<=sum; s++) + if (dp[s+offset]) + return s; + return 0; + } +}; From 3b12ca049bec40021b018edacc9232d3a007c80f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 08:05:46 -0800 Subject: [PATCH 0153/2729] Create 2069.Walking-Robot-Simulation-II.cpp --- .../2069.Walking-Robot-Simulation-II.cpp | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Simulation/2069.Walking-Robot-Simulation-II/2069.Walking-Robot-Simulation-II.cpp diff --git a/Simulation/2069.Walking-Robot-Simulation-II/2069.Walking-Robot-Simulation-II.cpp b/Simulation/2069.Walking-Robot-Simulation-II/2069.Walking-Robot-Simulation-II.cpp new file mode 100644 index 000000000..d3d4c81c8 --- /dev/null +++ b/Simulation/2069.Walking-Robot-Simulation-II/2069.Walking-Robot-Simulation-II.cpp @@ -0,0 +1,78 @@ +class Robot { + int width, height; + int d,x,y; + vector>dir = {{1,0},{0,1},{-1,0},{0,-1}}; + int total; +public: + Robot(int width, int height) + { + this->width = width; + this->height = height; + d=0, x=0, y=0; + total = width*2+(height-2)*2; + } + + void move(int num) + { + int flag = 0; + + while (num > 0) + { + int remain; + if (d==0) remain = width-1-x; + else if (d==1) remain = height-1-y; + else if (d==2) remain = x; + else remain = y; + + if (remain >= num) + { + x += dir[d].first * num; + y += dir[d].second * num; + num = 0; + } + else + { + x += dir[d].first * remain; + y += dir[d].second * remain; + d = (d+1)%4; + num -= remain; + + num %= total; + if (num == 0 && atCorner(x,y)) + { + d = (d-1+4)%4; + } + } + } + } + + bool atCorner(int x, int y) + { + if (x==0 && y==0) return true; + if (x==0 && y==height-1) return true; + if (x==width-1 && y==0) return true; + if (x==width-1 && y==height-1) return true; + return false; + } + + vector getPos() + { + return {x,y}; + } + + string getDir() + { + if (d==0) return "East"; + else if (d==1) return "North"; + else if (d==2) return "West"; + else return "South"; + } +}; + +/** + * Your Robot object will be instantiated and called as such: + * Robot* obj = new Robot(width, height); + * obj->move(num); + * vector param_2 = obj->getPos(); + * string param_3 = obj->getDir(); + */ From 74af1c9d82274af84da410992a33cc97bf645c2c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 08:06:42 -0800 Subject: [PATCH 0154/2729] Update Readme.md --- Readme.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Readme.md b/Readme.md index bf1fa8309..f57e0c845 100644 --- a/Readme.md +++ b/Readme.md @@ -1071,6 +1071,9 @@ [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) [932.Beautiful-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/932.Beautiful-Array) (H) +#### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation)   +[2069.Walking-Robot-Simulation-II](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2069.Walking-Robot-Simulation-II) (M+) + #### [Others](https://github.com/wisdompeak/LeetCode/tree/master/Others)   [007.Reverse-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/007.Reverse-Integer) (M) [048.Rotate-Image](https://github.com/wisdompeak/LeetCode/tree/master/Others/048.Rotate-Image) (M+) From 07111e4f0fc266fe9729d8c7ddb7b2e7a41f0d12 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 08:18:46 -0800 Subject: [PATCH 0155/2729] Create Readme.md --- Simulation/2069.Walking-Robot-Simulation-II/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Simulation/2069.Walking-Robot-Simulation-II/Readme.md diff --git a/Simulation/2069.Walking-Robot-Simulation-II/Readme.md b/Simulation/2069.Walking-Robot-Simulation-II/Readme.md new file mode 100644 index 000000000..e7304c36c --- /dev/null +++ b/Simulation/2069.Walking-Robot-Simulation-II/Readme.md @@ -0,0 +1,8 @@ +### 2069.Walking-Robot-Simulation-II + +本题就是一道模拟题。大致需要考虑这么几点。 + +1. 首先在判断在给定方向上,判断还能最多走几步碰到边界。如果走不到边界,那么就走指定的步数。 +2. 其次如果碰到边界还没有走完,那么就需要逆时针转向,然后根据1的方法再走剩余的步数。 +3. 如果已经在边缘绕着走的话,尝试用对```steps % total```来化简套圈的周期过程,其中total就是边缘一圈所需要的步数。通常,一个周期之后会回到原来的地方,方向不变。 +4. 特别注意的一个特例,如果起点本身是在“角落”,而需要走的步数又恰好是total,那么走完一圈之后回到起点时,并不需要变向。也就是说,方向还要倒退90度。 From aaabe8034d0ca8ba8aac38229abd684393219a5a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 10:57:30 -0800 Subject: [PATCH 0156/2729] Create 2071.Maximum-Number-of-Tasks-You-Can-Assign.cpp --- ...Maximum-Number-of-Tasks-You-Can-Assign.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign/2071.Maximum-Number-of-Tasks-You-Can-Assign.cpp diff --git a/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign/2071.Maximum-Number-of-Tasks-You-Can-Assign.cpp b/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign/2071.Maximum-Number-of-Tasks-You-Can-Assign.cpp new file mode 100644 index 000000000..eea60b46c --- /dev/null +++ b/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign/2071.Maximum-Number-of-Tasks-You-Can-Assign.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int maxTaskAssign(vector& tasks, vector& workers, int pills, int strength) + { + sort(tasks.begin(), tasks.end()); + sort(workers.begin(), workers.end()); + int left = 0, right = tasks.size(); + while (left < right) + { + int mid = right - (right - left)/2; + if (checkOK(tasks, workers, pills, strength, mid)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool checkOK(vector& tasks, vector& workers, int pills, int strength, int num) + { + if (num > tasks.size()) return false; + if (num > workers.size()) return false; + + multisetSet(workers.begin(), workers.end()); + + for (int i=num-1; i>=0; i--) + { + if (*Set.rbegin() >= tasks[i]) + { + Set.erase(prev(Set.end())); + } + else + { + if (pills == 0) return false; + auto iter = Set.lower_bound(tasks[i]-strength); + if (iter == Set.end()) return false; + Set.erase(iter); + pills--; + } + } + return true; + } +}; From 7e5dfba4c889591f5055801aa47cdca7de3103be Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 10:58:05 -0800 Subject: [PATCH 0157/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index f57e0c845..5d1468411 100644 --- a/Readme.md +++ b/Readme.md @@ -115,6 +115,7 @@ [1898.Maximum-Number-of-Removable-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1898.Maximum-Number-of-Removable-Characters) (H-) [1891.Cutting-Ribbons](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1891.Cutting-Ribbons) (E) [2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store) (M) +[2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) #### [Hash Table](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) @@ -176,6 +177,7 @@ [1847.Closest-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1847.Closest-Room) (M+) [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) +[2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From 858825361de00803e6d8a815cd9f32e1947c31a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 11:24:13 -0800 Subject: [PATCH 0158/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign/Readme.md diff --git a/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign/Readme.md b/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign/Readme.md new file mode 100644 index 000000000..eca8a92b3 --- /dev/null +++ b/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign/Readme.md @@ -0,0 +1,11 @@ +### 2071.Maximum-Number-of-Tasks-You-Can-Assign + +这道题如果正面硬刚的话比较棘手。对于任何一个task,我们首先不清楚它是否一定要被选中。即使要选中,它是应该分给一个能够单干的工人,还是分给一个吃了大力丸的工人?同样,对于任何一个工人,我们也不清楚他是否一定要被选中,或者他是选择单干一个task,还是吃一个大力丸再找一个task。 + +因为本题的解其实是有明确的范围的,即从0件到所有的task。所以我们可以考虑二分搜值,即猜测我们能够完成k件,看一下是否能够有一个合法的方法。 + +我们发现如果给定了完成k件的指标,就多了很多信息。首先这k件任务一定是难度最低的k件。我们先考虑其中难度最大的。这个难度最大的任务应该是必须完成的,所以它首先会找能力最强的worker,这是因为最强能力的工人如果不去做最难的任务,那么做其他简单任务就是浪费能力。于是就会有两种情况: +1. 当前最强工人能够单干解决它,那么就把这个任务和工人配对,记得将已经配对的工人剔除。 +2. 如果当前最强工人不能单干解决它,那么意味着我们必须要找一个工人吃大力丸来解决。显然,我们不一定要找最强工人去吃大力丸,我们只需要找一个刚刚好的工人,使得```worker+strength >= task```即可。于是这就提示我们需要将所有的worker排好序,用lower_bound来找到这个刚刚好的工人。完成这次配对之后,这个工人必须剔除。考虑到以后处理其他task时我们可能还需要剩余的工人保持有序状态,所以我们必须使用类似multiset的数据结构来保证删除一个元素之后仍然自动有序。 + +通过以上方法,就可以贪心地确认每个task应该分给哪个工人。如果指定的k任务都能顺利分配,那么二分搜值的checkOK就可以返回true,可以考虑在下一个回合提升k;反之就要减少k。 From 5ed6304dd01a4edfdb46d192e76f8190455b4b6f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 18:05:46 -0800 Subject: [PATCH 0159/2729] Create 2074.Reverse-Nodes-in-Even-Length-Groups.cpp --- ...74.Reverse-Nodes-in-Even-Length-Groups.cpp | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/2074.Reverse-Nodes-in-Even-Length-Groups.cpp diff --git a/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/2074.Reverse-Nodes-in-Even-Length-Groups.cpp b/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/2074.Reverse-Nodes-in-Even-Length-Groups.cpp new file mode 100644 index 000000000..59106b5f3 --- /dev/null +++ b/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/2074.Reverse-Nodes-in-Even-Length-Groups.cpp @@ -0,0 +1,71 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseEvenLengthGroups(ListNode* head) + { + vectorheads; + vectorlens; + + ListNode* h = head; + int len = 1; + + while (1) + { + heads.push_back(h); + int count = 1; + for (int i=0; inext == NULL) break; + h = h->next; + count++; + } + lens.push_back(count); + + if (h->next==NULL) break; + ListNode* nxt = h->next; + h->next = NULL; + h = nxt; + len++; + } + + for (int i=0; inext!=NULL) + p = p->next; + p->next = heads[i+1]; + } + + return heads[0]; + } + + ListNode* reverseLinkedList(ListNode* head) + { + ListNode* h = head; + ListNode* last = NULL; + while (h!=NULL) + { + ListNode* nxt = h->next; + h->next = last; + last = h; + h = nxt; + } + return last; + } +}; From 3cc2899c60dc10adef3f4db618305fd8422ad467 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 18:09:02 -0800 Subject: [PATCH 0160/2729] Update 2074.Reverse-Nodes-in-Even-Length-Groups.cpp --- .../2074.Reverse-Nodes-in-Even-Length-Groups.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/2074.Reverse-Nodes-in-Even-Length-Groups.cpp b/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/2074.Reverse-Nodes-in-Even-Length-Groups.cpp index 59106b5f3..209dcb677 100644 --- a/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/2074.Reverse-Nodes-in-Even-Length-Groups.cpp +++ b/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/2074.Reverse-Nodes-in-Even-Length-Groups.cpp @@ -57,14 +57,15 @@ class Solution { ListNode* reverseLinkedList(ListNode* head) { - ListNode* h = head; + ListNode* cur = head; ListNode* last = NULL; - while (h!=NULL) + ListNode* next = NULL; + while (cur!=NULL) { - ListNode* nxt = h->next; - h->next = last; - last = h; - h = nxt; + next = cur->next; + cur->next = last; + last = cur; + cur = next; } return last; } From 093e4f1ecba53f52ddeb5bd3605305d6c13dd888 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 18:40:09 -0800 Subject: [PATCH 0161/2729] Update Readme.md --- Readme.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 5d1468411..f575903d4 100644 --- a/Readme.md +++ b/Readme.md @@ -516,8 +516,6 @@ [086.Partition-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/086.Partition-List) (M) [142.Linked-List-Cycle-II](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/142.Linked-List-Cycle-II) (M+) [109.Convert-Sorted-List-to-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/109.Convert-Sorted-List-to-Binary-Search-Tree) (M) -[092.Reverse-Linked-List-II](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/092.Reverse-Linked-List-II) (H-) -[143.Reorder-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/143.Reorder-List) (H-) [369.Plus-One-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/369.Plus-One-Linked-List) (M) [430.Flatten-a-Multilevel-Doubly-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/430.Flatten-a-Multilevel-Doubly-Linked-List) (H-) [457.Circular-Array-Loop](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/457.Circular-Array-Loop) (H-) @@ -525,6 +523,11 @@ [1474.Delete-N-Nodes-After-M-Nodes-of-a-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/1474.Delete-N-Nodes-After-M-Nodes-of-a-Linked-List) (M+) [1670.Design-Front-Middle-Back-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/1670.Design-Front-Middle-Back-Queue) (M+) [1756.Design-Most-Recently-Used-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/1756.Design-Most-Recently-Used-Queue) (H) +* ``Reverse Linked List`` +206.Reverse Linked List (M) +[092.Reverse-Linked-List-II](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/092.Reverse-Linked-List-II) (H-) +[143.Reorder-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/143.Reorder-List) (H-) +[2074.Reverse-Nodes-in-Even-Length-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups) (H-) #### [Dynamic Programming](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming) [264.Ugly-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/264.Ugly-Number-II) (H-) From ae2eaa11d3063d5b68d6f81775cd8d24c69a8a72 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 20:21:15 -0800 Subject: [PATCH 0162/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/Readme.md diff --git a/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/Readme.md b/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/Readme.md new file mode 100644 index 000000000..84df88e0a --- /dev/null +++ b/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups/Readme.md @@ -0,0 +1,11 @@ +### 2074.Reverse-Nodes-in-Even-Length-Groups + +本题可以用取巧的方法,将所有的节点数值都复制到一个数组之中,然后根据题意重新创建一个链表。 + +在这里我们写一下严格的in-place的解法。 + +我们第一步是需要将原链表拆解成若干个独立的子链表,各个子链表的长度分别是1,2,3,... 注意到最后一个链表的长度不定。我们将所有子链表的头指针放入数组heads,并且将所有子链表的长度放入数组lens + +第二步就是对长度为偶数的子链表做反转操作。这是一个经典考点。 + +最后就是把所有的子链表串联起来。具体的就是将前一个子链表的尾节点,与下一个子链表的头节点相连。 From e8a8419b23ec8d07e7dcc9c789a0b6b79b6e045e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 23:02:30 -0800 Subject: [PATCH 0163/2729] Create 2076.Process-Restricted-Friend-Requests.cpp --- ...076.Process-Restricted-Friend-Requests.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Union_Find/2076.Process-Restricted-Friend-Requests/2076.Process-Restricted-Friend-Requests.cpp diff --git a/Union_Find/2076.Process-Restricted-Friend-Requests/2076.Process-Restricted-Friend-Requests.cpp b/Union_Find/2076.Process-Restricted-Friend-Requests/2076.Process-Restricted-Friend-Requests.cpp new file mode 100644 index 000000000..c2b7e9c8a --- /dev/null +++ b/Union_Find/2076.Process-Restricted-Friend-Requests/2076.Process-Restricted-Friend-Requests.cpp @@ -0,0 +1,49 @@ +class Solution { + vectorFather; + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (x friendRequests(int n, vector>& restrictions, vector>& requests) + { + Father.resize(n); + for (int i=0; irets; + for (auto& req: requests) + { + int x = req[0], y = req[1]; + int f_x = FindFather(x), f_y = FindFather(y); + if (f_x == f_y) + { + rets.push_back(true); + continue; + } + int flag = 1; + for (auto& res: restrictions) + { + int a = res[0], b = res[1]; + int f_a = FindFather(a), f_b = FindFather(b); + if ((f_a==f_x && f_b==f_y) || (f_a==f_y && f_b==f_x)) + { + flag = 0; + break; + } + } + rets.push_back(flag==1); + if (flag==1) Union(x,y); + } + return rets; + } +}; From ede030037573340c5d599eef22ed4426498c41bf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 23:02:55 -0800 Subject: [PATCH 0164/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f575903d4..c4c149541 100644 --- a/Readme.md +++ b/Readme.md @@ -817,6 +817,7 @@ [1722.Minimize-Hamming-Distance-After-Swap-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1722.Minimize-Hamming-Distance-After-Swap-Operations) (M+) [803.Bricks-Falling-When-Hit](https://github.com/wisdompeak/LeetCode/tree/master/DFS/803.Bricks-Falling-When-Hit) (H) [1970.Last-Day-Where-You-Can-Still-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1970.Last-Day-Where-You-Can-Still-Cross) (H-) +[2076.Process-Restricted-Friend-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2076.Process-Restricted-Friend-Requests) (H-) * ``Prime Factors`` [952.Largest-Component-Size-by-Common-Factor](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/952.Largest-Component-Size-by-Common-Factor) (H) [1627.Graph-Connectivity-With-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1627.Graph-Connectivity-With-Threshold) (M+) From ae76b108fc8e24185fe18f8f46bb01878cccb660 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Nov 2021 23:56:51 -0800 Subject: [PATCH 0165/2729] Create Readme.md --- Union_Find/2076.Process-Restricted-Friend-Requests/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Union_Find/2076.Process-Restricted-Friend-Requests/Readme.md diff --git a/Union_Find/2076.Process-Restricted-Friend-Requests/Readme.md b/Union_Find/2076.Process-Restricted-Friend-Requests/Readme.md new file mode 100644 index 000000000..e17b7e071 --- /dev/null +++ b/Union_Find/2076.Process-Restricted-Friend-Requests/Readme.md @@ -0,0 +1,5 @@ +### 2076.Process-Restricted-Friend-Requests + +我们想判断x和y是否能成为朋友,取决于x所在的家族X、y所在的家族Y,不能有任何一对是敌人。换句话说,如果家族X、家族Y中有存在任何一对是restriction,那么x和y就不能归并到一起。 + +显然,我们不可能穷举X家族、Y家族的配对。但是翻过来,我们可以穷举所有的restriction,查看每对敌人的双方是否分别存在这两个家族之中。这样,时间复杂度就是request的数目乘以restriction的数目,恰好符合题意。 From 659b26e5f7bbc4b864490944f932c75cc847acef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 16 Nov 2021 23:00:00 -0800 Subject: [PATCH 0166/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c4c149541..ca1b45f38 100644 --- a/Readme.md +++ b/Readme.md @@ -510,7 +510,6 @@ [1938.Maximum-Genetic-Difference-Query](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1938.Maximum-Genetic-Difference-Query) (H) #### [Linked List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List) -[025.Reverse-Nodes-in-k-Group](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/025.Reverse-Nodes-in-k-Group) (H-) [061.Rotate-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/061.Rotate-List) (M) 082.Remove-Duplicates-from-Sorted-List-II (M+) [086.Partition-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/086.Partition-List) (M) @@ -525,6 +524,7 @@ [1756.Design-Most-Recently-Used-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/1756.Design-Most-Recently-Used-Queue) (H) * ``Reverse Linked List`` 206.Reverse Linked List (M) +[025.Reverse-Nodes-in-k-Group](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/025.Reverse-Nodes-in-k-Group) (H-) [092.Reverse-Linked-List-II](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/092.Reverse-Linked-List-II) (H-) [143.Reorder-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/143.Reorder-List) (H-) [2074.Reverse-Nodes-in-Even-Length-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups) (H-) From 9f0732cb71caf6cb7f003d121a3186e251e3c903 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 16 Nov 2021 23:40:53 -0800 Subject: [PATCH 0167/2729] Create 206.Reverse-Linked-List.cpp --- .../206.Reverse-Linked-List.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Linked_List/206.Reverse-Linked-List/206.Reverse-Linked-List.cpp diff --git a/Linked_List/206.Reverse-Linked-List/206.Reverse-Linked-List.cpp b/Linked_List/206.Reverse-Linked-List/206.Reverse-Linked-List.cpp new file mode 100644 index 000000000..5c34894af --- /dev/null +++ b/Linked_List/206.Reverse-Linked-List/206.Reverse-Linked-List.cpp @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) + { + ListNode* last = NULL; + ListNode* cur = head; + ListNode* nxt; + + while (cur) + { + nxt = cur->next; + cur->next = last; + last = cur; + cur = nxt; + } + return last; + } +}; From 238569b694771e5f7e95bb9c45ee2f257540b487 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 16 Nov 2021 23:43:44 -0800 Subject: [PATCH 0168/2729] Create Readme.md --- Linked_List/206.Reverse-Linked-List/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Linked_List/206.Reverse-Linked-List/Readme.md diff --git a/Linked_List/206.Reverse-Linked-List/Readme.md b/Linked_List/206.Reverse-Linked-List/Readme.md new file mode 100644 index 000000000..494d430a5 --- /dev/null +++ b/Linked_List/206.Reverse-Linked-List/Readme.md @@ -0,0 +1,5 @@ +### 206.Reverse-Linked-List + +此题是链表操作的常规考题。我们维护一个滑窗,last,cur,nxt表示三个连续的node。初始的时候,last=NULL, cur=head, nxt=cur->next. 对于每一个滑窗,我们要做的仅仅就是把cur从指向nxt改为指向last。然后移动滑窗,更新last,cur,nxt所对应的节点. + +最终当cur==NULL是结束循环,此时反转链表之后的头指针就是last。 From 0bedfa044b9d5f2d1c1a2bb39eb5d5207832a76b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 16 Nov 2021 23:44:22 -0800 Subject: [PATCH 0169/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ca1b45f38..4d2843605 100644 --- a/Readme.md +++ b/Readme.md @@ -523,7 +523,7 @@ [1670.Design-Front-Middle-Back-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/1670.Design-Front-Middle-Back-Queue) (M+) [1756.Design-Most-Recently-Used-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/1756.Design-Most-Recently-Used-Queue) (H) * ``Reverse Linked List`` -206.Reverse Linked List (M) +[206.Reverse-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/206.Reverse-Linked-List) (M) [025.Reverse-Nodes-in-k-Group](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/025.Reverse-Nodes-in-k-Group) (H-) [092.Reverse-Linked-List-II](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/092.Reverse-Linked-List-II) (H-) [143.Reorder-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/143.Reorder-List) (H-) From d2ddaf8d1ae630a6c23e86bd00d2504cf6236a31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 17 Nov 2021 00:06:56 -0800 Subject: [PATCH 0170/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 4d2843605..df88bd55b 100644 --- a/Readme.md +++ b/Readme.md @@ -524,10 +524,10 @@ [1756.Design-Most-Recently-Used-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/1756.Design-Most-Recently-Used-Queue) (H) * ``Reverse Linked List`` [206.Reverse-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/206.Reverse-Linked-List) (M) -[025.Reverse-Nodes-in-k-Group](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/025.Reverse-Nodes-in-k-Group) (H-) [092.Reverse-Linked-List-II](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/092.Reverse-Linked-List-II) (H-) -[143.Reorder-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/143.Reorder-List) (H-) +[025.Reverse-Nodes-in-k-Group](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/025.Reverse-Nodes-in-k-Group) (H-) [2074.Reverse-Nodes-in-Even-Length-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups) (H-) +[143.Reorder-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/143.Reorder-List) (H-) #### [Dynamic Programming](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming) [264.Ugly-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/264.Ugly-Number-II) (H-) From 2fa6972110ce899dbbd827629f79ba1f5953c7c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Nov 2021 11:31:44 -0800 Subject: [PATCH 0171/2729] Create 092.Reverse-Linked-List-II_v2.cpp --- .../092.Reverse-Linked-List-II_v2.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Linked_List/092.Reverse-Linked-List-II/092.Reverse-Linked-List-II_v2.cpp diff --git a/Linked_List/092.Reverse-Linked-List-II/092.Reverse-Linked-List-II_v2.cpp b/Linked_List/092.Reverse-Linked-List-II/092.Reverse-Linked-List-II_v2.cpp new file mode 100644 index 000000000..7ff92189b --- /dev/null +++ b/Linked_List/092.Reverse-Linked-List-II/092.Reverse-Linked-List-II_v2.cpp @@ -0,0 +1,55 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseBetween(ListNode* head, int left, int right) + { + ListNode* dummy = new ListNode(0); + dummy->next = head; + + ListNode* p = dummy; + for (int i=0; inext; + ListNode* c = p->next; + p->next = NULL; + + p = dummy; + for (int i=0; inext; + ListNode* b = p->next; + p->next = NULL; + + b = reverseLinkedList(b); + + p = dummy; + while (p->next) p = p->next; + p->next = b; + while (p->next) p = p->next; + p->next = c; + + return dummy->next; + } + + ListNode* reverseLinkedList(ListNode* h) + { + ListNode* last = NULL; + ListNode* cur = h; + ListNode* nxt; + while (cur) + { + nxt = cur->next; + cur->next = last; + last = cur; + cur = nxt; + } + return last; + } +}; From 95c7f5b0e1644a050366da047dccab4dc2d4ba50 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Nov 2021 12:16:40 -0800 Subject: [PATCH 0172/2729] Update Readme.md --- Linked_List/092.Reverse-Linked-List-II/Readme.md | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/Linked_List/092.Reverse-Linked-List-II/Readme.md b/Linked_List/092.Reverse-Linked-List-II/Readme.md index 9da38a10c..53f19638c 100644 --- a/Linked_List/092.Reverse-Linked-List-II/Readme.md +++ b/Linked_List/092.Reverse-Linked-List-II/Readme.md @@ -1,13 +1,9 @@ ### 092.Reverse-Linked-List-II -本题比较考验对于链表操作的细节。 +本题的基本思路很明显,我们需要将原列表拆分为三部分。然后对中间一部分进行链表反转操作(参考 206.Reverse-Linked-List),最后将三部分拼接起来。 -我们先遍历到第m-1个和第m个节点。将第m-1个节点记为end_of_start,之后的next要重新指向逆序段的首节点。 +需要注意的是left和right可能很极限,也就是说原题可能本质上是反转整个链表。所以方便的处理方法是前面添加一个dummy节点,末尾也虚拟地认为有一个NULL节点。这样我们就一定能够把整个链表分为实实在在的三部分。然后应用上述的算法。 -从第m个节点到第n个节点,我们要做链表逆转的操作。基本的思想就是将向后指向的next,变更成向前指向。所以我们每操作一个cur,都要同时准确地知道prev和next。处理完之后,prev,cur,next都要正确地移动到下一个位置。最终处理完第n个节点后,此时的cur指向的是第n+1个节点,它就是第三段的首节点start_of_third,同时prev就是第二段的逆序的首节点。我们需要的操作是: -```cpp -end_of_first->next = start_of_third; -start_of_second->next = start_of_third; -``` +另外注意,所谓的将链表拆违三部分,并不是找到每一部分的首尾就完了,还要把尾节点的next置为NULL,这样才能形成一个单独的链表。否则可能会有各种意想不到的bug。 [Leetcode Link](https://leetcode.com/problems/reverse-linked-list-ii) From 27802a59ff1fb78eaa92467ac7cdb59d8258cda7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Nov 2021 14:09:47 -0800 Subject: [PATCH 0173/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index df88bd55b..90bb67a4f 100644 --- a/Readme.md +++ b/Readme.md @@ -524,8 +524,8 @@ [1756.Design-Most-Recently-Used-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/1756.Design-Most-Recently-Used-Queue) (H) * ``Reverse Linked List`` [206.Reverse-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/206.Reverse-Linked-List) (M) -[092.Reverse-Linked-List-II](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/092.Reverse-Linked-List-II) (H-) -[025.Reverse-Nodes-in-k-Group](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/025.Reverse-Nodes-in-k-Group) (H-) +[092.Reverse-Linked-List-II](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/092.Reverse-Linked-List-II) (M+) +[025.Reverse-Nodes-in-k-Group](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/025.Reverse-Nodes-in-k-Group) (M+) [2074.Reverse-Nodes-in-Even-Length-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups) (H-) [143.Reorder-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/143.Reorder-List) (H-) From f2f398e796449a3a4d133e7aec082376d1e02863 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 11:16:24 -0800 Subject: [PATCH 0174/2729] Update Readme.md --- .../1942.The-Number-of-the-Smallest-Unoccupied-Chair/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair/Readme.md b/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair/Readme.md index 59a08f742..a94169ef5 100644 --- a/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair/Readme.md +++ b/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair/Readme.md @@ -1,6 +1,6 @@ ### 1942.The-Number-of-the-Smallest-Unoccupied-Chair -times的数据规模不超过10000,说明椅子数量的上限就是10000. 我们可以将编号0到10000的椅子放进一个优先队列empty里面,按照ID从小到大依次弹出,按照使用人的先后顺序分配。 +times的数据规模不超过10000,说明椅子数量的上限就是10000. 我们可以将编号0到times.size()-1的椅子放进一个优先队列empty里面,按照ID从小到大依次弹出,按照使用人的先后顺序分配。 被分配出去的椅子,又要按照使用完毕的时间放回empty里面。所以我们会将所有正在使用的椅子放入一个按照结束时间排序的优先队列used。每次在empty分发椅子之前,先要查看一下当前时刻,从used里面调出那些该时刻已经结束使用的椅子,将ID塞回empty里。然后再从used里弹出ID最小的ID给人使用。 From 041cd44b5cbc3eb5a7c35cb4cd9818e01eb00e3c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 11:17:03 -0800 Subject: [PATCH 0175/2729] Update 1942.The-Number-of-the-Smallest-Unoccupied-Chair.cpp --- .../1942.The-Number-of-the-Smallest-Unoccupied-Chair.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair/1942.The-Number-of-the-Smallest-Unoccupied-Chair.cpp b/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair/1942.The-Number-of-the-Smallest-Unoccupied-Chair.cpp index 0b3859509..40c15ff80 100644 --- a/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair/1942.The-Number-of-the-Smallest-Unoccupied-Chair.cpp +++ b/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair/1942.The-Number-of-the-Smallest-Unoccupied-Chair.cpp @@ -4,7 +4,7 @@ class Solution { int smallestChair(vector>& times, int targetFriend) { priority_queue, greater<>>empty; - for (int i=0; i<10005; i++) + for (int i=0; i Date: Sun, 21 Nov 2021 11:47:43 -0800 Subject: [PATCH 0176/2729] Create 025.Reverse-Nodes-in-k-Group_v2.cpp --- .../025.Reverse-Nodes-in-k-Group_v2.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Linked_List/025.Reverse-Nodes-in-k-Group/025.Reverse-Nodes-in-k-Group_v2.cpp diff --git a/Linked_List/025.Reverse-Nodes-in-k-Group/025.Reverse-Nodes-in-k-Group_v2.cpp b/Linked_List/025.Reverse-Nodes-in-k-Group/025.Reverse-Nodes-in-k-Group_v2.cpp new file mode 100644 index 000000000..a0402abf9 --- /dev/null +++ b/Linked_List/025.Reverse-Nodes-in-k-Group/025.Reverse-Nodes-in-k-Group_v2.cpp @@ -0,0 +1,62 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) + { + vectorheads; + ListNode* p = head; + + int flag = 1; + while (p) + { + heads.push_back(p); + + for (int i=0; inext) p = p->next; + else flag = 0; + } + + ListNode* nxt = p->next; + p->next = NULL; + p = nxt; + } + + for (int i=0; inext) h = h->next; + h->next = heads[i+1]; + } + + return heads[0]; + } + + ListNode* reverseLinkedList(ListNode* h) + { + ListNode* last = NULL; + ListNode* cur = h; + ListNode* nxt; + while (cur) + { + nxt = cur->next; + cur->next = last; + last = cur; + cur = nxt; + } + return last; + } +}; From 0547f99227c4f6ccc62b1f917a7e5f54b332a8a0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 15:42:41 -0800 Subject: [PATCH 0177/2729] Update 143.Reorder-List.cpp --- .../143.Reorder-List/143.Reorder-List.cpp | 84 ++++++++++--------- 1 file changed, 46 insertions(+), 38 deletions(-) diff --git a/Linked_List/143.Reorder-List/143.Reorder-List.cpp b/Linked_List/143.Reorder-List/143.Reorder-List.cpp index 4b8100e2a..9ae6db726 100644 --- a/Linked_List/143.Reorder-List/143.Reorder-List.cpp +++ b/Linked_List/143.Reorder-List/143.Reorder-List.cpp @@ -3,57 +3,65 @@ * struct ListNode { * int val; * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: void reorderList(ListNode* head) { - if (head==NULL || head->next==NULL) - return; - - ListNode* h=new ListNode(0); - h->next=head; - - ListNode* p=h; - int count=0; - while (p->next!=NULL) + ListNode* dummy = new ListNode(0); + dummy->next = head; + + ListNode* p = dummy; + int count = 0; + while (p->next) { - p=p->next; count++; - } - p=h; - for (int i=0; i<(count-count/2); i++) - p=p->next; - - ListNode* temp=p->next; - p->next=NULL; - p=temp; - ListNode* q=NULL; - while (p!=NULL) - { - ListNode* temp=p->next; - p->next=q; - q=p; - p=temp; + p = p->next; } - - p=head; - while (p!=NULL || q!=NULL) + + ListNode* q = dummy; + for (int i=0; i<(count+1)/2; i++) + q = q->next; + ListNode* head2 = q->next; + q->next = NULL; + + head2 = reverseLinkedList(head2); + + p = head, q = head2; + ListNode* h = dummy; + while (p || q) { - if (p!=NULL) + if (p) { - h->next=p; - h=h->next; - p=p->next; + h->next = p; + p = p->next; + h = h->next; } - if (q!=NULL) + if (q) { - h->next=q; - h=h->next; - q=q->next; + h->next = q; + q = q->next; + h = h->next; } - } + } + } + + ListNode* reverseLinkedList(ListNode* head) + { + ListNode* cur = head; + ListNode* last = NULL; + ListNode* next = NULL; + while (cur!=NULL) + { + next = cur->next; + cur->next = last; + last = cur; + cur = next; + } + return last; } }; From 62e453b27ea76692a2b9717afaf46fbfd52a4bea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 15:44:11 -0800 Subject: [PATCH 0178/2729] Update Readme.md --- Linked_List/143.Reorder-List/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Linked_List/143.Reorder-List/Readme.md b/Linked_List/143.Reorder-List/Readme.md index 5e66aeefc..0be7e8cab 100644 --- a/Linked_List/143.Reorder-List/Readme.md +++ b/Linked_List/143.Reorder-List/Readme.md @@ -2,9 +2,9 @@ 此题不难,但是比较繁琐,需要耐心理清思路,细致地操作指针。 -其中对于一段链表进行逆序操作的基本算法是:不断从源链表首摘下一个节点(同时指针后移),拼接到目标链表首(同时指针前移)。 +本题的算法是,先求得整体的长度count。于是我们将整个链表分割为两部分:前者有(count+1)/2个节点;后者再进行反转链表的操作。 -得到两段链表之后,交替摘取节点拼接到新链表上。 +得到这两段链表之后,交替摘取节点拼接到新链表上。 -[Leetcode Link](https://leetcode.com/problems/reorder-list) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/reorder-list) From 93f26010ad774eca9f4409af6685a1bf65ff3eb5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 16:52:16 -0800 Subject: [PATCH 0179/2729] Create 2036.Maximum-Alternating-Subarray-Sum.cpp --- .../2036.Maximum-Alternating-Subarray-Sum.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/2036.Maximum-Alternating-Subarray-Sum.cpp diff --git a/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/2036.Maximum-Alternating-Subarray-Sum.cpp b/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/2036.Maximum-Alternating-Subarray-Sum.cpp new file mode 100644 index 000000000..d5d190daa --- /dev/null +++ b/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/2036.Maximum-Alternating-Subarray-Sum.cpp @@ -0,0 +1,22 @@ +using LL = long long; +class Solution { +public: + long long maximumAlternatingSubarraySum(vector& nums) + { + LL ret = INT_MIN; + LL curSum0 = INT_MIN; + LL curSum1 = 0; + + for (LL x: nums) + { + LL curSum0_temp = curSum0; + LL curSum1_temp = curSum1; + curSum0 = max(curSum1_temp + x, x); + curSum1 = curSum0_temp - x; + + ret = max(ret, curSum0); + ret = max(ret, curSum1); + } + return ret; + } +}; From 90631ae12c42a501dee8552ac58f7bcb70c5d032 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 16:52:44 -0800 Subject: [PATCH 0180/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 90bb67a4f..2803cb93e 100644 --- a/Readme.md +++ b/Readme.md @@ -591,6 +591,7 @@ [1824.Minimum-Sideway-Jumps](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1824.Minimum-Sideway-Jumps) (M) [1839.Longest-Substring-Of-All-Vowels-in-Order](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1839.Longest-Substring-Of-All-Vowels-in-Order) (M) [1883.Minimum-Skips-to-Arrive-at-Meeting-On-Time](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1883.Minimum-Skips-to-Arrive-at-Meeting-On-Time) (H) +[2036.Maximum-Alternating-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum) (M+) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From db01bd5d3b0719ec032cfd149a9ab621ade89d5c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 17:14:18 -0800 Subject: [PATCH 0181/2729] Create Readme.md --- .../2036.Maximum-Alternating-Subarray-Sum/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md diff --git a/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md b/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md new file mode 100644 index 000000000..e5ba4ca45 --- /dev/null +++ b/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md @@ -0,0 +1,9 @@ +### 2036.Maximum-Alternating-Subarray-Sum + +我们定义两个状态,curSum0[i]表示以元素i结尾、并且元素i本身未被符号翻转的情况下,能够得到的max subarray sum. 同理,curSum1[i]表示以元素i结尾、并且元素i本身已经被符号翻转的情况下,能够得到的max subarray sum. + +对于curSum0[i],它两种可能。要么只有仅包含单个元素+nums[i]。要么需要和前面的subarray连起来使用,显然能与+nums[i]连在一起的,必然是curSum1[i-1]. 所以```curSum0[i] = max(nums[i], curSum1[i-1]+nums[i]```. + +对于curSum1[i],它其实只有一种可能,即需要和前面的subarray连起来使用。这是因为题目不允许subarray的开头是一个符号反转的元素。所以必然-nums[i]要与curSum0[i-1]连在一起. 所以```curSum1[i] = curSum0[i-1]-nums[i]```. + +此外特别注意,对于边界条件,curSum1[-1]可以是0,但是curSum0[-1]必须设置为无穷小。这是因为nums[0]只能作为一个subarray的开头,它不能被符号翻转,所以```curSum1[0] = curSum0[-1]-nums[i]```没有意义。 From 3a80cbb2b4f9c07c8ecdb879d7e5efd5ebb35ba0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 17:16:23 -0800 Subject: [PATCH 0182/2729] Update Readme.md --- .../2036.Maximum-Alternating-Subarray-Sum/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md b/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md index e5ba4ca45..b34210189 100644 --- a/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md +++ b/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md @@ -1,6 +1,6 @@ ### 2036.Maximum-Alternating-Subarray-Sum -我们定义两个状态,curSum0[i]表示以元素i结尾、并且元素i本身未被符号翻转的情况下,能够得到的max subarray sum. 同理,curSum1[i]表示以元素i结尾、并且元素i本身已经被符号翻转的情况下,能够得到的max subarray sum. +我们定义两个状态,curSum0[i]表示以元素i结尾、并且元素i本身未被符号翻转的情况下(即+nums[i]),能够得到的max subarray sum. 同理,curSum1[i]表示以元素i结尾、并且元素i本身已经被符号翻转的情况下(即-nums[i]),能够得到的max subarray sum. 对于curSum0[i],它两种可能。要么只有仅包含单个元素+nums[i]。要么需要和前面的subarray连起来使用,显然能与+nums[i]连在一起的,必然是curSum1[i-1]. 所以```curSum0[i] = max(nums[i], curSum1[i-1]+nums[i]```. From 74977b4158ca2b8276ff95dc632977c7e297e90e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 17:17:40 -0800 Subject: [PATCH 0183/2729] Update Readme.md --- .../2036.Maximum-Alternating-Subarray-Sum/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md b/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md index b34210189..c5dc0b158 100644 --- a/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md +++ b/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum/Readme.md @@ -2,8 +2,8 @@ 我们定义两个状态,curSum0[i]表示以元素i结尾、并且元素i本身未被符号翻转的情况下(即+nums[i]),能够得到的max subarray sum. 同理,curSum1[i]表示以元素i结尾、并且元素i本身已经被符号翻转的情况下(即-nums[i]),能够得到的max subarray sum. -对于curSum0[i],它两种可能。要么只有仅包含单个元素+nums[i]。要么需要和前面的subarray连起来使用,显然能与+nums[i]连在一起的,必然是curSum1[i-1]. 所以```curSum0[i] = max(nums[i], curSum1[i-1]+nums[i]```. +对于curSum0[i],它两种可能。要么subarray仅包含单个元素+nums[i]。要么需要把+nums[i]和前面的subarray连起来使用:显然能与+nums[i]连在一起的,必然是curSum1[i-1]. 所以```curSum0[i] = max(nums[i], curSum1[i-1]+nums[i]```. -对于curSum1[i],它其实只有一种可能,即需要和前面的subarray连起来使用。这是因为题目不允许subarray的开头是一个符号反转的元素。所以必然-nums[i]要与curSum0[i-1]连在一起. 所以```curSum1[i] = curSum0[i-1]-nums[i]```. +对于curSum1[i],它其实只有一种可能,即需要和前面的subarray连起来使用。这是因为题目不允许subarray的开头是一个符号反转的元素。所以-nums[i]必须curSum0[i-1]连在一起. 所以```curSum1[i] = curSum0[i-1]-nums[i]```. 此外特别注意,对于边界条件,curSum1[-1]可以是0,但是curSum0[-1]必须设置为无穷小。这是因为nums[0]只能作为一个subarray的开头,它不能被符号翻转,所以```curSum1[0] = curSum0[-1]-nums[i]```没有意义。 From 11de177a47741c38bd723bc0dfe7f66e6a71d09f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 17:35:13 -0800 Subject: [PATCH 0184/2729] Create 2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values.cpp --- ...t-Already-Sorted-Using-Absolute-Values.cpp | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values.cpp diff --git a/Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values.cpp b/Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values.cpp new file mode 100644 index 000000000..a9d5dcec2 --- /dev/null +++ b/Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values.cpp @@ -0,0 +1,71 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* sortLinkedList(ListNode* head) + { + + ListNode* pos = new ListNode(0); + ListNode* neg = new ListNode(0); + ListNode* h = head; + ListNode* p1 = pos; + ListNode* p2 = neg; + + while (h) + { + if (h->val>=0) + { + p1->next = h; + h = h->next; + p1 = p1->next; + + } + else + { + p2->next = h; + h = h->next; + p2 = p2->next; + } + } + p1->next = NULL; + p2->next = NULL; + + pos = pos->next; + neg = neg->next; + + neg = reverseLinkedList(neg); + + if (neg) + { + h = neg; + while (h->next) h = h->next; + h->next = pos; + return neg; + } + else + return pos; + } + + ListNode* reverseLinkedList(ListNode* head) + { + ListNode* cur = head; + ListNode* last = NULL; + ListNode* next = NULL; + while (cur!=NULL) + { + next = cur->next; + cur->next = last; + last = cur; + cur = next; + } + return last; + } +}; From 3d350581b1ba7626c956b9f3efb13dd54ba83b71 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 17:35:43 -0800 Subject: [PATCH 0185/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 2803cb93e..48c4fae67 100644 --- a/Readme.md +++ b/Readme.md @@ -528,6 +528,7 @@ [025.Reverse-Nodes-in-k-Group](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/025.Reverse-Nodes-in-k-Group) (M+) [2074.Reverse-Nodes-in-Even-Length-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/2074.Reverse-Nodes-in-Even-Length-Groups) (H-) [143.Reorder-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/143.Reorder-List) (H-) +[2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values) (H-) #### [Dynamic Programming](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming) [264.Ugly-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/264.Ugly-Number-II) (H-) From a618066fc00d24956e4f9ee02846f15661ed18ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 18:26:43 -0800 Subject: [PATCH 0186/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values/Readme.md diff --git a/Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values/Readme.md b/Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values/Readme.md new file mode 100644 index 000000000..9e05a49d2 --- /dev/null +++ b/Linked_List/2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values/Readme.md @@ -0,0 +1,5 @@ +### 2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values + +本题的突破点在于,我们可以发现所有的正数都是从小到大排列的,所有的负数也是从大到小排列的。我们把所有的正数、负数节点分别拿出来组成两个链表,显然只需要把负数链表反转再接上正数链表就是答案了。 + +这种“按照绝对值升序排列”的序列有很多有意思的题目。比如说,在这样的一个数组里,能否用o(N)的时间判断是否存在two sum等于target。 From fe801dc651a04127ebb68671c01b5cb649d4a884 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 22:54:15 -0800 Subject: [PATCH 0187/2729] Create 206.Reverse-Linked-List_Recursion.cpp --- .../206.Reverse-Linked-List_Recursion.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Linked_List/206.Reverse-Linked-List/206.Reverse-Linked-List_Recursion.cpp diff --git a/Linked_List/206.Reverse-Linked-List/206.Reverse-Linked-List_Recursion.cpp b/Linked_List/206.Reverse-Linked-List/206.Reverse-Linked-List_Recursion.cpp new file mode 100644 index 000000000..4602779ae --- /dev/null +++ b/Linked_List/206.Reverse-Linked-List/206.Reverse-Linked-List_Recursion.cpp @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) + { + return helper(NULL, head); + } + + ListNode* helper(ListNode*last, ListNode* head) + { + if (head==NULL) return last; + ListNode* nxt = head->next; + head->next = last; + return helper(head, nxt); + } +}; From f4225fa4243102b39e5558a54ef3b37ee7015fab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 23:34:23 -0800 Subject: [PATCH 0188/2729] Create 2052.Minimum-Cost-to-Separate-Sentence-Into-Rows.cpp --- ...um-Cost-to-Separate-Sentence-Into-Rows.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows.cpp diff --git a/Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows.cpp b/Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows.cpp new file mode 100644 index 000000000..b9826cdad --- /dev/null +++ b/Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minimumCost(string sentence, int k) + { + vectornums; + for (int i=0; idp(n+1, INT_MAX/2); + dp[0] = 0; + for (int i=1; i<=n; i++) + { + int len = -1; + int j = i; + while (j>=1 && len+nums[j]+1 <= k) + { + len += nums[j]+1; + dp[i] = min(dp[i], dp[j-1]+(k-len)*(k-len)); + + if (i==n) ret = min(ret, dp[j-1]); + j--; + } + } + + return ret; + } +}; From 544a83dbfee3c089b9f4405df383367e57dc3eb2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 23:39:47 -0800 Subject: [PATCH 0189/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 48c4fae67..b764a04ce 100644 --- a/Readme.md +++ b/Readme.md @@ -602,6 +602,7 @@ [1043.Partition-Array-for-Maximum-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1043.Partition-Array-for-Maximum-Sum)(M+) [1105.Filling-Bookcase-Shelves](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1105.Filling-Bookcase-Shelves) (H-) [1959.minimum-total-space-wasted-with-k-resizing-operations](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1959.minimum-total-space-wasted-with-k-resizing-operations) (H-) +[2052.Minimum-Cost-to-Separate-Sentence-Into-Rows](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows) (H-) [1416.Restore-The-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1416.Restore-The-Array) (M+) [1546.Maximum-Number-of-Non-Overlapping-Subarrays-With-Sum-Equals-Target](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1546.Maximum-Number-of-Non-Overlapping-Subarrays-With-Sum-Equals-Target) (M+) [1626.Best-Team-With-No-Conflicts](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1626.Best-Team-With-No-Conflicts) (M) From 19504e64534fe3df9b11ac89cc3fda3ed147ccd3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Nov 2021 23:45:03 -0800 Subject: [PATCH 0190/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows/Readme.md diff --git a/Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows/Readme.md b/Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows/Readme.md new file mode 100644 index 000000000..331c6ba66 --- /dev/null +++ b/Dynamic_Programming/2052.Minimum-Cost-to-Separate-Sentence-Into-Rows/Readme.md @@ -0,0 +1,7 @@ +### 2052.Minimum-Cost-to-Separate-Sentence-Into-Rows + +首先计算每个单词的长度,放入数组nums. + +令dp[i]表前i个单词所需要的最小cost是多少。显然我们会考虑i所在的行的第一个单词j的选择,这样就有```dp[i] = dp[j-1] + cost(k, len[j:i], (i-j)) ```,其中len[j:i]表示第j个到第i个单词的总词长,(i-j)表示该行需要的空格长度。其中我们令j从i开始,从后往前遍历,直至不满足```len[j:i]+(i-j)<=k``` + +特别注意,本题中的cost不包含最后一行。因此我们在计算i=n的时候,答案就是此时所有合法dp[j-1]中的最小值。 From 82c2eec44dd212ba8397c48288b998e45c09aeb1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 23 Nov 2021 23:13:20 -0800 Subject: [PATCH 0191/2729] Create 2061.Number-of-Spaces-Cleaning-Robot-Cleaned.cpp --- ...umber-of-Spaces-Cleaning-Robot-Cleaned.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned/2061.Number-of-Spaces-Cleaning-Robot-Cleaned.cpp diff --git a/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned/2061.Number-of-Spaces-Cleaning-Robot-Cleaned.cpp b/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned/2061.Number-of-Spaces-Cleaning-Robot-Cleaned.cpp new file mode 100644 index 000000000..85dd1e392 --- /dev/null +++ b/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned/2061.Number-of-Spaces-Cleaning-Robot-Cleaned.cpp @@ -0,0 +1,35 @@ +class Solution { + int visited[300][300][4]; + int cleaned[300][300]; +public: + int numberOfCleanRooms(vector>& room) + { + int m = room.size(), n = room[0].size(); + vector>dir = {{0,1},{1,0},{0,-1},{-1,0}}; + int x = 0, y = 0, d = 0; + int ret = 0; + while (visited[x][y][d]==0) + { + if (cleaned[x][y]==0) + { + ret++; + cleaned[x][y] = 1; + } + + visited[x][y][d]=1; + + int i = x+dir[d].first; + int j = y+dir[d].second; + if (i>=m||i<0||j>=n||j<0||room[i][j]==1) + { + d = (d+1)%4; + } + else + { + x = i; + y = j; + } + } + return ret; + } +}; From a2de2ff99c52ba53914caef86e94b13a45f6453a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 23 Nov 2021 23:16:27 -0800 Subject: [PATCH 0192/2729] Create Readme.md --- .../2061.Number-of-Spaces-Cleaning-Robot-Cleaned/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned/Readme.md diff --git a/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned/Readme.md b/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned/Readme.md new file mode 100644 index 000000000..48e9b7aca --- /dev/null +++ b/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned/Readme.md @@ -0,0 +1,5 @@ +### 2061.Number-of-Spaces-Cleaning-Robot-Cleaned + +本题就是完全模拟机器人的轨迹,统计哪些格子被第一次访问。 + +我们还需要记录每一步的{x坐标、y坐标、朝向}这个三元对。当某个三元对重复出现时,说明之后的轨迹将会进入一个循环,就可以终止模拟了。 From c7b1231d2f7ff4cfdf29a0eac7aefaa65145d3c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 23 Nov 2021 23:17:04 -0800 Subject: [PATCH 0193/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b764a04ce..302545e47 100644 --- a/Readme.md +++ b/Readme.md @@ -1080,7 +1080,8 @@ [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) [932.Beautiful-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/932.Beautiful-Array) (H) -#### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation)   +#### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) +[2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) [2069.Walking-Robot-Simulation-II](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2069.Walking-Robot-Simulation-II) (M+) #### [Others](https://github.com/wisdompeak/LeetCode/tree/master/Others)   From 50f421b37761e5c06e9c24a6bc3e4d680e2ef0fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 24 Nov 2021 16:07:31 -0800 Subject: [PATCH 0194/2729] Create 2081.Sum-of-k-Mirror-Numbers.cpp --- .../2081.Sum-of-k-Mirror-Numbers.cpp | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Others/2081.Sum-of-k-Mirror-Numbers/2081.Sum-of-k-Mirror-Numbers.cpp diff --git a/Others/2081.Sum-of-k-Mirror-Numbers/2081.Sum-of-k-Mirror-Numbers.cpp b/Others/2081.Sum-of-k-Mirror-Numbers/2081.Sum-of-k-Mirror-Numbers.cpp new file mode 100644 index 000000000..39c9a20c1 --- /dev/null +++ b/Others/2081.Sum-of-k-Mirror-Numbers/2081.Sum-of-k-Mirror-Numbers.cpp @@ -0,0 +1,81 @@ +using LL = long long; +class Solution { + int temp[100]; +public: + long long kMirror(int k, int n) + { + int d = 1; + vectorrets; + + while (1) + { + if (d%2==0) + { + int len = d/2; + for (LL i=pow(10, len-1); i0) + { + count++; + z = z*10+(y%10); + y/=10; + } + + if (flag==1) x /= 10; + + for (int i=0; i0) + { + temp[t] = x%k; + x/=k; + t++; + } + int i = 0, j = t-1; + while (i Date: Wed, 24 Nov 2021 16:08:39 -0800 Subject: [PATCH 0195/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 302545e47..4c82e921d 100644 --- a/Readme.md +++ b/Readme.md @@ -1144,6 +1144,7 @@ [479.Largest-Palindrome-Product](https://github.com/wisdompeak/LeetCode/tree/master/Others/479.Largest-Palindrome-Product) (M+) [866.Prime-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Others/866.Prime-Palindrome) (H-) [906.Super-Palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Others/906.Super-Palindromes) (H-) +[2081.Sum-of-k-Mirror-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2081.Sum-of-k-Mirror-Numbers) (H-) [795.Number-of-Subarrays-with-Bounded-Maximum](https://github.com/wisdompeak/LeetCode/tree/master/Others/795.Number-of-Subarrays-with-Bounded-Maximum) (M+) [1625.Lexicographically-Smallest-String-After-Applying-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Others/1625.Lexicographically-Smallest-String-After-Applying-Operations) (H-) [1714.Sum-Of-Special-Evenly-Spaced-Elements-In-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1714.Sum-Of-Special-Evenly-Spaced-Elements-In-Array) (H) From 3d82e8f8df97fafea9621fa85b4d2a661ce2aeb7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 24 Nov 2021 17:03:17 -0800 Subject: [PATCH 0196/2729] Create Readme.md --- Others/2081.Sum-of-k-Mirror-Numbers/Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Others/2081.Sum-of-k-Mirror-Numbers/Readme.md diff --git a/Others/2081.Sum-of-k-Mirror-Numbers/Readme.md b/Others/2081.Sum-of-k-Mirror-Numbers/Readme.md new file mode 100644 index 000000000..565d4e3c7 --- /dev/null +++ b/Others/2081.Sum-of-k-Mirror-Numbers/Readme.md @@ -0,0 +1,21 @@ +### 2081.Sum-of-k-Mirror-Numbers + +本题本质就是从小到大枚举10进制和k进制都是回文形态的数。对于关于回文数的题目,最常见的做法就是枚举。类似的题目还有479,866,906。 + +对于任何十进制的数字xyz,我们只要翻转一下,就能得到两种回文数,xyzyx和xyzzyx。并且我们发现,对于从小到大的xyz,我们所构造的回文数也一定是从小到大递增的。更具体的说,我们从小到大遍历所有的xyz,那么就能得到从小到大所有的五位数的回文数xyzyx,同时还可以得到从小到大所有的六位数的回文数xyzzyx。依次类推。所以我们本质上就得到了所有从小到大所有的十进制回文数,只需再检查一下他们在k进制形态下是否是回文即可。 + +那么我们是否可以反过来做,遍历所有从小到大的k进制回文数,再查验是否是十进制回文数呢?理论上可以的:你先从小到大生成10进制数、再转为k进制数、再镜像翻转。 但是有点需要思考的地方。因为k小于10,遍历k进制回文数的效率不及遍历十进制回文数的效率高。k越小,在相同范围内,k进制的数字就越长,回文数概率就越高。比如十进制的两位数,只有11-99这9种回文数。但是对应的二进制表示却是从1010到1100011:期间有(部分)四位数的回文、(任意)五位数的回文、(任意)六位数的回文、(部分)七位数的回文。显然,在需要满足既是k进制回文、又是10进制回文的前提下,我们遍历10进制回文数需要尝试的次数更少。 + +此外还有一个具体的实现细节。如何高效实现镜像翻转?即如何由xyz得到zyx?不要用数组来拆解每一个digit,用如下的数学方法: +```cpp +LL reverse(LL a) +{ + LL b = 0; + while (a>0) + { + b = b*10 + a%10; + a /= 10; + } + return b; +} +``` From 63b0a08d76f3b8f9084b09a9ec2a8cb1922a1d33 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 24 Nov 2021 17:19:45 -0800 Subject: [PATCH 0197/2729] Update 2081.Sum-of-k-Mirror-Numbers.cpp --- .../2081.Sum-of-k-Mirror-Numbers.cpp | 50 ++++++++----------- 1 file changed, 20 insertions(+), 30 deletions(-) diff --git a/Others/2081.Sum-of-k-Mirror-Numbers/2081.Sum-of-k-Mirror-Numbers.cpp b/Others/2081.Sum-of-k-Mirror-Numbers/2081.Sum-of-k-Mirror-Numbers.cpp index 39c9a20c1..2d3a7dd31 100644 --- a/Others/2081.Sum-of-k-Mirror-Numbers/2081.Sum-of-k-Mirror-Numbers.cpp +++ b/Others/2081.Sum-of-k-Mirror-Numbers/2081.Sum-of-k-Mirror-Numbers.cpp @@ -3,42 +3,32 @@ class Solution { int temp[100]; public: long long kMirror(int k, int n) - { - int d = 1; + { + int len = 1; vectorrets; - + while (1) - { - if (d%2==0) + { + for (LL i = pow(10, len-1); i < pow(10, len); i++) { - int len = d/2; - for (LL i=pow(10, len-1); i Date: Thu, 25 Nov 2021 23:30:21 -0800 Subject: [PATCH 0198/2729] Create 2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp --- ...nt-Subarrays-With-More-Ones-Than-Zeros.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp diff --git a/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp b/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp new file mode 100644 index 000000000..08aac66cd --- /dev/null +++ b/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp @@ -0,0 +1,55 @@ +const int MAX_N = 200003; +using LL = long long; + +class Solution { + int OFFSET = 100001; + long long bitArr[MAX_N]; + long long nums[MAX_N]; // Note: nums is 1-index + long long M = 1e9+7; + + // increase nums[i] by delta (1-index) + void updateDelta(int i, long long delta) { + int idx = i; + while (idx <= MAX_N) + { + bitArr[idx]+=delta; + bitArr[idx] %= M; + idx+=idx&(-idx); + } + } + + // sum of a range nums[1:j] inclusively, 1-index + long long queryPreSum(int idx){ + long long result = 0; + while (idx){ + result += bitArr[idx]; + result %= M; + idx-=idx&(-idx); + } + return result; + } + + // sum of a range nums[i:j] inclusively + long long sumRange(int i, int j) { + return queryPreSum(j)-queryPreSum(i-1); + } + +public: + int subarraysWithMoreZerosThanOnes(vector& nums) + { + cout< Date: Thu, 25 Nov 2021 23:30:55 -0800 Subject: [PATCH 0199/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4c82e921d..8ec5b6c5e 100644 --- a/Readme.md +++ b/Readme.md @@ -266,6 +266,7 @@ #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) [1649.Create-Sorted-Array-through-Instructions](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions) (H) +[2031.Count-Subarrays-With-More-Ones-Than-Zeros](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros) (H) #### [Design](https://github.com/wisdompeak/LeetCode/tree/master/Design) [146.LRU-Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/146.LRU-Cache) (H-) From 23aa611a52b95d3471e01bc0452538a6f80ee18d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 26 Nov 2021 00:47:58 -0800 Subject: [PATCH 0200/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/Readme.md diff --git a/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/Readme.md b/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/Readme.md new file mode 100644 index 000000000..8f9c82055 --- /dev/null +++ b/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/Readme.md @@ -0,0 +1,11 @@ +### 2031.Count-Subarrays-With-More-Ones-Than-Zeros + +对于区间的问题,我们很容想到尝试前缀和。我们令diff[i]表示前i个数字里元素1与元素0个数之差。那么对于以i为右边界的合法区间,我们希望它对应的左边界位置j有什么性质呢?显然,我们希望```diff[j] < diff[i]```即可。这样从[j+1:i]这个区间里的元素1一定比0多。有多少个这样的j,就有多少个以i为右边界的合法区间。 + +那么有多少个j满足这个条件呢?我们显然需要在i之前,记录下所有diff[j]的值并且统计频次,并且累加那些差值小于diff[i]的频次。 + +比如,我们令nums[k]表示diff为k出现的频次,即有多少个j,满足长度为j的前缀区间里元素1与元素0个数之差为k。对于每一个右边界为i的合法区间,我们需要累加```nums[0]+nums[1]+..+nums[diff[i]-1]```,这个数目就是左边界的数目。计算出这个答案之后,我们还需要更新```nums[diff[i]]+=1```,因为下一个回合的diff[i+1]会再次用到更新后的nums数组。 + +由此可见,我们需要一个数据结构,能够快速求出nums数组里的指定区间和(更确切地说是前缀和),同时也要支持对nums任意单点的高效修改。显然这样的数据结果,binary index tree是再合适不过了。 + +此题需要额外处理的一个问题的是:diff的数值范围可以是-10000到+10000,即我们需要记录从nums[-100000]到nums[+100000]。但是树状数组的index必须都是正数。所以我们需要一个```offset=1e5+1```,将差值[-1e5,1e5]映射到正数[1, 2e5+2]上。注意在这里的模板中,树状数组里有意义的元素下标从1开始。 From 4b78f4dac762cf061f272c93d510af1a983ad706 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 26 Nov 2021 01:12:50 -0800 Subject: [PATCH 0201/2729] Create 145.Binary-Tree-Postorder-Traversal_v2.cpp --- ...145.Binary-Tree-Postorder-Traversal_v2.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Tree/145.Binary-Tree-Postorder-Traversal/145.Binary-Tree-Postorder-Traversal_v2.cpp diff --git a/Tree/145.Binary-Tree-Postorder-Traversal/145.Binary-Tree-Postorder-Traversal_v2.cpp b/Tree/145.Binary-Tree-Postorder-Traversal/145.Binary-Tree-Postorder-Traversal_v2.cpp new file mode 100644 index 000000000..a8ebb9d33 --- /dev/null +++ b/Tree/145.Binary-Tree-Postorder-Traversal/145.Binary-Tree-Postorder-Traversal_v2.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector postorderTraversal(TreeNode* root) + { + vectorrets; + stack>Stack; + Stack.push({root, 0}); + + while (!Stack.empty()) + { + TreeNode* cur = Stack.top().first; + int rev = Stack.top().second; + Stack.pop(); + + if (cur==NULL) continue; + + if (rev==1) + rets.push_back(cur->val); + else + { + Stack.push({cur, 1}); + Stack.push({cur->right, 0}); + Stack.push({cur->left, 0}); + } + } + return rets; + } +}; From 9444a0eec8be2f1cb70cde8b454171093fc2301b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 14:02:22 -0800 Subject: [PATCH 0202/2729] Update 391.Perfect-Rectangle.cpp --- Math/391.Perfect-Rectangle/391.Perfect-Rectangle.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Math/391.Perfect-Rectangle/391.Perfect-Rectangle.cpp b/Math/391.Perfect-Rectangle/391.Perfect-Rectangle.cpp index 0c2d8d146..4be094335 100644 --- a/Math/391.Perfect-Rectangle/391.Perfect-Rectangle.cpp +++ b/Math/391.Perfect-Rectangle/391.Perfect-Rectangle.cpp @@ -9,7 +9,7 @@ class Solution { public: bool isRectangleCover(vector>& rectangles) { - int area=0; + long long area=0; unordered_setSet; for (int i=0; i Date: Sun, 28 Nov 2021 14:21:23 -0800 Subject: [PATCH 0203/2729] Create 2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses.cpp --- ...uired-to-Collect-Rainwater-from-Houses.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses.cpp diff --git a/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses.cpp b/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses.cpp new file mode 100644 index 000000000..8d9b61d74 --- /dev/null +++ b/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int minimumBuckets(string street) + { + int n = street.size(); + int ret = 0; + + for (int i=0; i=0 && street[i-1]=='#') + { + continue; + } + else if (i+1=0 && street[i-1]=='.') + { + street[i-1] = '#'; + ret++; + } + else + { + return -1; + } + } + + return ret; + } +}; From 198ec0e500888c1016ce1f131801d1f63228edcf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 14:30:44 -0800 Subject: [PATCH 0204/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/Readme.md diff --git a/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/Readme.md b/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/Readme.md new file mode 100644 index 000000000..7bbe4ff2f --- /dev/null +++ b/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses/Readme.md @@ -0,0 +1,9 @@ +### 2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses + +本题有纯粹的贪心策略。但凡遇到H,我们可定优先在右边放篮子,这样放置的篮子就可以最大程度地被后面的H所分享。当然,如果右边不能放置篮子的话,那么也只有在左边放了。 + +正确的逻辑顺序是: +1. 查看左边是否已经放置了篮子。有的话则skip +2. 查看右边是否可以放置篮子,是的话,就标记篮子 +3. 查看左边是否可以放置篮子,是的话,就标记篮子 +4. 此时说明左右都无法放置篮子,返回-1 From 9fcda4f63fffcff129f4140724dc0ec9f07051d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 14:31:09 -0800 Subject: [PATCH 0205/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8ec5b6c5e..df892c6f2 100644 --- a/Readme.md +++ b/Readme.md @@ -1010,6 +1010,7 @@ [1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number) (M+) [1911.Maximum-Alternating-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1911.Maximum-Alternating-Subsequence-Sum) (M+) [1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) +[2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From aee54e0d897b743e40523521e97d67c9489f6008 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 14:36:54 -0800 Subject: [PATCH 0206/2729] Create 2088.Count-Fertile-Pyramids-in-a-Land.cpp --- .../2088.Count-Fertile-Pyramids-in-a-Land.cpp | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/2088.Count-Fertile-Pyramids-in-a-Land.cpp diff --git a/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/2088.Count-Fertile-Pyramids-in-a-Land.cpp b/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/2088.Count-Fertile-Pyramids-in-a-Land.cpp new file mode 100644 index 000000000..8172c647b --- /dev/null +++ b/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/2088.Count-Fertile-Pyramids-in-a-Land.cpp @@ -0,0 +1,74 @@ +class Solution { +public: + int countPyramids(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + + vector>left(m, vector(n)); + vector>right(m, vector(n)); + vector>dp1(m, vector(n)); + vector>dp2(m, vector(n)); + + for (int i=0; i=0; j--) + { + if (grid[i][j]==0) + count = 0; + else + count +=1; + right[i][j] = count; + } + } + + int ret = 0; + for (int i=0; i=0; i--) + for (int j=0; j Date: Sun, 28 Nov 2021 14:37:32 -0800 Subject: [PATCH 0207/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index df892c6f2..703ccbd02 100644 --- a/Readme.md +++ b/Readme.md @@ -568,6 +568,7 @@ [1900.The-Earliest-and-Latest-Rounds-Where-Players-Compete](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1900.The-Earliest-and-Latest-Rounds-Where-Players-Compete) (H) [1937.Maximum-Number-of-Points-with-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1937.Maximum-Number-of-Points-with-Cost) (H-) [1955.Count-Number-of-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1955.Count-Number-of-Special-Subsequences) (H-) +[2088.Count-Fertile-Pyramids-in-a-Land](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From af3f469bd817df312d67dbf7bd6d76d9262a9b83 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 15:21:45 -0800 Subject: [PATCH 0208/2729] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/Readme.md diff --git a/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/Readme.md b/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/Readme.md new file mode 100644 index 000000000..1ab3f1a12 --- /dev/null +++ b/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/Readme.md @@ -0,0 +1,17 @@ +### 2088.Count-Fertile-Pyramids-in-a-Land + +如果我们想不重复地数金字塔,那么就必须抓住金字塔的特征。我们通过数特征来统计金字塔的数目。 + +我们最容易想到的是金字塔的顶尖。任何一个金字塔都有一个唯一的顶尖,我们可以考虑遍历每个格子,思考如果它作为某个金字塔的顶尖的话,可以代表哪些金字塔。显然,我们光看这个格子A本身是不充分,我们得看它往下一格B,查看B是否为一个长度为3的区间的中点;再查看B的下一格C,查看C是否为一个长度为5的区间的中点... 直至类似的规律不能再持续下去。我们往下几行,就意味着A可以是几个不同金字塔的塔尖。不过这样的时间复杂度将会是o(MMN). + +我们注意到,上述方法时间复杂度高是因为我们站在top,无法了解bottom的情况,所以才需要逐层下沉去调查。举个例子,我们知道某点A是一个三层金字塔的顶,那么它是否也是一个四层金字塔的顶呢?我们不知道,得下沉了才知道。 + +那么反过来会怎么样呢?我们站在下层,是否能知道上层的情况呢?这其实是可行的。比如说,我们站在某点A,如果知道它是一个三层金字塔的底座中点,那么我们就一定知道A也同时是一个二层金子它的底座中点。这样,如果考察每个点作为金字塔底座中点的情况,那么我们就不需要向上调查就能知道它可以对应几个不同的金字塔。这就方便多了。 + +那么对于任意一点A,我们如何可以知道它最大可以是多少层金字塔的底座中点呢?首先,我们要知道它自身可以是一个多长连续区间的中点。这个可以通过从左往右、从右往左两遍预处理得到。其次我们知道,如果A想成为一个三层金字塔的底座中点,那么A上面的那个格子B必须至少是一个两层金字塔的底座中点。所以我们对于A对应底座半径就有了如下的表达式: +``` +dp(A) = min(left(A), right(A), dp(B)+1) +``` +其中dp表示最大金字塔的底座半径,left表示A往左边最多连续多少个1,right表示A往右边最多连续多少个1. + +注意最终答案不能包括层数为1的金字塔,所以答案是累加所有格子的dp值减1. From 38743887d9ba1e2a915bbd6d28ada5498ee6e9a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 16:11:31 -0800 Subject: [PATCH 0209/2729] Update 2088.Count-Fertile-Pyramids-in-a-Land.cpp --- .../2088.Count-Fertile-Pyramids-in-a-Land.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/2088.Count-Fertile-Pyramids-in-a-Land.cpp b/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/2088.Count-Fertile-Pyramids-in-a-Land.cpp index 8172c647b..9eb356868 100644 --- a/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/2088.Count-Fertile-Pyramids-in-a-Land.cpp +++ b/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land/2088.Count-Fertile-Pyramids-in-a-Land.cpp @@ -18,7 +18,7 @@ class Solution { if (grid[i][j]==0) count = 0; else - count +=1; + count+=1; left[i][j] = count; } } @@ -31,7 +31,7 @@ class Solution { if (grid[i][j]==0) count = 0; else - count +=1; + count+=1; right[i][j] = count; } } @@ -43,13 +43,12 @@ class Solution { if (grid[i][j]==0) continue; if (i==0) { - if (grid[i][j]==1) dp1[i][j] = 1; - else dp1[i][j] = 0; + dp1[i][j] = 1; } else { - dp1[i][j] = min(dp1[i-1][j]+1, min(left[i][j], right[i][j])); - } + dp1[i][j] = min(min(left[i][j], right[i][j]), dp1[i-1][j]+1); + } ret += dp1[i][j]-1; } @@ -59,16 +58,16 @@ class Solution { if (grid[i][j]==0) continue; if (i==m-1) { - if (grid[i][j]==1) dp2[i][j] = 1; - else dp2[i][j] = 0; + dp2[i][j] = 1; } else { - dp2[i][j] = min(dp2[i+1][j]+1, min(left[i][j], right[i][j])); + dp2[i][j] = min(min(left[i][j], right[i][j]), dp2[i+1][j]+1); } ret += dp2[i][j]-1; } return ret; + } }; From 00c88384b3a66a4c5bb1fb234eb0c95b3426bd91 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 16:40:16 -0800 Subject: [PATCH 0210/2729] Create 2092.Find-All-People-With-Secret.cpp --- .../2092.Find-All-People-With-Secret.cpp | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Union_Find/2092.Find-All-People-With-Secret/2092.Find-All-People-With-Secret.cpp diff --git a/Union_Find/2092.Find-All-People-With-Secret/2092.Find-All-People-With-Secret.cpp b/Union_Find/2092.Find-All-People-With-Secret/2092.Find-All-People-With-Secret.cpp new file mode 100644 index 000000000..a8290eaff --- /dev/null +++ b/Union_Find/2092.Find-All-People-With-Secret/2092.Find-All-People-With-Secret.cpp @@ -0,0 +1,69 @@ +class Solution { + vectorFather; + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (x&a, vector&b) + { + return a[2] findAllPeople(int n, vector>& meetings, int firstPerson) + { + Father.resize(n); + for (int i=0; iSet; + Set.insert(0); + Set.insert(firstPerson); + Father[firstPerson] = 0; + for (int i=0; itemp; + + int j; + for (j=i; jrets(Set.begin(), Set.end()); + return rets; + + } +}; From d4642db3f6aa3271ea74cfca21978d408bbd5a31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 16:40:52 -0800 Subject: [PATCH 0211/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 703ccbd02..731a3d553 100644 --- a/Readme.md +++ b/Readme.md @@ -823,6 +823,7 @@ [803.Bricks-Falling-When-Hit](https://github.com/wisdompeak/LeetCode/tree/master/DFS/803.Bricks-Falling-When-Hit) (H) [1970.Last-Day-Where-You-Can-Still-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1970.Last-Day-Where-You-Can-Still-Cross) (H-) [2076.Process-Restricted-Friend-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2076.Process-Restricted-Friend-Requests) (H-) +[2092.Find-All-People-With-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2092.Find-All-People-With-Secret) (H-) * ``Prime Factors`` [952.Largest-Component-Size-by-Common-Factor](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/952.Largest-Component-Size-by-Common-Factor) (H) [1627.Graph-Connectivity-With-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1627.Graph-Connectivity-With-Threshold) (M+) From b563085dacc629f7531200924f491bb0330b7ca5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 17:00:01 -0800 Subject: [PATCH 0212/2729] Create Readme.md --- Union_Find/2092.Find-All-People-With-Secret/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Union_Find/2092.Find-All-People-With-Secret/Readme.md diff --git a/Union_Find/2092.Find-All-People-With-Secret/Readme.md b/Union_Find/2092.Find-All-People-With-Secret/Readme.md new file mode 100644 index 000000000..533cef199 --- /dev/null +++ b/Union_Find/2092.Find-All-People-With-Secret/Readme.md @@ -0,0 +1,9 @@ +### 2092.Find-All-People-With-Secret + +很直观的想法是将所有的meeting按照时间先后顺序排列。同时为一个集合来记录哪些人已经知道秘密。对于任何一个新meeting,如果有一方已经在这个集合里,那么另一方也就可以加入集合。 + +本题的难点在于如果有若干个会议的时间相同怎么办?对于一批同时间的会议,可能第一个会议的A和B都不知道,但是在第二个会议里B从C知道了这个秘密,那么根据规则A也会在此时刻知道这个秘密。加入第三个会议是A与D,那么D也应该知道秘密。 + +可见,对于同一时刻的会议,我们很难有个比较合适的处理顺序。当然,你可以用类似拓扑排序的思想:先处理有知情者的会议,然后扩大知情者的集合;再查看剩下的会议里还有哪些知情者,再处理掉这些会议,扩大知情者集合... 不过这样的代码,想要满足线性的时间,不见得好写。 + +考虑到在同一个时间的会议,知情人有着明显的传递性,用并查集是再适合不过的算法了。我们将凡是有会议的双方都union起来。最后查看这些新处理的人,是否有被union到了0(即所有知情人的祖先)。如果有,就加入集合;如果没有,记得撤销这个人的任何union操作,即```Father[i] = i```,因为在这个时刻两个人的union状态,不能带入下一个时刻。举个例子,四点钟A与B会面了。五点钟A知情了,但不意味着五点钟B就会知情。 From c08fbb6191264b027b85a3055f621f5b628ddbab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 17:00:59 -0800 Subject: [PATCH 0213/2729] Update 2092.Find-All-People-With-Secret.cpp --- .../2092.Find-All-People-With-Secret.cpp | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/Union_Find/2092.Find-All-People-With-Secret/2092.Find-All-People-With-Secret.cpp b/Union_Find/2092.Find-All-People-With-Secret/2092.Find-All-People-With-Secret.cpp index a8290eaff..e6146fe7e 100644 --- a/Union_Find/2092.Find-All-People-With-Secret/2092.Find-All-People-With-Secret.cpp +++ b/Union_Find/2092.Find-All-People-With-Secret/2092.Find-All-People-With-Secret.cpp @@ -41,16 +41,8 @@ class Solution { int a = meetings[j][0], b = meetings[j][1], t = meetings[j][2]; temp.insert(a); temp.insert(b); - if (Set.find(a)!=Set.end() || Set.find(b)!=Set.end()) - { - Union(FindFather(a),0); - Union(FindFather(b),0); - } - else - { - if (FindFather(a)!=FindFather(b)) - Union(a,b); - } + if (FindFather(a)!=FindFather(b)) + Union(a,b); } for (auto x: temp) From e077140188da8301dbdb8653b0bcd90ef3f71e2a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 18:00:24 -0800 Subject: [PATCH 0214/2729] Create 1801.Number-of-Orders-in-the-Backlog.cpp --- .../1801.Number-of-Orders-in-the-Backlog.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Design/1801.Number-of-Orders-in-the-Backlog/1801.Number-of-Orders-in-the-Backlog.cpp diff --git a/Design/1801.Number-of-Orders-in-the-Backlog/1801.Number-of-Orders-in-the-Backlog.cpp b/Design/1801.Number-of-Orders-in-the-Backlog/1801.Number-of-Orders-in-the-Backlog.cpp new file mode 100644 index 000000000..37b5af7a9 --- /dev/null +++ b/Design/1801.Number-of-Orders-in-the-Backlog/1801.Number-of-Orders-in-the-Backlog.cpp @@ -0,0 +1,53 @@ +typedef pair PII; //{price,amount} + +class Solution { +public: + int getNumberOfBacklogOrders(vector>& orders) + { + priority_queuebuy; + priority_queue, greater<>>sell; + + long ret = 0; + long M = 1e9+7; + + for (auto order: orders) + { + ret = (ret+order[1]) % M; + + if (order[2]==0) + { + while (order[1]>0 && !sell.empty() && sell.top().first <= order[0]) + { + auto [price, amount] = sell.top(); + sell.pop(); + long num = min(amount, (long)order[1]); + amount-=num; + order[1]-=num; + ret = (ret - num*2 + M) % M; + if (amount > 0) + sell.push({price, amount}); + } + if (order[1] > 0) + buy.push({order[0], order[1]}); + } + else + { + while (order[1]>0 && !buy.empty() && buy.top().first >= order[0]) + { + auto [price, amount] = buy.top(); + buy.pop(); + long num = min(amount, (long)order[1]); + amount-=num; + order[1]-=num; + ret = (ret - num*2 + M) % M; + if (amount > 0) + buy.push({price, amount}); + } + if (order[1] > 0) + sell.push({order[0], order[1]}); + } + } + + return ret; + } +}; From 4d7c69bf6118b4f84d710dfb03e28dd22884d412 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 18:00:54 -0800 Subject: [PATCH 0215/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 731a3d553..4f1fa1974 100644 --- a/Readme.md +++ b/Readme.md @@ -286,6 +286,7 @@ [1352.Product-of-the-Last-K-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Design/1352.Product-of-the-Last-K-Numbers) (M+) [1418.Display-Table-of-Food-Orders-in-a-Restaurant](https://github.com/wisdompeak/LeetCode/tree/master/Design/1418.Display-Table-of-Food-Orders-in-a-Restaurant) (H-) [1622.Fancy-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Design/1622.Fancy-Sequence) (H+) +[1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Design/1801.Number-of-Orders-in-the-Backlog) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) From 7b34e951edd14d976012d880708c0ca4ea678d5a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Nov 2021 18:04:28 -0800 Subject: [PATCH 0216/2729] Create Readme.md --- Design/1801.Number-of-Orders-in-the-Backlog/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Design/1801.Number-of-Orders-in-the-Backlog/Readme.md diff --git a/Design/1801.Number-of-Orders-in-the-Backlog/Readme.md b/Design/1801.Number-of-Orders-in-the-Backlog/Readme.md new file mode 100644 index 000000000..7f6e63bbe --- /dev/null +++ b/Design/1801.Number-of-Orders-in-the-Backlog/Readme.md @@ -0,0 +1,7 @@ +### 1801.Number-of-Orders-in-the-Backlog + +设计两个优先队列。buy表示未完成的待买订单,按照价格从高到低排序;sell表示未完成的待卖订单,按照价格从到高排序。 + +每处理一个待买订单,我们就与sell队列队首的订单进行匹配。考察能消除多少sell里面的订单。记得如果仍有待买订单未完成,需要加入buy队列。 + +同理,每处理一个待待订单,我们就与buy队列队首的订单进行匹配。考察能消除多少biy里面的订单。记得如果仍有待卖订单未完成,需要加入sell队列。 From fd8944686a46cbdc12cf7a72a9de9965eb202784 Mon Sep 17 00:00:00 2001 From: Fenghe Xu Date: Mon, 6 Dec 2021 21:52:41 +0800 Subject: [PATCH 0217/2729] Create 143.Reorder-List_v2.cpp 1. Use fast and slow pointers; 2. More elegant revert and insertion. --- .../143.Reorder-List/143.Reorder-List_v2.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Linked_List/143.Reorder-List/143.Reorder-List_v2.cpp diff --git a/Linked_List/143.Reorder-List/143.Reorder-List_v2.cpp b/Linked_List/143.Reorder-List/143.Reorder-List_v2.cpp new file mode 100644 index 000000000..9e4d50ffc --- /dev/null +++ b/Linked_List/143.Reorder-List/143.Reorder-List_v2.cpp @@ -0,0 +1,39 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + void reorderList(ListNode* head) { + ListNode *slow = head, *fast = head; + for(; fast && fast->next; slow = slow->next, fast = fast->next->next); + ListNode *head1 = head; + ListNode *head2 = slow->next; + slow->next = nullptr; + + // reverse list2 + ListNode *nextNode = nullptr; + for(ListNode *cur = head2; cur != nullptr;) { + ListNode *curNext = cur->next; + cur->next = nextNode; + nextNode = cur; + cur = curNext; + } + head2 = nextNode; + + // traverse list1 to insert + for(ListNode *ptr1 = head1, *ptr2 = head2; ptr1 && ptr2;) { + ListNode *ptr1Next = ptr1->next, *ptr2Next = ptr2->next; + ptr1->next = ptr2; + ptr2->next = ptr1Next; + ptr1 = ptr1Next; + ptr2 = ptr2Next; + } + } +}; From 7ed47019129e07510d16359c3bc848853210df24 Mon Sep 17 00:00:00 2001 From: refinedcoding <63949022+refinedcoding@users.noreply.github.com> Date: Tue, 7 Dec 2021 22:32:20 -0800 Subject: [PATCH 0218/2729] Update 479.Largest-Palindrome-Product.cpp --- .../479.Largest-Palindrome-Product.cpp | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/Others/479.Largest-Palindrome-Product/479.Largest-Palindrome-Product.cpp b/Others/479.Largest-Palindrome-Product/479.Largest-Palindrome-Product.cpp index 631c4fc4b..1061ca1a5 100644 --- a/Others/479.Largest-Palindrome-Product/479.Largest-Palindrome-Product.cpp +++ b/Others/479.Largest-Palindrome-Product/479.Largest-Palindrome-Product.cpp @@ -1,30 +1,26 @@ class Solution { public: + // Rank: 34.85% -> 81.82% int largestPalindrome(int n) { if (n==1) return 9; - - int upper = pow(10,n)-1; - int lower = pow(10,n-1); + int lower = pow(10,n-1), upper = lower * 10 - 1; for (int i=upper; i>=lower; i--) { - long long palindrome = createPalindrome(i); + long long palindrome = i; + for (int j = i; j > 0; j /= 10) + { + palindrome = palindrome * 10 + j % 10; + } - for (int j=upper; j>=sqrt(palindrome); j--) + for (int j=sqrt(palindrome); j <= upper; j++) { - if (palindrome%j==0 && palindrome/j>=pow(10,n-1)) + if (palindrome%j==0 && palindrome/j<=upper) return palindrome%1337; } } return -1; } - - long long createPalindrome(int i) - { - string temp = to_string(i); - reverse(temp.begin(),temp.end()); - return stol(to_string(i)+temp); - } }; From 340b30fa0130d2a643c2015a77071a6bdb3a6b49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 8 Dec 2021 00:31:06 -0800 Subject: [PATCH 0219/2729] Update 312.Burst-Balloons-DP.cpp --- DFS/312.Burst-Balloons/312.Burst-Balloons-DP.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/312.Burst-Balloons/312.Burst-Balloons-DP.cpp b/DFS/312.Burst-Balloons/312.Burst-Balloons-DP.cpp index 64ce42f2f..38e70ccd3 100644 --- a/DFS/312.Burst-Balloons/312.Burst-Balloons-DP.cpp +++ b/DFS/312.Burst-Balloons/312.Burst-Balloons-DP.cpp @@ -9,7 +9,7 @@ class Solution { auto dp = vector>(N+2,vector(N+2,0)); for (int len=1; len<=N; len++) - for (int i=1; i+ken-1<=N; i++) + for (int i=1; i+len-1<=N; i++) { int j = i+len-1; for (int k=i; k<=j; k++) From 7ebf8aea46711d5a961e11de29771bacdb063fea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Dec 2021 04:20:50 -0800 Subject: [PATCH 0220/2729] Update Readme.md --- DFS/332.Reconstruct-Itinerary/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/332.Reconstruct-Itinerary/Readme.md b/DFS/332.Reconstruct-Itinerary/Readme.md index 311359a84..7f42ff56d 100644 --- a/DFS/332.Reconstruct-Itinerary/Readme.md +++ b/DFS/332.Reconstruct-Itinerary/Readme.md @@ -31,7 +31,7 @@ -> D -> E A -> B <-> F ``` -如上述的例子。最理想的情况是一次遍历走完所有想走的点 B->F->B->D->E. 但是我们在B的支路选择上不可能总是这么幸运,可能会走这样一条路 B->D->E,这样走到了尽头。但是B还有另一条支路->F没有走,如果我们尝试继续走那一条的话,就是 B->F->B,然后停止,因为此时B没有任何未走过的边了。 +如上述的例子(注意B->F和F->B是两条不同的边)。最理想的情况是一次遍历走完所有想走的点 B->F->B->D->E. 但是我们在B的支路选择上不可能总是这么幸运,可能会走这样一条路 B->D->E,这样走到了尽头。但是B还有另一条支路->F没有走,如果我们尝试继续走那一条的话,就是 B->F->B,然后停止,因为此时B没有任何未走过的边了。 那我们构造欧拉路径的思想是:B + path2 + path1,其中path1是从B点出发,选择任意支路并能够顺利走到终点的欧拉路径。path2是在path1走完之后,再从B点出发,最终走回B点的路径。注意,如果足够幸运,path1走遍了B后面的所有边,那么path2就不存在了。 From a438e3ea5db38ec9cd96fa9f0ac3156cbe6388fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Dec 2021 05:16:51 -0800 Subject: [PATCH 0221/2729] Create 2097.Valid-Arrangement-of-Pairs.cpp --- .../2097.Valid-Arrangement-of-Pairs.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Graph/2097.Valid-Arrangement-of-Pairs/2097.Valid-Arrangement-of-Pairs.cpp diff --git a/Graph/2097.Valid-Arrangement-of-Pairs/2097.Valid-Arrangement-of-Pairs.cpp b/Graph/2097.Valid-Arrangement-of-Pairs/2097.Valid-Arrangement-of-Pairs.cpp new file mode 100644 index 000000000..8d98aeeea --- /dev/null +++ b/Graph/2097.Valid-Arrangement-of-Pairs/2097.Valid-Arrangement-of-Pairs.cpp @@ -0,0 +1,49 @@ +class Solution { + unordered_map>Map; + unordered_mapin; + unordered_mapout; + +public: + vector> validArrangement(vector>& pairs) + { + + for (auto pair: pairs) + { + Map[pair[0]].push_back(pair[1]); + in[pair[1]]++; + out[pair[0]]++; + } + + int start = -1; + for (auto x: Map) + { + int p = x.first; + if (out[p]-in[p]==1) + start = p; + } + + if (start==-1) + start = pairs[0][0]; + + vectorpath; + DFS(start, path); + reverse(path.begin(), path.end()); + + vector>rets; + for (int i=0; i& path) + { + while (Map[start].size()>0) + { + int nextStart = Map[start].back(); + Map[start].pop_back(); + DFS(nextStart, path); + } + path.push_back(start); + } +}; From 4962b3121f8ce620079edcbc5dbaa44a19a2fdde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Dec 2021 05:17:13 -0800 Subject: [PATCH 0222/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4f1fa1974..d07480add 100644 --- a/Readme.md +++ b/Readme.md @@ -875,6 +875,7 @@ #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) +[2097.Valid-Arrangement-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2097.Valid-Arrangement-of-Pairs) (H) [753.Cracking-the-Safe](https://github.com/wisdompeak/LeetCode/tree/master/Hash/753.Cracking-the-Safe) (H) [1059.All-Paths-from-Source-Lead-to-Destination](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1059.All-Paths-from-Source-Lead-to-Destination) (H) [1192.Critical-Connections-in-a-Network](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1192.Critical-Connections-in-a-Network) (H) From 9bac2646613936390992e4d40dcb9c26a4fd8b3e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Dec 2021 05:44:54 -0800 Subject: [PATCH 0223/2729] Create Readme.md --- .../2097.Valid-Arrangement-of-Pairs/Readme.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Graph/2097.Valid-Arrangement-of-Pairs/Readme.md diff --git a/Graph/2097.Valid-Arrangement-of-Pairs/Readme.md b/Graph/2097.Valid-Arrangement-of-Pairs/Readme.md new file mode 100644 index 000000000..49f0cf81a --- /dev/null +++ b/Graph/2097.Valid-Arrangement-of-Pairs/Readme.md @@ -0,0 +1,23 @@ +### 2097.Valid-Arrangement-of-Pairs + +因为本题保证一定有解,所以这就是一个欧拉路径问题:我们将每个数字当做节点,每个pair看做是两个节点之间的路径,那么本题就是规划一条路径,要求不重复地走过所有边。类似的题目有LC332。 + +对于欧拉路径,我们回顾一下相关的知识点: + +欧拉路径:从一个点出发,到达另外一个点,所有的边都经过且只经过1次。 + +欧拉回路:欧拉路径中,终点能回到起点。 + +如果判断是否存在欧拉路径? + +1.无向图:(a) 如果只有两个点的度是奇数,其他的点的度都是偶数,则存在从一个奇数度点到另一个奇数度点的欧拉路径(不是回路)。(b) 如果所有的点的度都是偶数,那么就是欧拉回路。 + +2.有向图:(a) 如果最多有一个点出度大于入度by1,且最多有一个点入度大于出度by1,那么就有一条从前者(如果没有则可以任意)到后者(如果没有则可以任意)的欧拉路径。(b) 如果所有的点的入度等于出度,那么就存在欧拉回路。 + +对于本题而言,我们只要根据有向图的规则,找到```出度-入度==1```的那个点作为起点。如果不存在,就可以任意为起点。 + +那么如何规划这条路径呢?我们需要有这样一个概念:对于一个注定存在欧拉路径的图而言,抛开起点,只可能最多有一个dead end (这是注定的终点)。假设存在这样一个死胡同,那么你从任意一个点出发,在不重复走边的前提下任意走,最终状态一定会走进这个死胡同;并且此时未走过的边,必然都是一个一个封闭的环。这是因为欧拉路径里除了起点和终点,其他所有点都是入度等于出度,因此除了dead end外,你只要能从某条边进入某点,必然可以通过另一条边出去。 + +于是我们可以这样规划DFS算法:当你打算从start出发,随便选一个出口,就无脑递归下去,这条路径最终会走进一个dead end,我们记做path1. 然后我们考察start还有其他未被遍历的那些边。根据之前的分析,走这些边之后必然是经历一个封闭的环,也就是你无论选哪个边走下去,最终都肯定会走回来,我们将这些记做path2a, path2b, path2c... 于是我们只要这样规划路径:```start + ... + path2c + path2b + path2a + path1```,也就是将唯一会走入死胡同的路径放在最后一个即可,这样就构造一条从start开始的欧拉路径。 + +那么如果全图没有dead end呢?那么相当于没有path1,你从start的任何一个边出去,都一定会再转回来。上述的算法依然有效。 From c3fcbd2f4ac51e1fe822961e381d7601f5d66d7b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 10:35:37 -0800 Subject: [PATCH 0224/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d07480add..31f1fc8b9 100644 --- a/Readme.md +++ b/Readme.md @@ -239,6 +239,7 @@ [1597.Build-Binary-Expression-Tree-From-Infix-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1597.Build-Binary-Expression-Tree-From-Infix-Expression) (H) [1902.Depth-of-BST-Given-Insertion-Order](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order) (H-) * ``LCA`` +[235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (M) [236.Lowest-Common-Ancestor-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (H) [1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV) (M+) [1740.Find-Distance-in-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1740.Find-Distance-in-a-Binary-Tree) (H) From aa27b59b7e5aecda6a3c3923f134112c18fb0b0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 11:08:07 -0800 Subject: [PATCH 0225/2729] Create 1123.Lowest-Common-Ancestor-of-Deepest-Leaves.cpp --- ...west-Common-Ancestor-of-Deepest-Leaves.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/1123.Lowest-Common-Ancestor-of-Deepest-Leaves.cpp diff --git a/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/1123.Lowest-Common-Ancestor-of-Deepest-Leaves.cpp b/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/1123.Lowest-Common-Ancestor-of-Deepest-Leaves.cpp new file mode 100644 index 000000000..9878f3a46 --- /dev/null +++ b/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/1123.Lowest-Common-Ancestor-of-Deepest-Leaves.cpp @@ -0,0 +1,46 @@ +/** + * 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 { + int maxDepth = 0; + int deepCount = 0; + TreeNode* ret = NULL; + unordered_mapMap; +public: + TreeNode* lcaDeepestLeaves(TreeNode* root) + { + dfs(root, 1); + for (auto x:Map) + deepCount += (x.second == maxDepth); + dfs2(root); + return ret; + } + + void dfs(TreeNode* node, int depth) + { + if (node==NULL) return; + Map[node->val] = depth; + maxDepth = max(maxDepth, depth); + dfs(node->left, depth+1); + dfs(node->right, depth+1); + } + + int dfs2(TreeNode* node) + { + if (node==NULL) return 0; + int self = (Map[node->val]==maxDepth); + int a = dfs2(node->left); + int b = dfs2(node->right); + if (self+a+b == deepCount && ret==NULL) + ret = node; + return self+a+b; + } +}; From 7537c4db261fb2288c936a654cfb5eed8f9a841d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 11:08:25 -0800 Subject: [PATCH 0226/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 31f1fc8b9..7d592e846 100644 --- a/Readme.md +++ b/Readme.md @@ -240,6 +240,7 @@ [1902.Depth-of-BST-Given-Insertion-Order](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order) (H-) * ``LCA`` [235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (M) +[1123.Lowest-Common-Ancestor-of-Deepest-Leaves](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves) (M+) [236.Lowest-Common-Ancestor-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (H) [1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV) (M+) [1740.Find-Distance-in-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1740.Find-Distance-in-a-Binary-Tree) (H) From c3c5f1beda721e8b32d582eea48534e578f9e14d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 11:10:45 -0800 Subject: [PATCH 0227/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7d592e846..b241b3bc1 100644 --- a/Readme.md +++ b/Readme.md @@ -240,7 +240,7 @@ [1902.Depth-of-BST-Given-Insertion-Order](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order) (H-) * ``LCA`` [235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (M) -[1123.Lowest-Common-Ancestor-of-Deepest-Leaves](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves) (M+) +[1123.Lowest-Common-Ancestor-of-Deepest-Leaves](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves) (M+) (aka. LC.865) [236.Lowest-Common-Ancestor-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (H) [1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV) (M+) [1740.Find-Distance-in-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1740.Find-Distance-in-a-Binary-Tree) (H) From 858e9d7e3b092a75d2636f3414a627ee600e64b0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 11:15:00 -0800 Subject: [PATCH 0228/2729] Create Readme.md --- Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/Readme.md diff --git a/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/Readme.md b/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/Readme.md new file mode 100644 index 000000000..c4ee99e1a --- /dev/null +++ b/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/Readme.md @@ -0,0 +1,5 @@ +### 1123.Lowest-Common-Ancestor-of-Deepest-Leaves + +提前遍历整棵树做预处理,记录整棵树最深的深度maxDepth,以及总共有多少个深度是maxDepth的节点deepCount. + +然后第二次遍历整棵树,从下往上查看每个节点包含多少个maxDepth的叶子节点。当找到第一个数目是deepCount的节点时,说明它的子树下面包含了所有的deepest leaves,这就是答案。 From 1484ce487e74a96c0b7b51308498e7ebaed8d68c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 12:03:10 -0800 Subject: [PATCH 0229/2729] Create 1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp --- ...st-Common-Ancestor-of-a-Binary-Tree-II.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp diff --git a/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp b/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp new file mode 100644 index 000000000..23e75fbae --- /dev/null +++ b/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int count = 0; +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) + { + TreeNode* ret = lca(root, p, q); + if (count!=2) return NULL; + else return ret; + } + + TreeNode* lca(TreeNode* root, TreeNode* p, TreeNode* q) + { + if (root==NULL) return NULL; + + TreeNode* L = lca(root->left,p,q); + TreeNode* R = lca(root->right,p,q); + + if (root==p || root==q) + { + count++; + return root; + } + + if (L&&R) + return root; + else if (!L&&R) + return R; + else if (L&&!R) + return L; + else + return NULL; + } +}; From 6b2c13e2406b8925b12ac610400c0577cb109541 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 12:03:44 -0800 Subject: [PATCH 0230/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b241b3bc1..6f9a0a7f8 100644 --- a/Readme.md +++ b/Readme.md @@ -239,9 +239,10 @@ [1597.Build-Binary-Expression-Tree-From-Infix-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1597.Build-Binary-Expression-Tree-From-Infix-Expression) (H) [1902.Depth-of-BST-Given-Insertion-Order](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order) (H-) * ``LCA`` -[235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (M) [1123.Lowest-Common-Ancestor-of-Deepest-Leaves](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves) (M+) (aka. LC.865) +[235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (M) [236.Lowest-Common-Ancestor-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (H) +[1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II) (H) [1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV) (M+) [1740.Find-Distance-in-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1740.Find-Distance-in-a-Binary-Tree) (H) * ``N-ary Tree`` From 36581d0f859396517614055d7b7654e819fbd62e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 12:12:11 -0800 Subject: [PATCH 0231/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/Readme.md diff --git a/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/Readme.md b/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/Readme.md new file mode 100644 index 000000000..be9f97d6c --- /dev/null +++ b/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/Readme.md @@ -0,0 +1,11 @@ +### 1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II + +此题与LC.236相比,区别在于我们必须判定p和q的存在。因为236里面递归函数的返回值定义的是:或者p,或者q,或者p与q的LCA。因此假如q并不存在的话,递归函数依然能有非空的返回值,但返回的仅仅是p而已。 + +这就要求我们的递归函数必须强制把所有的节点都遍历完,并且确认访问过p和q。怎么办呢?复盘LC.236的代码里,我们有提前返回的逻辑 +```cpp +if (root==p || root==q) return root; +``` +正是因为这行代码如果发生在递归左右节点之前,那么我们没有机会遍历所有的节点。 + +所以我们应该把这一段代码移到递归左右节点之后。这样我们就一定会访问到所有的节点。同时我们还需要再加一行代码来判定是否遇到过p和q就行。只有p和q都访问过的flag为true时,整体递归函数返回的节点才是真正的LCA。 From 439b562ed1b63af37306632b9c420032e0352893 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 13:54:49 -0800 Subject: [PATCH 0232/2729] Rename 236.Lowest-Common-Ancestor-of-a-Binary-Tree_recursive.cpp to 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp --- ...ive.cpp => 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/{236.Lowest-Common-Ancestor-of-a-Binary-Tree_recursive.cpp => 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp} (100%) diff --git a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_recursive.cpp b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp similarity index 100% rename from Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_recursive.cpp rename to Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp From 26c1e4dca806a5549a59851d9e5563d535ea4643 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 13:55:04 -0800 Subject: [PATCH 0233/2729] Create 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp --- ...st-Common-Ancestor-of-a-Binary-Tree_v3.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp diff --git a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp new file mode 100644 index 000000000..0caacab26 --- /dev/null +++ b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int count = 0; + TreeNode* ret = NULL; +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) + { + dfs(root, p, q); + return ret; + } + + int dfs(TreeNode* node, TreeNode* p, TreeNode* q) + { + if (node==NULL) return 0; + int count = dfs(node->left, p, q) + dfs(node->right, p, q); + if (node==p || node==q) count++; + if (count == 2 && ret == NULL) + ret = node; + return count; + } +}; From 355d0a19135237e92530e31d9f458c64fc88cc41 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 13:55:18 -0800 Subject: [PATCH 0234/2729] Rename 236.Lowest Common Ancestor of a Binary Tree.cpp to 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v1.cpp --- ...ree.cpp => 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/{236.Lowest Common Ancestor of a Binary Tree.cpp => 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v1.cpp} (100%) diff --git a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest Common Ancestor of a Binary Tree.cpp b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v1.cpp similarity index 100% rename from Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest Common Ancestor of a Binary Tree.cpp rename to Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v1.cpp From 059bad66fd574fb6325f07b03bde99897005095a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:20:23 -0800 Subject: [PATCH 0235/2729] Delete 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp --- ...st-Common-Ancestor-of-a-Binary-Tree_v2.cpp | 27 ------------------- 1 file changed, 27 deletions(-) delete mode 100644 Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp diff --git a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp deleted file mode 100644 index 9a86f96ec..000000000 --- a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) - { - if (root==NULL || root==p || root==q) - return root; - TreeNode* left = lowestCommonAncestor(root->left,p,q); - TreeNode* right = lowestCommonAncestor(root->right,p,q); - if (left && right) - return root; - else if (!left && right) - return right; - else if (left && !right) - return left; - else - return NULL; - } -}; From 22754e66075c985cea80a3cb226c8f5d3c87aafc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:20:33 -0800 Subject: [PATCH 0236/2729] Rename 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp to 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp --- ..._v3.cpp => 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/{236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp => 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp} (100%) diff --git a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp similarity index 100% rename from Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v3.cpp rename to Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp From 9b6f095f91ea301249d0d67a1ad45eebf4451f77 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:24:42 -0800 Subject: [PATCH 0237/2729] Update Readme.md --- .../Readme.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/Readme.md b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/Readme.md index 390ef0d22..c219000f2 100644 --- a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/Readme.md +++ b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/Readme.md @@ -27,13 +27,10 @@ DFS函数会一路向下层搜索直到发现节点p,然后在返回的过程 ``` 得到数组P和Q之后,只要从后往前比较两个数组,追踪它们相同的路径截止到哪一位为止就行了。 -#### 解法2:递归调用 +#### 解法2:递归 -因为p,q保证是在这棵树里面,所以我们可以这样定义lowestCommonAncestor(node,p,q),返回的是p或者q或者两者的LCA。 - -1.如果node是NULL或者p或者q,那么我们就返回node,表示我们定位到了p/q。 - -2.分别递归调用```left=lowestCommonAncestor(node->left,p,q); right=lowestCommonAncestor(node->right,p,q)```.如果left和right都非空,那么必然说明一个分支含有p,另一个分支含有q,故node一定就是LCA。如果left非空而right为空,说明我们在左边定位到了p或者q或者是p,q的LCA,不管如何,都返回left。同理,如果right非空而left为空,说明我们在右边定位到了p或q或者是pq的LCA。如果两者都为空,那么就自然返回空。 +我们设计递归函数```int dfs(node)```表示node的子树里面包含了p和q中的几个?(可以是0,1,2)。显然,只有p和q的公共祖先节点,才会有该函数的返回值是2. +更特别地,因为递归是从下往上返回的。当我们第一次遇到某个节点的子树里同时包含p和q的节点,它必然就是p和q的最低公共祖先。 [Leetcode Link](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree) From 477908ec4a3aea6cd057aaf78acdb9fce2c76daa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:25:18 -0800 Subject: [PATCH 0238/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 6f9a0a7f8..b05aa4cd0 100644 --- a/Readme.md +++ b/Readme.md @@ -241,8 +241,8 @@ * ``LCA`` [1123.Lowest-Common-Ancestor-of-Deepest-Leaves](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves) (M+) (aka. LC.865) [235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (M) -[236.Lowest-Common-Ancestor-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (H) -[1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II) (H) +[236.Lowest-Common-Ancestor-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (H-) +[1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II) (H-) [1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV) (M+) [1740.Find-Distance-in-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1740.Find-Distance-in-a-Binary-Tree) (H) * ``N-ary Tree`` From ee81cfa9980e7a12d5eccd2ebb9764c3b9f7ecd0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:26:30 -0800 Subject: [PATCH 0239/2729] Update Readme.md --- .../Readme.md | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/Readme.md b/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/Readme.md index be9f97d6c..6caddcae6 100644 --- a/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/Readme.md +++ b/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/Readme.md @@ -1,11 +1,3 @@ ### 1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II -此题与LC.236相比,区别在于我们必须判定p和q的存在。因为236里面递归函数的返回值定义的是:或者p,或者q,或者p与q的LCA。因此假如q并不存在的话,递归函数依然能有非空的返回值,但返回的仅仅是p而已。 - -这就要求我们的递归函数必须强制把所有的节点都遍历完,并且确认访问过p和q。怎么办呢?复盘LC.236的代码里,我们有提前返回的逻辑 -```cpp -if (root==p || root==q) return root; -``` -正是因为这行代码如果发生在递归左右节点之前,那么我们没有机会遍历所有的节点。 - -所以我们应该把这一段代码移到递归左右节点之后。这样我们就一定会访问到所有的节点。同时我们还需要再加一行代码来判定是否遇到过p和q就行。只有p和q都访问过的flag为true时,整体递归函数返回的节点才是真正的LCA。 +LC.236的递归解法完全可以适用于本题。 From cd47d6c5aab062559f50b799274c5642fe5a4e9a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:27:33 -0800 Subject: [PATCH 0240/2729] Update 1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV.cpp --- .../1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV.cpp b/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV.cpp index 390f6bd82..da42afe0d 100644 --- a/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV.cpp +++ b/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV.cpp @@ -27,9 +27,9 @@ class Solution { if (node==NULL) return 0; int left = dfs(node->left); int right = dfs(node->right); - int cur = Set.find(node)!=Set.end(); - if (ret==NULL && left+right+cur==Set.size()) + int self = Set.find(node)!=Set.end(); + if (left+right+self==Set.size() && ret==NULL) ret = node; - return left+right+cur; + return left+right+self; } }; From f2817655b64fb213d8915059c56b7f0a6c61f0ac Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:29:54 -0800 Subject: [PATCH 0241/2729] Update Readme.md --- .../1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/Readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/Readme.md b/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/Readme.md index e753d8290..00086c38c 100644 --- a/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/Readme.md +++ b/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV/Readme.md @@ -1,5 +1,3 @@ ### 1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV -一个比较简单的算法思想就是,深度搜索每个节点node,查看它的子节点(包括自身)有多少个节点是在集合nodes里面的。如果数目和nodes的集合大小相同,那么node就是集合里所有节点的ancestor。 - -注意,只有在DFS过程中第一个被检测到的这样的节点才是答案。更高层的节点,虽然也满足判定条件,但并不是lowest common ancestor. +此题和```LC.236```一模一样的思想。令```int dfs(node)```表示以node为根的子树里面包含了多少个指定的节点。假设题目给出的nodes的个数是n,那么在从下往上返回的过程中,第一个发现dfs返回值是n的节点必然就是所有nodes的LCA。 From 7b804cf36bdc68a71a71c22f8d3a3e94030b4527 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:32:38 -0800 Subject: [PATCH 0242/2729] Create 1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp --- ...t-Common-Ancestor-of-a Binary-Tree-III.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp diff --git a/Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp b/Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp new file mode 100644 index 000000000..f4c1b90fe --- /dev/null +++ b/Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp @@ -0,0 +1,39 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* parent; +}; +*/ + +class Solution { +public: + Node* lowestCommonAncestor(Node* p, Node * q) + { + vectora; + while (p!=NULL) + { + a.push_back(p); + p = p->parent; + } + vectorb; + while (q!=NULL) + { + b.push_back(q); + q = q->parent; + } + reverse(a.begin(), a.end()); + reverse(b.begin(), b.end()); + int i = 0; + Node* ret; + while (i Date: Sat, 11 Dec 2021 22:34:02 -0800 Subject: [PATCH 0243/2729] Create Readme.md --- .../1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/Readme.md diff --git a/Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/Readme.md b/Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/Readme.md new file mode 100644 index 000000000..e4ac6c97c --- /dev/null +++ b/Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/Readme.md @@ -0,0 +1,3 @@ +### 1650.Lowest-Common-Ancestor-of-a Binary-Tree-III + +本题既然给出了每个节点的parent,那么只要把p和q上行至root的路径都遍历出来,然后分别反向。这样两条路径的最后一个公共节点就是LCA。 From aaa172cfa37274438979115fab8b9179c2d2f23d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:34:52 -0800 Subject: [PATCH 0244/2729] Rename Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp to Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III.cpp --- .../1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/{1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp => 1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III.cpp} (100%) diff --git a/Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp b/Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III.cpp similarity index 100% rename from Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III.cpp rename to Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III.cpp From 5c919dcd3cef5eae499a5fab07574a2d4a3babc1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:35:27 -0800 Subject: [PATCH 0245/2729] Rename Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/Readme.md to Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III/Readme.md --- .../Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/{1650.Lowest-Common-Ancestor-of-a Binary-Tree-III => 1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III}/Readme.md (100%) diff --git a/Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/Readme.md b/Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III/Readme.md similarity index 100% rename from Tree/1650.Lowest-Common-Ancestor-of-a Binary-Tree-III/Readme.md rename to Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III/Readme.md From 5a2a43acd4d65d17e1d8e1b820151684aef5c213 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Dec 2021 22:36:00 -0800 Subject: [PATCH 0246/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index b05aa4cd0..d04bd33ce 100644 --- a/Readme.md +++ b/Readme.md @@ -241,9 +241,10 @@ * ``LCA`` [1123.Lowest-Common-Ancestor-of-Deepest-Leaves](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1123.Lowest-Common-Ancestor-of-Deepest-Leaves) (M+) (aka. LC.865) [235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (M) -[236.Lowest-Common-Ancestor-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (H-) -[1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II) (H-) +[236.Lowest-Common-Ancestor-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree) (M+) +[1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II) (M+) [1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV) (M+) +[1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III) (M) [1740.Find-Distance-in-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1740.Find-Distance-in-a-Binary-Tree) (H) * ``N-ary Tree`` [428.Serialize-and-Deserialize-N-ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/428.Serialize-and-Deserialize-N-ary-Tree) (H) From 544aca502f35e69ccad161294c47c315005f2f43 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Dec 2021 06:41:27 -0800 Subject: [PATCH 0247/2729] Update Readme.md --- Tree/1740.Find-Distance-in-a-Binary-Tree/Readme.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Tree/1740.Find-Distance-in-a-Binary-Tree/Readme.md b/Tree/1740.Find-Distance-in-a-Binary-Tree/Readme.md index fc63ee6b0..ef2a613ee 100644 --- a/Tree/1740.Find-Distance-in-a-Binary-Tree/Readme.md +++ b/Tree/1740.Find-Distance-in-a-Binary-Tree/Readme.md @@ -1,13 +1,17 @@ ### 1740.Find-Distance-in-a-Binary-Tree -解决Lowest Common Ancestor (LCA)的一个递归套路是:定义dfs(node, p, q),返回值是一个pair,包含node与子节点p的距离、node与子节点q的距离。如果node下属没有子节点是p和q,那么对应的值是-1. +很显然,本题中的那个“拐点”必然是两个节点的LCA。 + +本题的解法可以很暴力,直接寻找从root到p与q分别的路径,根据记录路径然后找出LCA分别到p和q的长度。 + +更加节省空间的方法就是纯递归。在LC236的想法里,dfs(node)返回的是该节点的子树里包含了多少个p或者q。在本题中,我们可以有类似的思想:定义dfs(node)的返回值是一个pair,包含node与p的距离、node与q的距离。如果node下属没有子节点是p和q,那么对应的值是-1. 先分别递归```ans1 = dfs(node->left, p, q)```和```ans2 = dfs(node->left, p, q)```. 分情况讨论: -1. 如果ans1->first!=-1,那么说明node到p的距离是ans1->first+1 -2. 如果ans2->first!=-1,那么说明node到p的距离是ans2->first+1 -3. 如果node->val==p,那么说明node到p的距离是0 +1. 如果已知左节点到p的距离x,那么说明node到p的距离是x+1 +2. 如果已知右节点到p的距离x,那么说明node到p的距离是x+1 +3. 如果node本身就是p,那么说明node到p的距离是0 4. 其余的情况,node到p的距离标记为-1 同理,处理对于node到q的距离处理。 -如果第一次出现node到p和q的距离都不是-1,那么node就是p和q的LCA。答案就是两距离之和。 +因为递归是从下往上走的,如果第一次出现node到p和q的距离都不是-1,那么node就是p和q的LCA。答案就是两距离之和。 From 0724c934b87476ea8a3ee338c2691a12e13e02e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Dec 2021 11:16:31 -0800 Subject: [PATCH 0248/2729] Create 2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp --- ...ons-From-a-Binary-Tree-Node-to-Another.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp diff --git a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp new file mode 100644 index 000000000..1f3a553c3 --- /dev/null +++ b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp @@ -0,0 +1,57 @@ +/** + * 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: + string getDirections(TreeNode* root, int startValue, int destValue) + { + vectornums1, nums2; + nums1.push_back(root->val); + nums2.push_back(root->val); + string dirs1, dirs2; + dfs(root, nums1, dirs1, startValue); + dfs(root, nums2, dirs2, destValue); + + int k = 0; + while (k&nums, string&dirs, int target) + { + if (node==NULL) return false; + if (node->val == target) return true; + if (node->left) + { + nums.push_back(node->left->val); + dirs.push_back('L'); + if (dfs(node->left, nums, dirs, target)) + return true; + nums.pop_back(); + dirs.pop_back(); + } + if (node->right) + { + nums.push_back(node->right->val); + dirs.push_back('R'); + if (dfs(node->right, nums, dirs, target)) + return true; + nums.pop_back(); + dirs.pop_back(); + } + return false; + } + +}; From db9b9889f574fc105e505efaef1cd7eb938be426 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Dec 2021 11:17:06 -0800 Subject: [PATCH 0249/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d04bd33ce..360f98471 100644 --- a/Readme.md +++ b/Readme.md @@ -246,6 +246,7 @@ [1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1676.Lowest-Common-Ancestor-of-a-Binary-Tree-IV) (M+) [1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III) (M) [1740.Find-Distance-in-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1740.Find-Distance-in-a-Binary-Tree) (H) +[2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another) (M+) * ``N-ary Tree`` [428.Serialize-and-Deserialize-N-ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/428.Serialize-and-Deserialize-N-ary-Tree) (H) [431.Encode-N-ary-Tree-to-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/431.Encode-N-ary-Tree-to-Binary-Tree) (H-) From c64ea64a72a2bd03037d156c6b4688959d78f2ad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Dec 2021 11:22:46 -0800 Subject: [PATCH 0250/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/Readme.md diff --git a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/Readme.md b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/Readme.md new file mode 100644 index 000000000..75a4a278d --- /dev/null +++ b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/Readme.md @@ -0,0 +1,5 @@ +### 2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another + +本题和以往求LCA的题目不同。以往的LCA只需要求得LCA的节点本身,而这道题需要设计到路径打印。因此我们就老老实实地用递归的方法,把从root到q或者q的路径先记录出来,然后再比较得到LCA的位置。 + +注意此题中我们需要记录两个信息,首先是从root到p(或者q)一路上遇到的节点数值,另外是一路上的操作(L或者R)。假设两条路径dirs1和dirs2在第k个节点位置分叉(也就是LCA的位置)。根据题意,我们就将dirs1[k:]全部搞成“U”(因为从p到LCA一路都是up),再拼接上dirs2[k:]这段路径即可。 From 1f4100fa519a129e017daada24e36f02af2caa61 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Dec 2021 17:53:52 -0800 Subject: [PATCH 0251/2729] Update 236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp --- .../236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp index 0caacab26..0e2a3850d 100644 --- a/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp +++ b/Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree/236.Lowest-Common-Ancestor-of-a-Binary-Tree_v2.cpp @@ -8,7 +8,6 @@ * }; */ class Solution { - int count = 0; TreeNode* ret = NULL; public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) From 06de30801bbf35c801597ea2065d99308ccf1ebc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Dec 2021 17:57:16 -0800 Subject: [PATCH 0252/2729] Update 1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp --- ...st-Common-Ancestor-of-a-Binary-Tree-II.cpp | 36 +++++++------------ 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp b/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp index 23e75fbae..baa5f7f05 100644 --- a/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp +++ b/Tree/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II/1644.Lowest-Common-Ancestor-of-a-Binary-Tree-II.cpp @@ -8,35 +8,23 @@ * }; */ class Solution { - int count = 0; + TreeNode* ret = NULL; public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - TreeNode* ret = lca(root, p, q); - if (count!=2) return NULL; - else return ret; + int a = dfs(root, p, q); + return ret; } - TreeNode* lca(TreeNode* root, TreeNode* p, TreeNode* q) + int dfs(TreeNode* root, TreeNode* p, TreeNode* q) { - if (root==NULL) return NULL; - - TreeNode* L = lca(root->left,p,q); - TreeNode* R = lca(root->right,p,q); - - if (root==p || root==q) - { - count++; - return root; - } - - if (L&&R) - return root; - else if (!L&&R) - return R; - else if (L&&!R) - return L; - else - return NULL; + if (root==NULL) return 0; + int left = dfs(root->left, p, q); + int right = dfs(root->right, p, q); + int self = (root==p || root==q); + int count = left+right+self; + if (count==2 && ret==NULL) + ret = root; + return count; } }; From 4487405fcfc603046246c7ae1afcca8679456c76 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 13 Dec 2021 04:46:54 -0800 Subject: [PATCH 0253/2729] Update 2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp --- ...p-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp index 1f3a553c3..6a4b77b72 100644 --- a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp +++ b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp @@ -14,8 +14,6 @@ class Solution { string getDirections(TreeNode* root, int startValue, int destValue) { vectornums1, nums2; - nums1.push_back(root->val); - nums2.push_back(root->val); string dirs1, dirs2; dfs(root, nums1, dirs1, startValue); dfs(root, nums2, dirs2, destValue); @@ -23,7 +21,6 @@ class Solution { int k = 0; while (k Date: Fri, 17 Dec 2021 05:33:14 -0800 Subject: [PATCH 0254/2729] Create 2101.Detonate-the-Maximum-Bombs.cpp --- .../2101.Detonate-the-Maximum-Bombs.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 BFS/2101.Detonate-the-Maximum-Bombs/2101.Detonate-the-Maximum-Bombs.cpp diff --git a/BFS/2101.Detonate-the-Maximum-Bombs/2101.Detonate-the-Maximum-Bombs.cpp b/BFS/2101.Detonate-the-Maximum-Bombs/2101.Detonate-the-Maximum-Bombs.cpp new file mode 100644 index 000000000..53de335d2 --- /dev/null +++ b/BFS/2101.Detonate-the-Maximum-Bombs/2101.Detonate-the-Maximum-Bombs.cpp @@ -0,0 +1,44 @@ +using LL = long long; +class Solution { + vectornext[100]; +public: + int maximumDetonation(vector>& bombs) + { + int n = bombs.size(); + for (int i=0; iq; + q.push(s); + vectorvisited(n); + visited[s] = 1; + while (!q.empty()) + { + int cur = q.front(); + q.pop(); + for (int i: next[cur]) + { + if (visited[i]) continue; + q.push(i); + visited[i] = 1; + } + } + int count = 0; + for (int i=0; i Date: Fri, 17 Dec 2021 05:33:43 -0800 Subject: [PATCH 0255/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 360f98471..5c85f8755 100644 --- a/Readme.md +++ b/Readme.md @@ -458,6 +458,7 @@ [1654.Minimum-Jumps-to-Reach-Home](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1654.Minimum-Jumps-to-Reach-Home) (H-) [1905.Count-Sub-Islands](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1905.Count-Sub-Islands) (M+) [2045.Second-Minimum-Time-to-Reach-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2045.Second-Minimum-Time-to-Reach-Destination) (M+) +[2101.Detonate-the-Maximum-Bombs](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2101.Detonate-the-Maximum-Bombs) (M+) * ``Multi State`` [847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) [864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) From e3c1e952d5b86205ae5066b756b7a5dfe2969516 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Dec 2021 05:50:35 -0800 Subject: [PATCH 0256/2729] Create Readme.md --- BFS/2101.Detonate-the-Maximum-Bombs/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2101.Detonate-the-Maximum-Bombs/Readme.md diff --git a/BFS/2101.Detonate-the-Maximum-Bombs/Readme.md b/BFS/2101.Detonate-the-Maximum-Bombs/Readme.md new file mode 100644 index 000000000..f7bbcbfd0 --- /dev/null +++ b/BFS/2101.Detonate-the-Maximum-Bombs/Readme.md @@ -0,0 +1,5 @@ +### 2101.Detonate-the-Maximum-Bombs + +根据题目的范围n<=100,可以大胆地设计n^3时间复杂度的算法。我们随意采用一个炸弹作为初始引爆点,题目所给的条件可以知道哪些后续炸弹会被第一个引爆。于是我们将这些后续一定会被引爆的炸弹也放入一个队列。之后队列里只要每弹出一个能被引爆的炸弹,我们就加入后续能被引爆的炸弹(已经引爆过的不算)。于是这就是一个非常直观的BFS。 + +注意本题的时间复杂度。选取初始引爆炸弹需要o(n)的遍历;之后的队列的维护生成需要o(n);每次我们根据一个已引爆炸弹穷举所有可能被引爆的炸弹,这也需要o(n)。所以总的时间复杂度是o(n^3). From fd89424306541b4095c1ea584e519789974b207f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Dec 2021 06:27:07 -0800 Subject: [PATCH 0257/2729] Update 496.Next Greater Element I.cpp --- .../496.Next Greater Element I.cpp | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/Stack/496.Next-Greater-Element-I/496.Next Greater Element I.cpp b/Stack/496.Next-Greater-Element-I/496.Next Greater Element I.cpp index 679fd563f..b976c0380 100644 --- a/Stack/496.Next-Greater-Element-I/496.Next Greater Element I.cpp +++ b/Stack/496.Next-Greater-Element-I/496.Next Greater Element I.cpp @@ -7,17 +7,12 @@ class Solution { for (int i=0; inums[i]) - Stack.push(nums[i]); - else + while (!Stack.empty() && Stack.top()results; From 0de5c44072264b5b3eef7837593c4500d07a0b3f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Dec 2021 06:39:32 -0800 Subject: [PATCH 0258/2729] Create 2104.Sum-of-Subarray-Ranges.cpp --- .../2104.Sum-of-Subarray-Ranges.cpp | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Stack/2104.Sum-of-Subarray-Ranges/2104.Sum-of-Subarray-Ranges.cpp diff --git a/Stack/2104.Sum-of-Subarray-Ranges/2104.Sum-of-Subarray-Ranges.cpp b/Stack/2104.Sum-of-Subarray-Ranges/2104.Sum-of-Subarray-Ranges.cpp new file mode 100644 index 000000000..6af084cb9 --- /dev/null +++ b/Stack/2104.Sum-of-Subarray-Ranges/2104.Sum-of-Subarray-Ranges.cpp @@ -0,0 +1,71 @@ +using LL = long long; +class Solution { +public: + long long subArrayRanges(vector& nums) + { + int n = nums.size(); + + stackStack; + vectornextSmaller(n,n); + for (int i=0; inums[i]) + { + nextSmaller[Stack.top()] = i; + Stack.pop(); + } + Stack.push(i); + } + + while (!Stack.empty()) Stack.pop(); + vectorprevSmaller(n,-1); + for (int i=n-1; i>=0; i--) + { + while (!Stack.empty() && nums[Stack.top()]>=nums[i]) + { + prevSmaller[Stack.top()] = i; + Stack.pop(); + } + Stack.push(i); + } + + while (!Stack.empty()) Stack.pop(); + vectornextGreater(n,n); + for (int i=0; iprevGreater(n,-1); + for (int i=n-1; i>=0; i--) + { + while (!Stack.empty() && nums[Stack.top()]<=nums[i]) + { + prevGreater[Stack.top()] = i; + Stack.pop(); + } + Stack.push(i); + } + + LL ret = 0; + for (int i=0; i Date: Fri, 17 Dec 2021 06:40:18 -0800 Subject: [PATCH 0259/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5c85f8755..2ef280215 100644 --- a/Readme.md +++ b/Readme.md @@ -319,8 +319,9 @@ [739.Daily-Temperatures](https://github.com/wisdompeak/LeetCode/tree/master/Stack/739.Daily-Temperatures) (H-) [768.Max-Chunks-To-Make-Sorted-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/768.Max-Chunks-To-Make-Sorted-II) (H-) [901.Online-Stock-Span](https://github.com/wisdompeak/LeetCode/tree/master/Stack/901.Online-Stock-Span) (H-) -[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H) +[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) [1856.Maximum-Subarray-Min-Product](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1856.Maximum-Subarray-Min-Product) (M+) +[2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1019.Next-Greater-Node-In-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1019.Next-Greater-Node-In-Linked-List) (M) [1063.Number-of-Valid-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1063.Number-of-Valid-Subarrays) (M+) From c683c8521f365575cd6bc333c66eae18d4d51324 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Dec 2021 06:46:30 -0800 Subject: [PATCH 0260/2729] Create Readme.md --- Stack/2104.Sum-of-Subarray-Ranges/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Stack/2104.Sum-of-Subarray-Ranges/Readme.md diff --git a/Stack/2104.Sum-of-Subarray-Ranges/Readme.md b/Stack/2104.Sum-of-Subarray-Ranges/Readme.md new file mode 100644 index 000000000..3fd7f56e9 --- /dev/null +++ b/Stack/2104.Sum-of-Subarray-Ranges/Readme.md @@ -0,0 +1,9 @@ +### 2104.Sum-of-Subarray-Ranges + +此题和```907.Sum-of-Subarray-Minimums```非常相似。我们不是根据每个区间来考察它的最大值(或最小值)。而是根据根据最大值(或最小值)来考察对应的区间。 + +我们考察每个元素nums[i],它作为区间最大值时,可以是哪些区间?假设有a个。另外,它作为区间最小值时,可以是哪些区间?假设有b个。那么该元素对于最终答案的贡献就是```nums[i]*a-nums[i]*b```. + +那么怎么求解a呢?只要用单调栈,来算出nums[i]的prevSmaller所在的位置l,nextSmaller所在的位置r,那么这样的区间的数目就有```a=(i-l)*(r-i)```个。求解b同理。 + +特别注意的是,对于区间内如果存在多个相同的最大值,我们需要约定,比如只有最靠右边的那个才是最大值。在这样的情况下,我们实际计算的应该是prevSmallerOrEqual而不是prevSmaller. From 2ea8ddf790cbeb584327ff9d6d59480eefde5026 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Dec 2021 06:49:45 -0800 Subject: [PATCH 0261/2729] Update 902.Numbers-At-Most-N-Given-Digit-Set.cpp --- .../902.Numbers-At-Most-N-Given-Digit-Set.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Recursion/902.Numbers-At-Most-N-Given-Digit-Set/902.Numbers-At-Most-N-Given-Digit-Set.cpp b/Recursion/902.Numbers-At-Most-N-Given-Digit-Set/902.Numbers-At-Most-N-Given-Digit-Set.cpp index 99c713422..eff210bd9 100644 --- a/Recursion/902.Numbers-At-Most-N-Given-Digit-Set/902.Numbers-At-Most-N-Given-Digit-Set.cpp +++ b/Recursion/902.Numbers-At-Most-N-Given-Digit-Set/902.Numbers-At-Most-N-Given-Digit-Set.cpp @@ -12,12 +12,12 @@ class Solution { for (int i=1; i<=K-1; i++) count += pow(D.size(), i); - DFS(0, 0, D); + DFS(0, D); return count; } - void DFS(long cur, int pos, vector& D) + void DFS(int pos, vector& D) { if (pos==K) { @@ -30,7 +30,7 @@ class Solution { if ('0'+stoi(s) < num[pos]) count += pow( D.size(), K-1-pos); else if ('0'+stoi(s) == num[pos]) - DFS(cur*10+stoi(s), pos+1, D); + DFS(pos+1, D); } } }; From 927daad9c684c77c1f33a8a766b3c7d373cc0696 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Dec 2021 15:25:55 -0800 Subject: [PATCH 0262/2729] Update Readme.md --- DFS/332.Reconstruct-Itinerary/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/332.Reconstruct-Itinerary/Readme.md b/DFS/332.Reconstruct-Itinerary/Readme.md index 7f42ff56d..531104943 100644 --- a/DFS/332.Reconstruct-Itinerary/Readme.md +++ b/DFS/332.Reconstruct-Itinerary/Readme.md @@ -35,6 +35,6 @@ A -> B <-> F 那我们构造欧拉路径的思想是:B + path2 + path1,其中path1是从B点出发,选择任意支路并能够顺利走到终点的欧拉路径。path2是在path1走完之后,再从B点出发,最终走回B点的路径。注意,如果足够幸运,path1走遍了B后面的所有边,那么path2就不存在了。 -因为我们要最小化字典序,所以我们每次的分叉总会优先选择字典序较小的一支。如果这一支是类似上例中的"->D->E"这样直通到底的path1,那我们也无能为力,D注定是无法往前提的;否则的话我们就会先进入path2,从而更小化了整个欧拉路径的字典序。 +因为我们要最小化字典序,所以我们每次的分叉总会优先选择字典序较小的一支。有人会问,这样一定能得到欧拉路径吗?我们看上面的例子,在B点时,我们依据最小字典序会选择走D,即"->D->E",发现这是一条直通到底的path1;然后回溯到B点,此时再选择走F,得到“->F->B”,这其实是一个path2. 根据规则最终构建的路径是“B + path2 + path1”,可见依然保证是一条欧拉路径, [Leetcode Link](https://leetcode.com/problems/reconstruct-itinerary) From 7cd1668e862eab4663262c1730f44c0a2969a43e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Dec 2021 15:27:42 -0800 Subject: [PATCH 0263/2729] Update Readme.md --- DFS/332.Reconstruct-Itinerary/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/332.Reconstruct-Itinerary/Readme.md b/DFS/332.Reconstruct-Itinerary/Readme.md index 531104943..b466e1db9 100644 --- a/DFS/332.Reconstruct-Itinerary/Readme.md +++ b/DFS/332.Reconstruct-Itinerary/Readme.md @@ -31,7 +31,7 @@ -> D -> E A -> B <-> F ``` -如上述的例子(注意B->F和F->B是两条不同的边)。最理想的情况是一次遍历走完所有想走的点 B->F->B->D->E. 但是我们在B的支路选择上不可能总是这么幸运,可能会走这样一条路 B->D->E,这样走到了尽头。但是B还有另一条支路->F没有走,如果我们尝试继续走那一条的话,就是 B->F->B,然后停止,因为此时B没有任何未走过的边了。 +如上述的例子(注意B->F和F->B是两条不同的边)。最理想的情况是一次遍历走完所有想走的点 B->F->B->D->E. 但是我们在B的支路选择上不可能总是这么幸运,可能会走这样一条路 ->D->E,这样走到了尽头。但是B还有另一条支路->F没有走,此时我们再尝试走那一条支路的话,就是 ->F->B,然后停止(因为此时B没有任何未走过的出度了)。 那我们构造欧拉路径的思想是:B + path2 + path1,其中path1是从B点出发,选择任意支路并能够顺利走到终点的欧拉路径。path2是在path1走完之后,再从B点出发,最终走回B点的路径。注意,如果足够幸运,path1走遍了B后面的所有边,那么path2就不存在了。 From dbe9db416577f5fb2e8b27ddbb53fa2c8c736173 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Dec 2021 15:47:06 -0800 Subject: [PATCH 0264/2729] Create 2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp --- ...2.Sequentially-Ordinal-Rank-Tracker_v1.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp new file mode 100644 index 000000000..60984b4a0 --- /dev/null +++ b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp @@ -0,0 +1,30 @@ +class SORTracker { + set>Set; + set>::iterator iter; +public: + SORTracker() + { + Set.insert({INT_MIN, ""}); + iter = Set.begin(); + } + + void add(string name, int score) + { + Set.insert({-score, name}); + if (make_pair(-score, name) < *iter) + iter = prev(iter); + } + + string get() + { + iter = next(iter); + return iter->second; + } +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ From 7b0cd690e38c470b839281e6730729f1c496fb0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Dec 2021 15:47:39 -0800 Subject: [PATCH 0265/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2ef280215..f3f108a20 100644 --- a/Readme.md +++ b/Readme.md @@ -115,7 +115,8 @@ [1898.Maximum-Number-of-Removable-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1898.Maximum-Number-of-Removable-Characters) (H-) [1891.Cutting-Ribbons](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1891.Cutting-Ribbons) (E) [2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store) (M) -[2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) +[2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) +[2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) #### [Hash Table](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From 2d620d898a19eed1a46063a6bb8348662a7c63f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Dec 2021 15:50:22 -0800 Subject: [PATCH 0266/2729] Create 2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp --- ...2.Sequentially-Ordinal-Rank-Tracker_v2.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp new file mode 100644 index 000000000..5fc7f7802 --- /dev/null +++ b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp @@ -0,0 +1,38 @@ +#include // Common file +#include // Including tree_order_statistics_node_update +using namespace __gnu_pbds; + +typedef tree< +pair , +null_type, +less>, +rb_tree_tag, +tree_order_statistics_node_update> +ordered_set; + +class SORTracker { + ordered_set Set; + int i = 0; +public: + SORTracker() + { + } + + void add(string name, int score) + { + Set.insert({-score, name}); + } + + string get() + { + i++; + return Set.find_by_order(i-1)->second; + } +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ From 39507fc2ee048e0943c8635f41ef88126ebaaddf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Dec 2021 16:14:38 -0800 Subject: [PATCH 0267/2729] Create Readme.md --- Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md new file mode 100644 index 000000000..262227721 --- /dev/null +++ b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md @@ -0,0 +1,11 @@ +### 2102.Sequentially-Ordinal-Rank-Tracker + +#### 解法1 +本题乍看之下,需要一个既能自动排序(像Set)、又可以按照index来读取内容(像数组)的数据结构。通常情况下这种数据结构是很难得到的。但是本题暗藏的玄机在于,它并不是真正需要随机按index来读取数据,而是固定按照递增的顺序来读取。这就意味着,每次add和get的操作,最多只会影响待读取内容的指针往左右移动最多一位即可。 + +具体的说,我们维护一个有序集合的迭代器,指向当前的第i个位置(即下一个get所需要读取的index)。如果有新加入数据,并且新数据小于指针的数据,那么我们就可以将迭代器前移一位(用prev函数),这样依然指向的是第i个数据;如果新数据大于指针的数据,那么迭代器就不需要变化。遇到get操作时,就读取指针当前指向的内容,并且把迭代器后移一位即可(用next函数)。 + +注意为了能使得有序集合按照「分数」从大到小、「名字|从小到大的顺序排列,我们定义set>set,其中pair的第一个分量是-score。 + +#### 解法2 +可以直接使用pbds的数据库和find_by_order(k)这个API。参见[模版](https://github.com/wisdompeak/LeetCode/blob/master/Template/RB_Tree/ordered_set.cpp). From 452373485b84e535b569cc8c65c60249c9072929 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Dec 2021 16:59:39 -0800 Subject: [PATCH 0268/2729] Update and rename 496.Next Greater Element I.cpp to 496.Next-Greater-Element-I.cpp --- .../496.Next Greater Element I.cpp | 29 ------------------- .../496.Next-Greater-Element-I.cpp | 28 ++++++++++++++++++ 2 files changed, 28 insertions(+), 29 deletions(-) delete mode 100644 Stack/496.Next-Greater-Element-I/496.Next Greater Element I.cpp create mode 100644 Stack/496.Next-Greater-Element-I/496.Next-Greater-Element-I.cpp diff --git a/Stack/496.Next-Greater-Element-I/496.Next Greater Element I.cpp b/Stack/496.Next-Greater-Element-I/496.Next Greater Element I.cpp deleted file mode 100644 index b976c0380..000000000 --- a/Stack/496.Next-Greater-Element-I/496.Next Greater Element I.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution { -public: - vector nextGreaterElement(vector& findNums, vector& nums) - { - stackStack; - unordered_mapMap; - - for (int i=0; iresults; - for (int i=0; inextGreater; +public: + vector nextGreaterElement(vector& nums1, vector& nums2) + { + int n = nums2.size(); + stackStack; // index + for (int i = 0; i < n; i++) + { + while (!Stack.empty() && nums2[Stack.top()] < nums2[i]) + { + nextGreater[nums2[Stack.top()]] = nums2[i]; + Stack.pop(); + } + Stack.push(i); + } + + vectorrets; + for (int x: nums1) + { + if (nextGreater.find(x)==nextGreater.end()) + rets.push_back(-1); + else + rets.push_back(nextGreater[x]); + } + return rets; + } +}; From 8e0d89669b8cd9b4fe76b21d2b1b732026793b4f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Dec 2021 17:22:53 -0800 Subject: [PATCH 0269/2729] Create 2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp --- ...Fruits-Harvested-After-at-Most-K-Steps.cpp | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp diff --git a/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp b/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp new file mode 100644 index 000000000..a6101b31d --- /dev/null +++ b/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp @@ -0,0 +1,65 @@ +class Solution { +public: + int maxTotalFruits(vector>& fruits, int startPos, int k) + { + int n = fruits.size(); + vectorpos(n); + vectorval(n); + for (int i=0; ipresum(n); + int cur = 0; + for (int i=0; i=0 && pos[j]>startPos) j--; + for (int i=n-1; i>=0 && pos[i]>=startPos; i--) + { + while (j>=0 && (pos[i]-startPos+(startPos-pos[j])*2 <=k)) + { + + ret = max(ret, presum[i] - (j==0?0:presum[j-1])); + j--; + } + } + + int i = upper_bound(pos.begin(), pos.end(), startPos) - pos.begin()-1; + int sum = 0; + while (i>=0 && startPos-pos[i]<=k) + { + sum += val[i]; + i--; + } + ret = max(ret, sum); + + i = lower_bound(pos.begin(), pos.end(), startPos) - pos.begin(); + sum = 0; + while (i Date: Sun, 19 Dec 2021 17:25:12 -0800 Subject: [PATCH 0270/2729] Rename Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp to Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp --- .../2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp => Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp (100%) diff --git a/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp similarity index 100% rename from Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps.cpp rename to Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp From 238e118fcabbe4dd564f6aa4823bcb2f1517bb74 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Dec 2021 22:40:54 -0800 Subject: [PATCH 0271/2729] Create 2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp --- ...its-Harvested-After-at-Most-K-Steps_v2.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp new file mode 100644 index 000000000..d9a5ede21 --- /dev/null +++ b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int maxTotalFruits(vector>& fruits, int startPos, int k) + { + int n = fruits.size(); + vectorpos(n); + vectorpresum(n); + for (int i=0; i=0 && j=0 && j Date: Sun, 19 Dec 2021 22:41:37 -0800 Subject: [PATCH 0272/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f3f108a20..2e412fd2b 100644 --- a/Readme.md +++ b/Readme.md @@ -80,6 +80,7 @@ [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) +[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H-) * ``Binary Processing`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) From 2a603399a574c83697825db25927a18eac747e81 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Dec 2021 23:16:44 -0800 Subject: [PATCH 0273/2729] Create Readme.md --- .../Readme.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md new file mode 100644 index 000000000..6b9e64e69 --- /dev/null +++ b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md @@ -0,0 +1,4 @@ +### 2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps + +#### 解法1:双指针 + From bcdb49c33ff61fc930950470931bcc073fac43d7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Dec 2021 23:17:25 -0800 Subject: [PATCH 0274/2729] Update 2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp --- ...its-Harvested-After-at-Most-K-Steps_v1.cpp | 64 ++++++------------- 1 file changed, 18 insertions(+), 46 deletions(-) diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp index a6101b31d..47c93728b 100644 --- a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp +++ b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp @@ -4,61 +4,33 @@ class Solution { { int n = fruits.size(); vectorpos(n); - vectorval(n); - for (int i=0; ipresum(n); - int cur = 0; for (int i=0; i=0; i--) { - while (j=startPos && startPos-pos[i]+(pos[j]-startPos)*2 > k) + j--; + if (pos[j]>=startPos) ret = max(ret, presum[j] - (i==0?0:presum[i-1])); + else if (startPos-pos[i] <= k) ret = max(ret, presum[j] - (i==0?0:presum[i-1])); } - - j = n-1; - while (j>=0 && pos[j]>startPos) j--; - for (int i=n-1; i>=0 && pos[i]>=startPos; i--) + + mid = lower_bound(pos.begin(), pos.end(), startPos) - pos.begin(); + j = 0; + for (int i=mid; i=0 && (pos[i]-startPos+(startPos-pos[j])*2 <=k)) - { - - ret = max(ret, presum[i] - (j==0?0:presum[j-1])); - j--; - } - } - - int i = upper_bound(pos.begin(), pos.end(), startPos) - pos.begin()-1; - int sum = 0; - while (i>=0 && startPos-pos[i]<=k) - { - sum += val[i]; - i--; - } - ret = max(ret, sum); - - i = lower_bound(pos.begin(), pos.end(), startPos) - pos.begin(); - sum = 0; - while (i k) + j++; + if (pos[j]<=startPos) ret = max(ret, presum[i] - (j==0?0:presum[j-1])); + else if (pos[i]-startPos <= k) ret = max(ret, presum[i] - (j==0?0:presum[j-1])); } - ret = max(ret, sum); return ret; } From 29dbdd73d60541b61f59ae5ce4256f44d3130ce2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Dec 2021 23:18:07 -0800 Subject: [PATCH 0275/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2e412fd2b..83012033d 100644 --- a/Readme.md +++ b/Readme.md @@ -42,6 +42,7 @@ [2009.Minimum-Number-of-Operations-to-Make-Array-Continuous](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2009.Minimum-Number-of-Operations-to-Make-Array-Continuous) (M+) [2024.Maximize-the-Confusion-of-an-Exam](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam) (M) [424.Longest-Repeating-Character-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/424.Longest-Repeating-Character-Replacement) (H-) +[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) @@ -80,7 +81,7 @@ [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) -[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H-) +[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) * ``Binary Processing`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) From fd4206c83e11a80e8c067b77516cb7531bfe68be Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Dec 2021 23:45:35 -0800 Subject: [PATCH 0276/2729] Update 2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp --- ...its-Harvested-After-at-Most-K-Steps_v1.cpp | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp index 47c93728b..4e77631a7 100644 --- a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp +++ b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp @@ -12,17 +12,8 @@ class Solution { } int ret = 0; - int mid = upper_bound(pos.begin(), pos.end(), startPos) - pos.begin(); - int j = n-1; - for (int i=mid-1; i>=0; i--) - { - while (pos[j]>=startPos && startPos-pos[i]+(pos[j]-startPos)*2 > k) - j--; - if (pos[j]>=startPos) ret = max(ret, presum[j] - (i==0?0:presum[i-1])); - else if (startPos-pos[i] <= k) ret = max(ret, presum[j] - (i==0?0:presum[i-1])); - } - mid = lower_bound(pos.begin(), pos.end(), startPos) - pos.begin(); + int mid = lower_bound(pos.begin(), pos.end(), startPos) - pos.begin(); j = 0; for (int i=mid; i=0; i--) + { + while (pos[j]>=startPos && startPos-pos[i]+(pos[j]-startPos)*2 > k) + j--; + if (pos[j]>=startPos) ret = max(ret, presum[j] - (i==0?0:presum[i-1])); + else if (startPos-pos[i] <= k) ret = max(ret, presum[j] - (i==0?0:presum[i-1])); + } + + return ret; } From bb57dab4961e665441f94e5ac9027190be9e693f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Dec 2021 23:52:16 -0800 Subject: [PATCH 0277/2729] Update 2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp --- ...its-Harvested-After-at-Most-K-Steps_v2.cpp | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp index d9a5ede21..e47010ddd 100644 --- a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp +++ b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp @@ -12,25 +12,24 @@ class Solution { } int ret = 0; - for (int i=0; i=0 && j=0 && j k) break; + double d = (k-(pos[i]-startPos))/2; + int j = lower_bound(pos.begin(), pos.end(), startPos-d) - pos.begin(); + if (j>=0 && j=0; i--) + { + if (startPos - pos[i] > k) break; + double d = (k-(startPos-pos[i]))/2; + int j = upper_bound(pos.begin(), pos.end(), startPos+d) - pos.begin() - 1; + if (j>=0 && j Date: Sun, 19 Dec 2021 23:54:02 -0800 Subject: [PATCH 0278/2729] Update Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md index 6b9e64e69..04760f795 100644 --- a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md +++ b/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md @@ -1,4 +1,19 @@ ### 2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps #### 解法1:双指针 +首先我们要明确最优解的pattern,一定是往一个方向走x步到A,再返回起点(必然同样走了x步),再往另一个方向走y步到B。需要满足的约束是2x+y<=k. 注意,其中x不是必须的,可以为0. +我们不妨假设A和B分别在startPos的左边和右边。我们可以有这么一个发现:因为约束关系的存在,如果B点朝右变动,则A也不得不朝右变动。于是我们就有了滑动窗口的思想。我们从左往右尝试所有大于等于startPos的水果位置作为B,相应地为了满足约束,必然单调地从左往右单调移动A的位置,当使得恰好满足约束时AB的距离必然最远,能够得到的收获区间[A,B]也是最大的(在B点固定的情况下)。 + +注意这里有一个特殊的情况。当A点跨过了startPos时,A点的意义已经失效。这个时候我们需要检查x=0情况下,B点本身是否是一个可行解。即如果```pos[B]-startPos<=k```,那么此时双闭区间[A,B]内的val都是有效答案。 + +同理,我们在假设A和B分别在startPos的右边和左边。此时我们从右往左尝试所有小于等于startPos的水果位置作为B,相应地我们要把A从右往左单调地移动直至满足约束条件。此时[B,A]也是在固定B的情况下的最大收获区间。 + +这个解法是o(n)。 + +#### 解法2:二分搜值 +将以上的解法稍微改动一下,确定了B点之后,我们对于A点的期望也就有了,可以直接在pos里二分。 + +假如B是在startPos的右边,那么我们就希望A是大于等于```startPos - (k-y)/2```的第一个位置。这样双闭区间[A,B]就是我们的最大收获。注意我们需要判定A是否合法。 + +同理假如B是在startPos的左边,那么我们就希望A是小于等于```startPos + (k-y)/2```的最后一个位置。这样双闭区间[B,A]就是我们的最大收获。同样我们需要判定A是否合法。 From 4077d32d89a3ed337ecc103785818b790e72da3c Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Sun, 19 Dec 2021 23:55:22 -0800 Subject: [PATCH 0279/2729] mv 2106 --- .../2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp | 0 .../2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp | 0 .../2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {Binary_Search => Two_Pointers}/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp (100%) rename {Binary_Search => Two_Pointers}/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp (100%) rename {Binary_Search => Two_Pointers}/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md (100%) diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp b/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp similarity index 100% rename from Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp rename to Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v1.cpp diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp b/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp similarity index 100% rename from Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp rename to Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps_v2.cpp diff --git a/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md b/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md similarity index 100% rename from Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md rename to Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps/Readme.md From d484570078543e8e1586e808c1ad9704b8875999 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Dec 2021 23:56:08 -0800 Subject: [PATCH 0280/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 83012033d..10a3d60b6 100644 --- a/Readme.md +++ b/Readme.md @@ -42,7 +42,7 @@ [2009.Minimum-Number-of-Operations-to-Make-Array-Continuous](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2009.Minimum-Number-of-Operations-to-Make-Array-Continuous) (M+) [2024.Maximize-the-Confusion-of-an-Exam](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam) (M) [424.Longest-Repeating-Character-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/424.Longest-Repeating-Character-Replacement) (H-) -[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) +[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) @@ -81,7 +81,7 @@ [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) -[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) +[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) * ``Binary Processing`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) From 4ed0b1df76bf6d9bbc05509f66c101024f86a6d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Dec 2021 06:10:57 -0800 Subject: [PATCH 0281/2729] Create 2111.Minimum-Operations-to-Make-the-Array-K-Increasing.cpp --- ...rations-to-Make-the-Array-K-Increasing.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing/2111.Minimum-Operations-to-Make-the-Array-K-Increasing.cpp diff --git a/Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing/2111.Minimum-Operations-to-Make-the-Array-K-Increasing.cpp b/Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing/2111.Minimum-Operations-to-Make-the-Array-K-Increasing.cpp new file mode 100644 index 000000000..852d2845b --- /dev/null +++ b/Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing/2111.Minimum-Operations-to-Make-the-Array-K-Increasing.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int kIncreasing(vector& arr, int k) + { + int ret = 0; + int n = arr.size(); + + for (int t=0; tnums; + for (int i=t; i& nums) + { + int n = nums.size(); + vectorq(n, INT_MAX); + for (int i=0; i= 0; i--) + { + if (q[i] != INT_MAX) + return i + 1; + } + return 0; + } +}; From 9d6f11398e3177c8a1b68c61acd06236b22b6f8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Dec 2021 06:11:33 -0800 Subject: [PATCH 0282/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 10a3d60b6..6d17f2026 100644 --- a/Readme.md +++ b/Readme.md @@ -1030,6 +1030,7 @@ [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) [1713.Minimum-Operations-to-Make-a-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1713.Minimum-Operations-to-Make-a-Subsequence) (H-) [1964.Find-the-Longest-Valid-Obstacle-Course-at-Each-Position](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1964.Find-the-Longest-Valid-Obstacle-Course-at-Each-Position) (M+) +[2111.Minimum-Operations-to-Make-the-Array-K-Increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing) (M+) * ``Two-pass distribution`` [135.Candy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/135.Candy) (M+) [1840.Maximum-Building-Height](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1840.Maximum-Building-Height) (H) From 9e11b0b5cc78264dcfbb88dba1f92c028c8619b2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Dec 2021 06:23:00 -0800 Subject: [PATCH 0283/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing/Readme.md diff --git a/Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing/Readme.md b/Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing/Readme.md new file mode 100644 index 000000000..e6073f72a --- /dev/null +++ b/Greedy/2111.Minimum-Operations-to-Make-the-Array-K-Increasing/Readme.md @@ -0,0 +1,7 @@ +### 2111.Minimum-Operations-to-Make-the-Array-K-Increasing + +此题的本质就是在每个k间隔的系列里找到最长递增子序列的长度,其余未被选定的元素只需要使之与相邻的元素相同即可。这样这些未被选中的元素就对应着最少需要修改的数目。 + +这里的一个细节是:本题的LIS允许相同的元素。所以贪心法的时候需要用upper_bound。 + +此外有一个followup:如果要求构造所有元素为正、且严格的递增序列怎么办?这里会出现的一个问题是,找到LIS之后,其他元素的改动可能无法实现。比如[1,1,2],最长严格递增序列是[1,2],但是你无法只修改一个数字得到合法的解。方法是,将所有的元素都减去其下标(1,2,3...),然后去除掉负数,在其中找LIS(更确切的说是非递减序列)。在这个例子中,变换后的数组是[0,-1,-1]。所以其LIS的长度其实只有1. 去掉负数的那些元素k无论如何都无法成为一个严格递增序列里面的成员,原因是它之前的元素个数太少,即使第一个元素从1开始以公差1递增,到该元素时也超过了k本身。 From df977d081fc79fa2afeae86f11f5f9f1bbb9a397 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Dec 2021 14:52:52 -0800 Subject: [PATCH 0284/2729] Update 2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp --- ...ons-From-a-Binary-Tree-Node-to-Another.cpp | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp index 6a4b77b72..411258d2e 100644 --- a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp +++ b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another.cpp @@ -13,42 +13,37 @@ class Solution { public: string getDirections(TreeNode* root, int startValue, int destValue) { - vectornums1, nums2; string dirs1, dirs2; - dfs(root, nums1, dirs1, startValue); - dfs(root, nums2, dirs2, destValue); - + dfs(root, dirs1, startValue); + dfs(root, dirs2, destValue); + int k = 0; - while (k&nums, string&dirs, int target) + + bool dfs(TreeNode* node, string& dirs, int target) { if (node==NULL) return false; if (node->val == target) return true; + if (node->left) { - nums.push_back(node->left->val); dirs.push_back('L'); - if (dfs(node->left, nums, dirs, target)) + if (dfs(node->left, dirs, target)) return true; - nums.pop_back(); dirs.pop_back(); } if (node->right) { - nums.push_back(node->right->val); dirs.push_back('R'); - if (dfs(node->right, nums, dirs, target)) + if (dfs(node->right, dirs, target)) return true; - nums.pop_back(); dirs.pop_back(); } return false; } - }; From 828f9c42bf51e36f025160f0d7293933a9715811 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Dec 2021 14:53:24 -0800 Subject: [PATCH 0285/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/Readme.md b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/Readme.md index 75a4a278d..5019659f6 100644 --- a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/Readme.md +++ b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/Readme.md @@ -2,4 +2,4 @@ 本题和以往求LCA的题目不同。以往的LCA只需要求得LCA的节点本身,而这道题需要设计到路径打印。因此我们就老老实实地用递归的方法,把从root到q或者q的路径先记录出来,然后再比较得到LCA的位置。 -注意此题中我们需要记录两个信息,首先是从root到p(或者q)一路上遇到的节点数值,另外是一路上的操作(L或者R)。假设两条路径dirs1和dirs2在第k个节点位置分叉(也就是LCA的位置)。根据题意,我们就将dirs1[k:]全部搞成“U”(因为从p到LCA一路都是up),再拼接上dirs2[k:]这段路径即可。 +此题中我们需要记录从root到p(或者q)一路上的操作(L或者R)。假设两条路径dirs1和dirs2在第k个节点位置分叉(也就是LCA的位置)。根据题意,我们就将dirs1[k:]全部搞成“U”(因为从p到LCA一路都是up),再拼接上dirs2[k:]这段路径即可。 From 354fac28a3b784ddd186f59cec586849f435e67c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 23 Dec 2021 01:13:54 -0800 Subject: [PATCH 0286/2729] Create 2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp --- ...2.Sequentially-Ordinal-Rank-Tracker_v3.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp new file mode 100644 index 000000000..07b59d966 --- /dev/null +++ b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp @@ -0,0 +1,39 @@ +using PIS = pair; +class SORTracker { + priority_queuepq1; + priority_queue,greater<>>pq2; + PIS cur; +public: + SORTracker() + { + pq1.push({INT_MIN, "#"}); + } + + void add(string name, int score) + { + PIS temp = make_pair(-score, name); + if (temp > pq1.top()) + pq2.push(temp); + else + { + pq2.push(pq1.top()); + pq1.pop(); + pq1.push(temp); + } + } + + string get() + { + auto temp = pq2.top(); + pq1.push(temp); + pq2.pop(); + return temp.second; + } +}; + +/** + * Your SORTracker object will be instantiated and called as such: + * SORTracker* obj = new SORTracker(); + * obj->add(name,score); + * string param_2 = obj->get(); + */ From 2b1160615576e12ca5f5393d04aefd7bcf71c45a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 23 Dec 2021 01:14:21 -0800 Subject: [PATCH 0287/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6d17f2026..d20251a66 100644 --- a/Readme.md +++ b/Readme.md @@ -378,6 +378,7 @@ [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) +[2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) * ``Sort+PQ`` [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) From 6879d3331f62609a519748a63bd6fdf49c1bff29 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 23 Dec 2021 01:24:31 -0800 Subject: [PATCH 0288/2729] Update Readme.md --- Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md index 262227721..2e1bbbe56 100644 --- a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md +++ b/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md @@ -9,3 +9,10 @@ #### 解法2 可以直接使用pbds的数据库和find_by_order(k)这个API。参见[模版](https://github.com/wisdompeak/LeetCode/blob/master/Template/RB_Tree/ordered_set.cpp). + +#### 解法3 +设置两个优先队列pq1(大顶堆,出口是最大值),pq2(小顶堆,出口是最小值).我们始终保持pq1含有i-1个元素。 + +如果有新元素X进来,我们与pq1的出口元素Y比较: +1. 如果Y更靠前的话,直接把X加入pq2,pq2出口处自动更新为当前全局的第i大元素。 +2. 如果X更靠前,那么Y就会被挤成第i大元素,所以将Y从pq1移出加入pq2,并把X加入pq1.这样pq2的出口处依然是全局的第i大元素。 From 7138bc1cd167b881cb5f04d54347b976149f0973 Mon Sep 17 00:00:00 2001 From: Fenghe Xu Date: Thu, 23 Dec 2021 18:45:37 +0800 Subject: [PATCH 0289/2729] Create 1740.Find-Distance-in-a-Binary-Tree_v2.cpp Calculate the distance by recording tree depth of each relevant node. --- ...1740.Find-Distance-in-a-Binary-Tree_v2.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Tree/1740.Find-Distance-in-a-Binary-Tree/1740.Find-Distance-in-a-Binary-Tree_v2.cpp diff --git a/Tree/1740.Find-Distance-in-a-Binary-Tree/1740.Find-Distance-in-a-Binary-Tree_v2.cpp b/Tree/1740.Find-Distance-in-a-Binary-Tree/1740.Find-Distance-in-a-Binary-Tree_v2.cpp new file mode 100644 index 000000000..4812fb449 --- /dev/null +++ b/Tree/1740.Find-Distance-in-a-Binary-Tree/1740.Find-Distance-in-a-Binary-Tree_v2.cpp @@ -0,0 +1,34 @@ +/** + * 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 { + int lcaDepth = -1, pDepth, qDepth; + TreeNode* lcaNode; + int lowestCommonAncestor(TreeNode* root, int p, int q, int depth) { + if(!root) return 0; + + int count = lowestCommonAncestor(root->left, p, q, depth + 1) + + lowestCommonAncestor(root->right, p, q, depth + 1) + + (root->val == p) + (root->val == q); + + if(root->val == p) pDepth = depth; + if(root->val == q) qDepth = depth; + if(count == 2 && lcaDepth == -1) lcaDepth = depth; + + return count; + } +public: + int findDistance(TreeNode* root, int p, int q) { + lowestCommonAncestor(root, p, q, 0); + + return (pDepth - lcaDepth) + (qDepth - lcaDepth); + } +}; From 1d8f4ebf88473a298068c65e366c7740ca853d09 Mon Sep 17 00:00:00 2001 From: gma Date: Fri, 31 Dec 2021 23:29:26 -0500 Subject: [PATCH 0290/2729] add cmake/tests and onboard a edit distance solution with compressed memory usage --- .gitignore | 2 + CMakeLists.txt | 10 ++++ .../072.Edit-Distance/072.Edit-Distance.cpp | 49 +++++++++++++++++++ Readme.md | 2 +- tests/CMakeLists.txt | 12 +++++ .../072.Edit-Distance/072.Edit-Distance.t.cpp | 17 +++++++ .../072.Edit-Distance/CMakeLists.txt | 9 ++++ tests/Dynamic_Programming/CMakeLists.txt | 1 + 8 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 tests/CMakeLists.txt create mode 100644 tests/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.t.cpp create mode 100644 tests/Dynamic_Programming/072.Edit-Distance/CMakeLists.txt create mode 100644 tests/Dynamic_Programming/CMakeLists.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..84610780c --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build +.idea diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..19850dfb6 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.10) + +project(LeetCode VERSION 1.0) + +set (CMAKE_CXX_STANDARD 11) + +include_directories(PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + +enable_testing() +add_subdirectory(tests) \ No newline at end of file diff --git a/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.cpp b/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.cpp index 90aa3f6b9..43a03d2a9 100644 --- a/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.cpp +++ b/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.cpp @@ -30,4 +30,53 @@ class Solution { return dp[n1][n2]; } + + /** + * @brief calculate the minimum edit distance between word1 and word2 + * Another implementation of edit distance with compressed memory usage + * @param word1 const std::string & The reference of first string + * @param word2 const std::string & The reference of second string + * @return The edit distance + */ + int minDistance2(const std::string &word1, const std::string &word2) + { + int n1=word1.size(); + int n2=word2.size(); + + // dp[i][j] : edit distance between word1[0, i) and word2[0, j) + // dp[i][j] = std::min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 + // ---------- ---------- ------------- + // add-j delete-j replace-j + // if word1[i] != word2[j] + // Compressed to + // dp[j] + + std::vector dp(n2+1, 0); + + for (auto j = 1; j <= n2; ++j) + dp[j] = j; // distance between word1[0, 0) and word2[0, j), j deletions + + for (auto i = 1; i <= n1; ++i) + { + int topleft = dp[0]; + // reset dp[i] + dp[0] = i; // edit distance = j add operations + + for (auto j = 1; j <= n2; ++j) + { + int top = dp[j]; + + if (word1[i-1] == word2[j-1]) + dp[j] = topleft; + else + dp[j] = std::min({dp[j-1], top, topleft}) + 1; + // -------- --- --------- + // delete-j add-j replace-j + + topleft = top; // move the top 1 step to the right + } + } + + return dp.back(); + } }; diff --git a/Readme.md b/Readme.md index d20251a66..74d66278e 100644 --- a/Readme.md +++ b/Readme.md @@ -1195,4 +1195,4 @@ [Bit_Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Template/Bit_manipulation) [Combination-Number](https://github.com/wisdompeak/LeetCode/tree/master/Template/Combination-Number) [RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) -[CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) +[CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 000000000..466d54d9e --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,12 @@ +include(FetchContent) + +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip +) + +FetchContent_MakeAvailable(googletest) + +include(GoogleTest) + +add_subdirectory(Dynamic_Programming) \ No newline at end of file diff --git a/tests/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.t.cpp b/tests/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.t.cpp new file mode 100644 index 000000000..0c830b7cb --- /dev/null +++ b/tests/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.t.cpp @@ -0,0 +1,17 @@ +#include "gtest/gtest.h" +#include // INT_MAX +#include // std::min({}) +#include +#include +using namespace std; + +#include + +TEST(edit_distance_72_test, I) +{ + std::string word1 = "horse"; + std::string word2 = "ros"; + + ASSERT_EQ(Solution().minDistance2(word1, word2), 3); + ASSERT_EQ(Solution().minDistance(word1, word2), 3); +} diff --git a/tests/Dynamic_Programming/072.Edit-Distance/CMakeLists.txt b/tests/Dynamic_Programming/072.Edit-Distance/CMakeLists.txt new file mode 100644 index 000000000..ea944f088 --- /dev/null +++ b/tests/Dynamic_Programming/072.Edit-Distance/CMakeLists.txt @@ -0,0 +1,9 @@ +set(BINARY edit_distance_test) + +add_executable(${BINARY} 072.Edit-Distance.t.cpp) + +target_link_libraries(${BINARY} gtest_main) + +include(GoogleTest) + +gtest_discover_tests(${BINARY}) \ No newline at end of file diff --git a/tests/Dynamic_Programming/CMakeLists.txt b/tests/Dynamic_Programming/CMakeLists.txt new file mode 100644 index 000000000..c97e1cf09 --- /dev/null +++ b/tests/Dynamic_Programming/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(072\.Edit-Distance) \ No newline at end of file From 67ab597a9a33374c25deb9c8c29bf83b90b9a474 Mon Sep 17 00:00:00 2001 From: gma Date: Fri, 31 Dec 2021 23:42:27 -0500 Subject: [PATCH 0291/2729] add test case for benchmark --- .../072.Edit-Distance/072.Edit-Distance.t.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/tests/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.t.cpp b/tests/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.t.cpp index 0c830b7cb..654ee3b18 100644 --- a/tests/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.t.cpp +++ b/tests/Dynamic_Programming/072.Edit-Distance/072.Edit-Distance.t.cpp @@ -5,6 +5,11 @@ #include using namespace std; +#include +#include + +#include // benchmark + #include TEST(edit_distance_72_test, I) @@ -15,3 +20,58 @@ TEST(edit_distance_72_test, I) ASSERT_EQ(Solution().minDistance2(word1, word2), 3); ASSERT_EQ(Solution().minDistance(word1, word2), 3); } + +TEST(edit_distance_72_test, II) +{ + std::string word1 = "intention"; + std::string word2 = "execution"; + + ASSERT_EQ(Solution().minDistance2(word1, word2), 5); + ASSERT_EQ(Solution().minDistance(word1, word2), 5); +} + +TEST(edit_distance_72_test, benchmark) +{ + static std::string alnums = + "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; + + static std::size_t len = 1000; + + std::string rand1; + rand1.reserve(len); + + for (auto i = 0; i != len; ++i) + rand1.append(1, alnums[rand() % alnums.size()]); + + std::string rand2; + rand2.reserve(len); + + for (auto i = 0; i != len; ++i) + rand2.append(1, alnums[rand() % alnums.size()]); + + int ed1 = 0; + int ed2 = 0; + Solution s; + + { + auto start = chrono::steady_clock::now(); + ed1 = s.minDistance(rand1, rand2); + auto end = chrono::steady_clock::now(); + + printf("time cost of minDistance is %ld [ms]\n", + chrono::duration_cast(end - start).count()); + } + + { + auto start = chrono::steady_clock::now(); + ed2 = s.minDistance2(rand1, rand2); + auto end = chrono::steady_clock::now(); + + printf("time cost of minDistance2 is %ld [ms]\n", + chrono::duration_cast(end - start).count()); + } + + ASSERT_EQ(ed1, ed2); +} \ No newline at end of file From fa7a34f57deac123b761a5c007b4ebeeab3b575b Mon Sep 17 00:00:00 2001 From: gma Date: Sat, 1 Jan 2022 02:01:46 -0500 Subject: [PATCH 0292/2729] resolve the TLE issue by replacing unordered_map to vector --- .../1027.Longest-Arithmetic-Sequence.cpp | 60 ++++++++++++++----- .../1027.Longest-Arithmetic-Sequence.t.cpp | 27 +++++++++ .../CMakeLists.txt | 9 +++ tests/Dynamic_Programming/CMakeLists.txt | 3 +- 4 files changed, 82 insertions(+), 17 deletions(-) create mode 100644 tests/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.t.cpp create mode 100644 tests/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/CMakeLists.txt diff --git a/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.cpp b/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.cpp index 7c17dbfff..a770b3b66 100644 --- a/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.cpp +++ b/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.cpp @@ -1,21 +1,49 @@ class Solution { public: - int longestArithSeqLength(vector& A) + int longestArithSeqLength(vector& nums) + { + // dynamic algorithm to solve longest arith sequence length + // dp[i][diff] = dp[j][diff] + 1 if diff exist in dp[j] + // else 2 + // where j < i + // and, it is guaranteed that if diff exists in both j and k where j < k + // dp[j][diff] <= dp[k][diff] + + int n = nums.size(); + + static int lASL_MAX = 1000; + static int lASL_MIN = 2; + + // the maximum diff to form a longer arith sequence by looking forward + static int DIFF = (lASL_MAX-lASL_MIN)/2; + + // biggest size the diff array should be maintained + static int DIFF_MAX_SIZE = 2 * DIFF + 1; + + // the 2d dp array, row label is array index, column label is diff + DIFF + + // if one num is not formed an arith sequence, we think it has potential + // to form any arith sequence + std::vector> dp(n, std::vector(DIFF_MAX_SIZE, 1)); + + int lasl = 2; + + for (auto r = 0; r != n; ++r) { - vector>dp(A.size()); - int result = 1; - for (int i=0; i DIFF || diff < -DIFF) + continue; + + diff += DIFF; + + dp[r][diff] = dp[l][diff] + 1; + + lasl = std::max(lasl, dp[r][diff]); + } } + + return lasl; + } }; diff --git a/tests/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.t.cpp b/tests/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.t.cpp new file mode 100644 index 000000000..487b9a65b --- /dev/null +++ b/tests/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.t.cpp @@ -0,0 +1,27 @@ +#include "gtest/gtest.h" +#include +#include +using namespace std; + +#include + +TEST(longest_arithmetic_sequence_test, I) +{ + std::vector arr{3,6,9,12}; + + ASSERT_EQ(Solution().longestArithSeqLength(arr), 4); +} + +TEST(longest_arithmetic_sequence_test, II) +{ + std::vector arr{9,4,7,2,10}; + + ASSERT_EQ(Solution().longestArithSeqLength(arr), 3); +} + +TEST(longest_arithmetic_sequence_test, III) +{ + std::vector arr{20,1,15,3,10,5,8}; + + ASSERT_EQ(Solution().longestArithSeqLength(arr), 4); +} diff --git a/tests/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/CMakeLists.txt b/tests/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/CMakeLists.txt new file mode 100644 index 000000000..847e99db9 --- /dev/null +++ b/tests/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/CMakeLists.txt @@ -0,0 +1,9 @@ +set(BINARY longest_arithmetic_sequence_test) + +add_executable(${BINARY} 1027.Longest-Arithmetic-Sequence.t.cpp) + +target_link_libraries(${BINARY} gtest_main) + +include(GoogleTest) + +gtest_discover_tests(${BINARY}) \ No newline at end of file diff --git a/tests/Dynamic_Programming/CMakeLists.txt b/tests/Dynamic_Programming/CMakeLists.txt index c97e1cf09..f7ea05ddf 100644 --- a/tests/Dynamic_Programming/CMakeLists.txt +++ b/tests/Dynamic_Programming/CMakeLists.txt @@ -1 +1,2 @@ -add_subdirectory(072\.Edit-Distance) \ No newline at end of file +add_subdirectory(072\.Edit-Distance) +add_subdirectory(1027.Longest-Arithmetic-Sequence) \ No newline at end of file From 9ff360bfc9569622e32f351930e7091fc1d89398 Mon Sep 17 00:00:00 2001 From: gma Date: Sat, 1 Jan 2022 18:50:04 -0500 Subject: [PATCH 0293/2729] improve the time performance of 1036 --- .../1036.Escape-a-Large-Maze.cpp | 125 ++++++++++-------- .../1036.Escape-a-Large-Maze.t.cpp | 66 +++++++++ .../1036.Escape-a-Large-Maze/CMakeLists.txt | 9 ++ tests/BFS/CMakeLists.txt | 1 + tests/CMakeLists.txt | 1 + 5 files changed, 149 insertions(+), 53 deletions(-) create mode 100644 tests/BFS/1036.Escape-a-Large-Maze/1036.Escape-a-Large-Maze.t.cpp create mode 100644 tests/BFS/1036.Escape-a-Large-Maze/CMakeLists.txt create mode 100644 tests/BFS/CMakeLists.txt diff --git a/BFS/1036.Escape-a-Large-Maze/1036.Escape-a-Large-Maze.cpp b/BFS/1036.Escape-a-Large-Maze/1036.Escape-a-Large-Maze.cpp index cbb54f9de..59e2e7796 100644 --- a/BFS/1036.Escape-a-Large-Maze/1036.Escape-a-Large-Maze.cpp +++ b/BFS/1036.Escape-a-Large-Maze/1036.Escape-a-Large-Maze.cpp @@ -1,57 +1,76 @@ class Solution { + +private: + using point_t = std::vector; + + static inline uint64_t hash(const point_t &p) + { + return p[0] * 1e6 + p[1]; + } + public: - bool isEscapePossible(vector>& blocked, vector& source, vector& target) + bool isEscapePossible(vector>& blocked, + vector& source, + vector& target) + { + // blocked points set, uint64_t is selected since it is larger than 1e6*le6 + std::unordered_set bps; + + for (auto &x: blocked) + bps.insert(hash(x)); + + auto e1 = enclose(source, bps, target); + auto e2 = enclose(target, bps, source); + + return !e1 && !e2; + } + +private: + bool enclose(const point_t &s, + const std::unordered_set & b, + const point_t &d) + { + int max_points = (1+b.size()-1) * b.size()/2; + + std::deque Q; + Q.push_back(s); + + std::unordered_set visited; + visited.insert(hash(s)); + + while (!Q.empty() && visited.size() <= max_points) { - if (blocked.size()<=1) return true; - unordered_setblocks; - for (auto b:blocked) - blocks.insert(to_string(b[0])+"#"+to_string(b[1])); - - if (enclose(source,target,blocks) || enclose(target,source,blocks)) - return false; - else - return true; + int &r = Q.front()[0]; + int &c = Q.front()[1]; + + static std::vector> ds + { + {0, 1}, {-1, 0}, {0, -1}, {1, 0} + }; + + for (auto &dir: ds) + { + auto rr = r + dir.first; + auto cc = c + dir.second; + + std::vector p{rr, cc}; + + if (rr < 0 || rr >= 1e6 || // out of bound + cc < 0 || cc >= 1e6 || // out of bound + visited.find(hash(p)) != visited.end()|| // visited + b.find(hash(p)) != b.end() ) // blocked + continue; + + if (p == d) // reached out to destination + return false; + + Q.push_back(p); + visited.insert(hash(p)); + } + + Q.pop_front(); } - - bool enclose(vector& source, vector& target, unordered_set& blocks) - { - auto dir = vector>({{1,0},{-1,0},{0,1},{0,-1}}); - queue>q; - unordered_setvisited; - - q.push({source[0],source[1]}); - visited.insert(to_string(source[0])+"#"+to_string(source[1])); - - while (!q.empty() && visited.size()<=19900) - { - int x = q.front().first; - int y = q.front().second; - q.pop(); - - for (int k=0; k<4; k++) - { - int i = x+dir[k].first; - int j = y+dir[k].second; - - if (i<0||i>=1e6||j<0||j>=1e6) - continue; - if (i==target[0] && j==target[1]) - return false; - - string encode = to_string(i)+"#"+to_string(j); - if (blocks.find(encode)!=blocks.end()) - continue; - if (visited.find(encode)!=visited.end()) - continue; - - visited.insert(encode); - q.push({i,j}); - } - } - - if (q.empty()) - return true; - else - return false; - } -}; + // no points left in queue, indicating this attempt is enclosed + return Q.empty(); + } +}; \ No newline at end of file diff --git a/tests/BFS/1036.Escape-a-Large-Maze/1036.Escape-a-Large-Maze.t.cpp b/tests/BFS/1036.Escape-a-Large-Maze/1036.Escape-a-Large-Maze.t.cpp new file mode 100644 index 000000000..2b2cf18c4 --- /dev/null +++ b/tests/BFS/1036.Escape-a-Large-Maze/1036.Escape-a-Large-Maze.t.cpp @@ -0,0 +1,66 @@ +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +using namespace std; + +#include + +TEST(escape_a_large_maze_test, I) +{ + std::vector> blocked { + {0,1}, {1,0} + }; + + std::vector source {0, 0}; + std::vector target {0, 2}; + + ASSERT_FALSE(Solution().isEscapePossible(blocked, source, target)); +} + +TEST(escape_a_large_maze_test, II) +{ + std::vector> blocked {}; + + std::vector source {0, 0}; + std::vector target {999999, 999999}; + + ASSERT_TRUE(Solution().isEscapePossible(blocked, source, target)); +} + +TEST(escape_a_large_maze_test, III) +{ + std::vector> blocked { + {1,0}, {1,1}, {1,2}, {1,3}, {1,4}, {1,5}, {1,6}, {1,7}, {1,8}, {1,9}, + {1,10}, {1,11}, {1,12}, {1,13}, {1,14}, {1,15}, {1,16}, {1,17}, {1,18}, + {1,19}, {1,20}, {1,21}, {1,22}, {1,23}, {1,24}, {1,25}, {1,26}, {1,27}, + {1,28}, {1,29}, {1,30}, {1,31}, {1,32}, {1,33}, {1,34}, {1,35}, {1,36}, + {1,37}, {1,38}, {1,39}, {1,40}, {1,41}, {1,42}, {1,43}, {1,44}, {1,45}, + {1,46}, {1,47}, {1,48}, {1,49}, {1,50}, {1,51}, {1,52}, {1,53}, {1,54}, + {1,55}, {1,56}, {1,57}, {1,58}, {1,59}, {1,60}, {1,61}, {1,62}, {1,63}, + {1,64}, {1,65}, {1,66}, {1,67}, {1,68}, {1,69}, {1,70}, {1,71}, {1,72}, + {1,73}, {1,74}, {1,75}, {1,76}, {1,77}, {1,78}, {1,79}, {1,80}, {1,81}, + {1,82}, {1,83}, {1,84}, {1,85}, {1,86}, {1,87}, {1,88}, {1,89}, {1,90}, + {1,91}, {1,92}, {1,93}, {1,94}, {1,95}, {1,96}, {1,97}, {1,98}, {1,99}, + {1,100}, {1,101}, {1,102}, {1,103}, {1,104}, {1,105}, {1,106}, {1,107}, + {1,108}, {1,109}, {1,110}, {1,111}, {1,112}, {1,113}, {1,114}, {1,115}, + {1,116}, {1,117}, {1,118}, {1,119}, {1,120}, {1,121}, {1,122}, {1,123}, + {1,124}, {1,125}, {1,126}, {1,127}, {1,128}, {1,129}, {1,130}, {1,131}, + {1,132}, {1,133}, {1,134}, {1,135}, {1,136}, {1,137}, {1,138}, {1,139}, + {1,140}, {1,141}, {1,142}, {1,143}, {1,144}, {1,145}, {1,146}, {1,147}, + {1,148}, {1,149}, {1,150}, {1,151}, {1,152}, {1,153}, {1,154}, {1,155}, + {1,156}, {1,157}, {1,158}, {1,159}, {1,160}, {1,161}, {1,162}, {1,163}, + {1,164}, {1,165}, {1,166}, {1,167}, {1,168}, {1,169}, {1,170}, {1,171}, + {1,172}, {1,173}, {1,174}, {1,175}, {1,176}, {1,177}, {1,178}, {1,179}, + {1,180}, {1,181}, {1,182}, {1,183}, {1,184}, {1,185}, {1,186}, {1,187}, + {1,188}, {1,189}, {1,190}, {1,191}, {1,192}, {1,193}, {1,194}, {1,195}, + {1,196}, {1,197}, {1,198}, {0,199} + }; + + std::vector source {0, 0}; + std::vector target {999, 999}; + + ASSERT_FALSE(Solution().isEscapePossible(blocked, source, target)); +} \ No newline at end of file diff --git a/tests/BFS/1036.Escape-a-Large-Maze/CMakeLists.txt b/tests/BFS/1036.Escape-a-Large-Maze/CMakeLists.txt new file mode 100644 index 000000000..f2d69d2c9 --- /dev/null +++ b/tests/BFS/1036.Escape-a-Large-Maze/CMakeLists.txt @@ -0,0 +1,9 @@ +set(BINARY escape_a_large_maze_1036_test) + +add_executable(${BINARY} 1036.Escape-a-Large-Maze.t.cpp) + +target_link_libraries(${BINARY} gtest_main) + +include(GoogleTest) + +gtest_discover_tests(${BINARY}) \ No newline at end of file diff --git a/tests/BFS/CMakeLists.txt b/tests/BFS/CMakeLists.txt new file mode 100644 index 000000000..51263ccbb --- /dev/null +++ b/tests/BFS/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(1036.Escape-a-Large-Maze) \ No newline at end of file diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 466d54d9e..2b8c1c028 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -9,4 +9,5 @@ FetchContent_MakeAvailable(googletest) include(GoogleTest) +add_subdirectory(BFS) add_subdirectory(Dynamic_Programming) \ No newline at end of file From ea1374b93b372daf348c343e467317ee7702175e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jan 2022 22:26:26 -0800 Subject: [PATCH 0294/2729] Update 1044.Longest-Duplicate-Substring_v2.cpp --- .../1044.Longest-Duplicate-Substring_v2.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/String/1044.Longest-Duplicate-Substring/1044.Longest-Duplicate-Substring_v2.cpp b/String/1044.Longest-Duplicate-Substring/1044.Longest-Duplicate-Substring_v2.cpp index 581f6beda..071a9216c 100644 --- a/String/1044.Longest-Duplicate-Substring/1044.Longest-Duplicate-Substring_v2.cpp +++ b/String/1044.Longest-Duplicate-Substring/1044.Longest-Duplicate-Substring_v2.cpp @@ -26,15 +26,15 @@ class Solution { ULL hash = 0; ULL pow_base_len = 1; - for (int i=0; i=len) - hash = (hash - pow_base_len*(S[i-len]-'a') ) ; - hash = hash * base + (S[i]-'a'); + + if (i>=len) + hash = (hash - pow_base_len*(S[i-len]-'a') ) ; if (i>=len-1) { From 23add1258aa484b0697c114a467fc5cd4d55de28 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jan 2022 23:41:54 -0800 Subject: [PATCH 0295/2729] Update Readme.md --- String/418.Sentence-Screen-Fitting/Readme.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/String/418.Sentence-Screen-Fitting/Readme.md b/String/418.Sentence-Screen-Fitting/Readme.md index 5f82f6717..0141824a5 100644 --- a/String/418.Sentence-Screen-Fitting/Readme.md +++ b/String/418.Sentence-Screen-Fitting/Readme.md @@ -1,6 +1,6 @@ ### 418.Sentence-Screen-Fitting -此题如果按照逐个单词去分析处理,结果会超时.更合理的方式是按照逐个cols的长度去处理.这里将sentence的所有单词用空格串联起来: +此题如果按照逐个单词去填充,那么如果单词长度都特别短的话,想要填充完rows x cols这么多位置就会TLE.本题更合理的方式是以cols的长度去处理。首先将sentence的所有单词用空格串联起来记做str: ```cpp for (auto str:sentence) { @@ -10,9 +10,12 @@ ``` 注意,这里可以提前处理不合法的例子. -初始的字符idex是0,每处理一行,我们就把index+=cols,此时如果index落到了空格上,一切OK,说明至此的所有字符都可以放在一个row里面.如果没有落到空格上,说明某个单词没有写完就触碰了边界,这时候我们将index慢慢回退直至遇到了一个空格为止. +我们接下来的任务就是在一段```xxx xxx xx xxxx xx x xxxx ```里面试图以没cols的宽度去插板,要求板子只能插在空格里,不能分割任何单词本身。特别注意,最后我们特地留有一个空格,这是为了将前一个str与下一个str之间区分开来。 -重复以上过程,当处理完rows行之后,看看此刻的index是length的多少倍,就说明能重复多少个字符串. +具体的做法是,初始的指针index指向0,每处理一行,我们就把index+=cols,此时如果index落到了空格上,说明至此的所有字符都可以放在一个row里面,然后index指向空格后的第一个字符。如果没有落到空格上,说明某个单词没有写完就触碰了边界,这时候我们将index慢慢回退直至遇到了一个空格为止。 +注意到指针wrap的情况,所以我们对于index的处理永远都是考虑它对str长度的取余。 + +重复以上过程,当处理完rows行之后,看看此刻的index是str长度的多少倍,就说明能重复多少个字符串. [Leetcode Link](https://leetcode.com/problems/sentence-screen-fitting) From e0faef5416c939bd7d00926def10fdc74fd1dd62 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jan 2022 23:43:31 -0800 Subject: [PATCH 0296/2729] Update Readme.md --- String/418.Sentence-Screen-Fitting/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/418.Sentence-Screen-Fitting/Readme.md b/String/418.Sentence-Screen-Fitting/Readme.md index 0141824a5..2313c22af 100644 --- a/String/418.Sentence-Screen-Fitting/Readme.md +++ b/String/418.Sentence-Screen-Fitting/Readme.md @@ -10,7 +10,7 @@ ``` 注意,这里可以提前处理不合法的例子. -我们接下来的任务就是在一段```xxx xxx xx xxxx xx x xxxx ```里面试图以没cols的宽度去插板,要求板子只能插在空格里,不能分割任何单词本身。特别注意,最后我们特地留有一个空格,这是为了将前一个str与下一个str之间区分开来。 +我们接下来的任务就是在一段```xxx xxx xx xxxx xx x xxxx ```里面试图以每cols的宽度去插板,要求板子只能插在空格里,不能分割任何单词本身。特别注意,最后我们特地留有一个空格,这是为了将前一个str与下一个str之间区分开来。 具体的做法是,初始的指针index指向0,每处理一行,我们就把index+=cols,此时如果index落到了空格上,说明至此的所有字符都可以放在一个row里面,然后index指向空格后的第一个字符。如果没有落到空格上,说明某个单词没有写完就触碰了边界,这时候我们将index慢慢回退直至遇到了一个空格为止。 From f036bab46e0cdb1964df22ffc75a657cf947d111 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jan 2022 00:43:55 -0800 Subject: [PATCH 0297/2729] Create 2115.Find-All-Possible-Recipes-from-Given-Supplies.cpp --- ...l-Possible-Recipes-from-Given-Supplies.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies/2115.Find-All-Possible-Recipes-from-Given-Supplies.cpp diff --git a/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies/2115.Find-All-Possible-Recipes-from-Given-Supplies.cpp b/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies/2115.Find-All-Possible-Recipes-from-Given-Supplies.cpp new file mode 100644 index 000000000..b1431d555 --- /dev/null +++ b/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies/2115.Find-All-Possible-Recipes-from-Given-Supplies.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector findAllRecipes(vector& recipes, vector>& ingredients, vector& supplies) + { + queueq; + for (auto x: supplies) + q.push(x); + + unordered_mapindegree; + unordered_map>next; + unordered_setwanted(recipes.begin(), recipes.end()); + + for (int i=0; irets; + while (!q.empty()) + { + string cur = q.front(); + q.pop(); + if (wanted.find(cur)!=wanted.end()) + rets.push_back(cur); + for (auto x: next[cur]) + { + indegree[x]-=1; + if (indegree[x]==0) + q.push(x); + } + } + + return rets; + } +}; From 36f853e9bb3d9c20aa61ff5caf2556fcb1d07980 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jan 2022 00:44:26 -0800 Subject: [PATCH 0298/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 74d66278e..1414a79d4 100644 --- a/Readme.md +++ b/Readme.md @@ -484,6 +484,7 @@ [1591.Strange-Printer-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1591.Strange-Printer-II) (H-) [1857.Largest-Color-Value-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1857.Largest-Color-Value-in-a-Directed-Graph) (H-) [2050.Parallel-Courses-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2050.Parallel-Courses-III) (M+) +[2115.Find-All-Possible-Recipes-from-Given-Supplies](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies) (M) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From 9eca46e24bcb223ac12f1a84d52ffb7a5af71954 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jan 2022 00:49:34 -0800 Subject: [PATCH 0299/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies/Readme.md diff --git a/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies/Readme.md b/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies/Readme.md new file mode 100644 index 000000000..ea2e03382 --- /dev/null +++ b/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies/Readme.md @@ -0,0 +1,5 @@ +### 2115.Find-All-Possible-Recipes-from-Given-Supplies + +此题非常类似那些“先修课程”的题目:必须已经访问过若干个节点(ingredient)之后才能访问一个新节点(recipe)。所以用拓扑排序是非常自然的想法。 + +具体做法:BFS队列的初始节点就是那些supplies。每次从队列里弹出一个物品,查看它可能“解锁”哪些新物品,确认这个新物品的所有条件都已经满足(入度为零)之后就把其加入队列。 From 9de0d06b8e600423550aae5af71d3eb2192a563b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Jan 2022 23:05:14 -0800 Subject: [PATCH 0300/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1414a79d4..e1f4e3f0e 100644 --- a/Readme.md +++ b/Readme.md @@ -718,6 +718,7 @@ [1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks) (M+) * ``二分图`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) +[1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) [1947.Maximum-Compatibility-Score-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1947.Maximum-Compatibility-Score-Sum) (H) * ``Catalan`` From 4a8321be730d8875ef013529d08fadb36333d909 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Jan 2022 23:06:23 -0800 Subject: [PATCH 0301/2729] Update Readme.md --- Readme.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e1f4e3f0e..887a3bd1a 100644 --- a/Readme.md +++ b/Readme.md @@ -716,9 +716,8 @@ [1494.Parallel-Courses-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1494.Parallel-Courses-II) (H) [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) [1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks) (M+) - * ``二分图`` + * ``带权二分图`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) -[1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) [1947.Maximum-Compatibility-Score-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1947.Maximum-Compatibility-Score-Sum) (H) * ``Catalan`` From b67db82b12547e1e7805e7888f6fed3d127bcab9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jan 2022 00:31:09 -0800 Subject: [PATCH 0302/2729] Create 2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp --- ...k-if-a-Parentheses-String-Can-Be-Valid.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp diff --git a/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp new file mode 100644 index 000000000..01d17e85c --- /dev/null +++ b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp @@ -0,0 +1,63 @@ +class Solution { +public: + bool canBeValid(string s, string locked) + { + int n = s.size(); + if (n%2!=0) return false; + + if (!checkRight(s, locked)) return false; + if (!checkLeft(s, locked)) return false; + return true; + + } + + bool checkRight(string s, string locked) + { + int unmatched = 0; + int count = 0; + + for (int i = 0; i=0; i--) + { + if (s[i]==')') + unmatched++; + else + unmatched--; + + if (locked[i]=='0' && s[i]=='(') + count++; + + if (unmatched < 0) + { + if (count==0) return false; + unmatched += 2; + count--; + } + } + return true; + } +}; From 2fa47e1ac16d8f9f3eaba18f3089ec225b270512 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jan 2022 00:31:39 -0800 Subject: [PATCH 0303/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 887a3bd1a..699a64ebb 100644 --- a/Readme.md +++ b/Readme.md @@ -1082,6 +1082,7 @@ [1541.Minimum-Insertions-to-Balance-a-Parentheses-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1541.Minimum-Insertions-to-Balance-a-Parentheses-String) (M+) [678.Valid-Parenthesis-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/678.Valid-Parenthesis-String) (H-) [1963.minimum-number-of-swaps-to-make-the-string-balanced](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1963.minimum-number-of-swaps-to-make-the-string-balanced) (M+) +[2116.Check-if-a-Parentheses-String-Can-Be-Valid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid) (H-) * ``Intervals`` [435.Non-overlapping-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/435.Non-overlapping-Intervals) (M+) (aka. [646.Maximum-Length-of-Pair-Chain](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/646.Maximum-Length-of-Pair-Chain)) [452.Minimum-Number-of-Arrows-to-Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons) (H-) From aae931dbfe766a5ffbc1ab4f5ec81cf292291185 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jan 2022 15:02:19 -0800 Subject: [PATCH 0304/2729] Rename 2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp to 2116.Check-if-a-Parentheses-String-Can-Be-Valid_v1.cpp --- ...cpp => 2116.Check-if-a-Parentheses-String-Can-Be-Valid_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/{2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp => 2116.Check-if-a-Parentheses-String-Can-Be-Valid_v1.cpp} (100%) diff --git a/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v1.cpp similarity index 100% rename from Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid.cpp rename to Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v1.cpp From 15973d6b9dc04f57867d81215381c2609b5db1f7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jan 2022 16:27:44 -0800 Subject: [PATCH 0305/2729] Create 2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp --- ...f-a-Parentheses-String-Can-Be-Valid_v2.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp diff --git a/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp new file mode 100644 index 000000000..f540f0fc3 --- /dev/null +++ b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + bool canBeValid(string s, string locked) + { + if (s.size() % 2 != 0) return false; + int upper = 0, lower = 0; + for (int i=0; i Date: Sat, 8 Jan 2022 16:27:47 -0800 Subject: [PATCH 0306/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/Readme.md diff --git a/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/Readme.md b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/Readme.md new file mode 100644 index 000000000..ea6d152af --- /dev/null +++ b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/Readme.md @@ -0,0 +1,9 @@ +### 2116.Check-if-a-Parentheses-String-Can-Be-Valid + +#### 解法1:Two Pass +我们用count来表示未被匹配的左括号的数目。然后我们从左往右遍历每一个字符。显然,遇到左括号的时候count加一,遇到右括号的时候count减一。如果某一时刻发现count小于0了,说明有一个右括号注定在它之前找不到左括号与之匹配,那么为了“挽救”,我们只有唯一的对策:在之前某一个允许改动的地方将右括号改为左括号。这样的后果是count+=2。可见我们在遍历的过程中需要另外一个计数器,就是记录有多少个unlocked的右括号(以便于做所述的改动)。如果我们从左往右遍历完,count始终为正,那么说明所有的右括号(扣除那些必须改为左括号的右括号)都一定有与之配对的左括号。 + +同理,从左往右遍历,查看是否所有的左括号(扣除那些必须改为右括号的左括号)都一定有与之配对的右括号。如果Two Pass的check都通过的话,那么就可以返回true。 + +那么满足以上两个条件是否就是返回true的充要条件呢?事实上确实如此,你找不出反例。 + From 0e91c895172f93cf3b4b84a40674ec32e978083f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jan 2022 16:28:06 -0800 Subject: [PATCH 0307/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 699a64ebb..9ff900272 100644 --- a/Readme.md +++ b/Readme.md @@ -1080,8 +1080,8 @@ [921.Minimum-Add-to-Make-Parentheses-Valid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/921.Minimum-Add-to-Make-Parentheses-Valid) (M+) [1249.Minimum-Remove-to-Make-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1249.Minimum-Remove-to-Make-Valid-Parentheses) (M+) [1541.Minimum-Insertions-to-Balance-a-Parentheses-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1541.Minimum-Insertions-to-Balance-a-Parentheses-String) (M+) -[678.Valid-Parenthesis-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/678.Valid-Parenthesis-String) (H-) [1963.minimum-number-of-swaps-to-make-the-string-balanced](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1963.minimum-number-of-swaps-to-make-the-string-balanced) (M+) +[678.Valid-Parenthesis-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/678.Valid-Parenthesis-String) (H-) [2116.Check-if-a-Parentheses-String-Can-Be-Valid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid) (H-) * ``Intervals`` [435.Non-overlapping-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/435.Non-overlapping-Intervals) (M+) (aka. [646.Maximum-Length-of-Pair-Chain](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/646.Maximum-Length-of-Pair-Chain)) From 90327b2d67c3c66131ebff952a61e75743715027 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jan 2022 16:42:54 -0800 Subject: [PATCH 0308/2729] Update 2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp --- .../2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp index f540f0fc3..45ee9425d 100644 --- a/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp +++ b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/2116.Check-if-a-Parentheses-String-Can-Be-Valid_v2.cpp @@ -28,7 +28,6 @@ class Solution { if (lower < 0) lower += 2; - if (upper < lower) return false; if (upper < 0) return false; } From 292f91b98f4bd51046fbc8feb3dfbf82ac99da83 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jan 2022 16:43:55 -0800 Subject: [PATCH 0309/2729] Update Readme.md --- .../Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/Readme.md b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/Readme.md index ea6d152af..49f0f285f 100644 --- a/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/Readme.md +++ b/Greedy/2116.Check-if-a-Parentheses-String-Can-Be-Valid/Readme.md @@ -7,3 +7,11 @@ 那么满足以上两个条件是否就是返回true的充要条件呢?事实上确实如此,你找不出反例。 +#### 解法2:One Pass +本题其实就是LC 678的follow up。我们把那些unlocked的字符看成是星号,但是只允许替换成左括号或者右括号(不能设置为空)。 + +我们设置upper表示最多可能有多少个未被匹配的左括号,lower表示最少可能有多少个未被匹配的左括号。upper和lower的区别就在于对于那些待定字符如何处理:如果我们无脑设为'('的话,upper就会增1,如果无脑设为')'的话,那么lower就会减1. 另外,如果遇到那些locked的字符,那么upper和lower的增减就是一致的。 + +变化出现在如果发现lower<0的时候,那说明我们设置')'的策略过于激进,不能无脑地将所有待定字符设置为右括号。所以我们必须“让出”一个被变为右括号的星号,转而让其变为左括号。注意,这样一正一反的修正,lower就会增2. + +判定的条件是:在遍历的过程中,如果任何时候发现upper<0,那么说明即使激进的设置左括号也不够用(与右括号匹配),就可以返回false。此外,最终为了表示平衡,lower必须为0. 如果lower大于0,说明“激进地加右括号”的策略也无法匹配所有的左括号,自然也是无解。 From d485a8cc04d9200e46714cc340139da3523090cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jan 2022 23:34:24 -0800 Subject: [PATCH 0310/2729] Create 2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another_v2.cpp --- ...-From-a-Binary-Tree-Node-to-Another_v2.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another_v2.cpp diff --git a/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another_v2.cpp b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another_v2.cpp new file mode 100644 index 000000000..460fcdb8d --- /dev/null +++ b/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another_v2.cpp @@ -0,0 +1,56 @@ +/** + * 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: + string getDirections(TreeNode* root, int startValue, int destValue) + { + vectornums1, nums2; + string dirs1, dirs2; + dfs(root, nums1, dirs1, startValue); + dfs(root, nums2, dirs2, destValue); + + // nums1: 0-1-3; nums2: 0-2-6 + // dirs1: L-U-U; dirs2: R-R-L + int k = 0; + while (k&nums, string& dirs, int target) + { + if (node==NULL) return false; + if (node->val == target) return true; + + if (node->left) + { + nums.push_back(node->left->val); + dirs.push_back('L'); + if (dfs(node->left, nums, dirs, target)) + return true; + nums.pop_back(); + dirs.pop_back(); + } + if (node->right) + { + nums.push_back(node->right->val); + dirs.push_back('R'); + if (dfs(node->right, nums, dirs, target)) + return true; + nums.pop_back(); + dirs.pop_back(); + } + return false; + } +}; From 569f8b953330354558b64dde9a0eb80285601927 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Jan 2022 16:18:44 -0800 Subject: [PATCH 0311/2729] Create 2136.Earliest-Possible-Day-of-Full-Bloom_v1.cpp --- ...Earliest-Possible-Day-of-Full-Bloom_v1.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/2136.Earliest-Possible-Day-of-Full-Bloom_v1.cpp diff --git a/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/2136.Earliest-Possible-Day-of-Full-Bloom_v1.cpp b/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/2136.Earliest-Possible-Day-of-Full-Bloom_v1.cpp new file mode 100644 index 000000000..16f3bb8ba --- /dev/null +++ b/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/2136.Earliest-Possible-Day-of-Full-Bloom_v1.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int earliestFullBloom(vector& plantTime, vector& growTime) + { + int n = plantTime.size(); + vector>time(n); + for (int i=0; i&a, vector&b){return a[1]>&time) + { + int n = time.size(); + int days = 0; + + for (int i=0; i T+time[i][1]) + { + return false; + } + } + return true; + } +}; From 5cfbd2f921f95b115a2feba0e418af9f3be4be1f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Jan 2022 16:23:08 -0800 Subject: [PATCH 0312/2729] Create 2136.Earliest-Possible-Day-of-Full-Bloom_v2.cpp --- ...Earliest-Possible-Day-of-Full-Bloom_v2.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/2136.Earliest-Possible-Day-of-Full-Bloom_v2.cpp diff --git a/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/2136.Earliest-Possible-Day-of-Full-Bloom_v2.cpp b/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/2136.Earliest-Possible-Day-of-Full-Bloom_v2.cpp new file mode 100644 index 000000000..2ef9c19e3 --- /dev/null +++ b/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/2136.Earliest-Possible-Day-of-Full-Bloom_v2.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int earliestFullBloom(vector& plantTime, vector& growTime) + { + int n = plantTime.size(); + vector>time(n); + for (int i=0; i&a, vector&b){return a[1]>b[1];}); + + int ret = 0; + int days = 0; + for (int i=0; i Date: Sun, 9 Jan 2022 16:25:56 -0800 Subject: [PATCH 0313/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9ff900272..8b8cad4ba 100644 --- a/Readme.md +++ b/Readme.md @@ -1027,6 +1027,7 @@ [1911.Maximum-Alternating-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1911.Maximum-Alternating-Subsequence-Sum) (M+) [1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) [2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses) (M+) +[2136.Earliest-Possible-Day-of-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From eedc11d8979cfcbe53d0af3fcb2a823e6456a11d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Jan 2022 17:07:21 -0800 Subject: [PATCH 0314/2729] Create Readme.md --- Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/Readme.md diff --git a/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/Readme.md b/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/Readme.md new file mode 100644 index 000000000..bbb0bed32 --- /dev/null +++ b/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom/Readme.md @@ -0,0 +1,5 @@ +### 2136.Earliest-Possible-Day-of-Full-Bloom + +假设最后的统一开花日是T,那么growTime越长的花所留给我们的种植时间越短,我们必须优先把此花搞定。所以按照种植完成的deadline从早到晚排序,这就是我们的最优策略。 + +有了种植的顺序,我们依次遍历每个花,就有了各自的种植完成时刻。然后比较每朵花“种植完成时刻+growTime”,最大值就是最终的统一开花日期。 From 11d9084331087cd14b96ef0a3d0927bea2cb800c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Jan 2022 22:48:02 -0800 Subject: [PATCH 0315/2729] Update Readme.md --- Others/850.Rectangle-Area-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/850.Rectangle-Area-II/Readme.md b/Others/850.Rectangle-Area-II/Readme.md index 36d9b5b15..554a6fa9d 100644 --- a/Others/850.Rectangle-Area-II/Readme.md +++ b/Others/850.Rectangle-Area-II/Readme.md @@ -14,7 +14,7 @@ 对于一个矩阵,如果遍历所有内部的格子做标记,显然是效率很低的。我们很容易想到,是否能有类似一维扫描线算法(只记录两端的差分值)。这就是二维差分数组的应用。这里我们需要记录四个差分值: ```cpp diff[x0][y0]+=1; -diff[x0+1][y1]-=1; +diff[x0][y1+1]-=1; diff[x1+1][y0]-=1; diff[x1+1][y1+1]+=1; ``` From fb65a9cfa1da2650586d8c1d51d59ef8f2f2aa4f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Jan 2022 23:55:44 -0800 Subject: [PATCH 0316/2729] Create 2132.Stamping-the-Grid_v1.cpp --- .../2132.Stamping-the-Grid_v1.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp diff --git a/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp new file mode 100644 index 000000000..9f9a3d355 --- /dev/null +++ b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + vector>getPresum(vector>& A) + { + int m = A.size(); + int n = A[0].size(); + vector>presum(m, vector(n)); + for (int i=0; i>& presum, int i, int j, int x, int y) + { + int a = j==0?0:presum[x][j-1]; + int b = i==0?0:presum[i-1][y]; + int c = (i==0||j==0)?0:presum[i-1][j-1]; + int area = presum[x][y] - a - b + c; + return area; + } + + bool possibleToStamp(vector>& grid, int stampHeight, int stampWidth) + { + int m = grid.size(), n = grid[0].size(); + auto gridPresum = getPresum(grid); + + vector>stamp(m, vector(n)); + for (int i=stampHeight-1; i Date: Mon, 10 Jan 2022 00:20:55 -0800 Subject: [PATCH 0317/2729] Create Readme.md --- Others/2132.Stamping-the-Grid/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 Others/2132.Stamping-the-Grid/Readme.md diff --git a/Others/2132.Stamping-the-Grid/Readme.md b/Others/2132.Stamping-the-Grid/Readme.md new file mode 100644 index 000000000..872fb761b --- /dev/null +++ b/Others/2132.Stamping-the-Grid/Readme.md @@ -0,0 +1,6 @@ +### 2132.Stamping-the-Grid + +#### 解法1:二维区间和 +遍历grid的每一个位置(i,j),考察以(i,j)为左上角、(x,y)为右下角、形状等同于邮票的区间,如何快算判断这个区域是否可以合法放置邮票呢?显然用一个预处理的二维区间和查询即可。这样我们就可以求出所有可以合法放置邮票的区域,将右下角的位置都标记为1,存储在二维数组stamps里面。 + +然后我们再遍历grid里面的每一个非1的点位(i,j),考察它是否可能被某一个stamp覆盖。怎么做到呢?只要考察以(i,j)为左上角、(x,y)为右下角、形状等同于邮票的区间,看看stamps数组在这个区间里的元素和是否大于0. 是的话那么必然有一个合法的stamp能够覆盖(i,j),否则的话就可以返回false。 From 6dbddb2e1bb8f4feb9c3c582c67e8e8c1b56e020 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 10 Jan 2022 00:28:25 -0800 Subject: [PATCH 0318/2729] Update 2132.Stamping-the-Grid_v1.cpp --- .../2132.Stamping-the-Grid_v1.cpp | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp index 9f9a3d355..ab1938249 100644 --- a/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp +++ b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp @@ -1,6 +1,7 @@ -class Solution { +class RegionSum { + vector>presum; public: - vector>getPresum(vector>& A) + RegionSum(vector>& A) { int m = A.size(); int n = A[0].size(); @@ -13,10 +14,9 @@ class Solution { int c = (i==0||j==0)?0:presum[i-1][j-1]; presum[i][j] = a + b - c + A[i][j]; } - return presum; + this->presum = presum; } - - int queryPresum(vector>& presum, int i, int j, int x, int y) + int query(int i, int j, int x, int y) { int a = j==0?0:presum[x][j-1]; int b = i==0?0:presum[i-1][y]; @@ -24,32 +24,34 @@ class Solution { int area = presum[x][y] - a - b + c; return area; } +}; +class Solution { +public: bool possibleToStamp(vector>& grid, int stampHeight, int stampWidth) { int m = grid.size(), n = grid[0].size(); - auto gridPresum = getPresum(grid); + vector>stamps(m, vector(n)); - vector>stamp(m, vector(n)); - for (int i=stampHeight-1; i Date: Mon, 10 Jan 2022 01:08:34 -0800 Subject: [PATCH 0319/2729] Create 2132.Stamping-the-Grid_v2.cpp --- .../2132.Stamping-the-Grid_v2.cpp | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp diff --git a/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp new file mode 100644 index 000000000..fdbfa332c --- /dev/null +++ b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp @@ -0,0 +1,76 @@ +class Diff2d { +public: + vector>f; + vector>diff; + int m,n; + Diff2d(vector>& A) + { + m = A.size(); + n = A[0].size(); + diff.resize(m+1); + f.resize(m+1); + for (int i=0; i>& grid, int stampHeight, int stampWidth) + { + int m = grid.size(), n = grid[0].size(); + + Diff2d Grid(grid); + for (int i=0; i=0; x--) + for (int y=n-1; y-stampWidth+1>=0; y--) + { + if (Grid.f[x][y]>0) continue; + int i = x-stampHeight+1; + int j = y-stampWidth+1; + Stamps.set(i,j,x,y); + } + Stamps.compute(); + + for (int i=0; i Date: Mon, 10 Jan 2022 01:09:45 -0800 Subject: [PATCH 0320/2729] Update Readme.md --- Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8b8cad4ba..3ae73f1a0 100644 --- a/Readme.md +++ b/Readme.md @@ -1158,9 +1158,11 @@ [1674.Minimum-Moves-to-Make-Array-Complementary](https://github.com/wisdompeak/LeetCode/tree/master/Others/1674.Minimum-Moves-to-Make-Array-Complementary) (H) [1871.Jump-Game-VII](https://github.com/wisdompeak/LeetCode/tree/master/Others/1871.Jump-Game-VII) (M+) 1893.Check if All the Integers in a Range Are Covered (E) -[850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [1943.Describe-the-Painting](https://github.com/wisdompeak/LeetCode/tree/master/Others/1943.Describe-the-Painting) (H-) [2015.Average-Height-of-Buildings-in-Each-Segment](https://github.com/wisdompeak/LeetCode/tree/master/Others/2015.Average-Height-of-Buildings-in-Each-Segment) (H-) +* ``二维差分`` +[850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) +[2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) * ``Enumeration`` [479.Largest-Palindrome-Product](https://github.com/wisdompeak/LeetCode/tree/master/Others/479.Largest-Palindrome-Product) (M+) [866.Prime-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Others/866.Prime-Palindrome) (H-) @@ -1174,6 +1176,8 @@ * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) +* ``2D Presum`` +[2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) * ``Quick Select`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [347.Top-K-Frequent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/347.Top-K-Frequent-Elements) (M+) From d52ea06404ddb820c2514e677c71795839b212cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 10 Jan 2022 01:12:56 -0800 Subject: [PATCH 0321/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 3ae73f1a0..59ca73330 100644 --- a/Readme.md +++ b/Readme.md @@ -1177,6 +1177,8 @@ [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) * ``2D Presum`` +1314.Matrix-Block-Sum (M) +[1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold) (H-) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) * ``Quick Select`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) From a07adfcbb05bb6c11c794f485ead4cc5f235b1fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Jan 2022 03:45:07 -0800 Subject: [PATCH 0322/2729] Create .cpp --- Template/Diff_Array_2D/.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Template/Diff_Array_2D/.cpp diff --git a/Template/Diff_Array_2D/.cpp b/Template/Diff_Array_2D/.cpp new file mode 100644 index 000000000..3dcaebfaa --- /dev/null +++ b/Template/Diff_Array_2D/.cpp @@ -0,0 +1,37 @@ +class Diff2d { +public: + vector>f; + vector>diff; + int m,n; + Diff2d(vector>& A) + { + m = A.size(); + n = A[0].size(); + diff.resize(m+1); + f.resize(m+1); + for (int i=0; i Date: Tue, 11 Jan 2022 03:45:20 -0800 Subject: [PATCH 0323/2729] Create Readme.md --- Template/Diff_Array_2D/Readme.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Template/Diff_Array_2D/Readme.md diff --git a/Template/Diff_Array_2D/Readme.md b/Template/Diff_Array_2D/Readme.md new file mode 100644 index 000000000..232d6f75a --- /dev/null +++ b/Template/Diff_Array_2D/Readme.md @@ -0,0 +1,16 @@ +我们来复习一下二维差分的模板。假设二维矩阵为f[i][j]。我们构造与之对应的差分数组diff[i][j]. 如果我们想将以(x0,y0)为左上角、(x1,y1)为右下角的矩形区域统一加上val,那么我们只需要在diff数组上做标记: +``` +diff[x0][y0]+=1; +diff[x0][y1+1]-=1; +diff[x1+1][y0]-=1; +diff[x1+1][y1+1]+=1; +``` +这样的操作可以进行多次。如果我们想重构更新后的f的值,需要做如下操作: +``` +for (int i=0; i Date: Tue, 11 Jan 2022 03:45:41 -0800 Subject: [PATCH 0324/2729] Rename .cpp to code.cpp --- Template/Diff_Array_2D/{.cpp => code.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Template/Diff_Array_2D/{.cpp => code.cpp} (100%) diff --git a/Template/Diff_Array_2D/.cpp b/Template/Diff_Array_2D/code.cpp similarity index 100% rename from Template/Diff_Array_2D/.cpp rename to Template/Diff_Array_2D/code.cpp From ce102929117b9ca485233049890a072160494022 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Jan 2022 03:47:55 -0800 Subject: [PATCH 0325/2729] Create code.cpp --- Template/Sub_Rect_Sum_2D/code.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Template/Sub_Rect_Sum_2D/code.cpp diff --git a/Template/Sub_Rect_Sum_2D/code.cpp b/Template/Sub_Rect_Sum_2D/code.cpp new file mode 100644 index 000000000..063566bbc --- /dev/null +++ b/Template/Sub_Rect_Sum_2D/code.cpp @@ -0,0 +1,28 @@ +class RegionSum { + vector>presum; +public: + RegionSum(vector>& A) + { + int m = A.size(); + int n = A[0].size(); + presum.resize(m); + for (int i=0; i Date: Tue, 11 Jan 2022 03:49:15 -0800 Subject: [PATCH 0326/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 59ca73330..bf84f9b28 100644 --- a/Readme.md +++ b/Readme.md @@ -1204,4 +1204,6 @@ [Bit_Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Template/Bit_manipulation) [Combination-Number](https://github.com/wisdompeak/LeetCode/tree/master/Template/Combination-Number) [RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) +[二维子矩阵求和](https://github.com/wisdompeak/LeetCode/tree/master/Template/Sub_Rect_Sum_2D) +[二维差分数组](https://github.com/wisdompeak/LeetCode/tree/master/Template/Diff_Array_2D) [CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) From 9ea5091200775c16c921ab23185a804848dc19e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Jan 2022 03:51:55 -0800 Subject: [PATCH 0327/2729] Update Readme.md --- Template/Diff_Array_2D/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Template/Diff_Array_2D/Readme.md b/Template/Diff_Array_2D/Readme.md index 232d6f75a..6adfd2086 100644 --- a/Template/Diff_Array_2D/Readme.md +++ b/Template/Diff_Array_2D/Readme.md @@ -14,3 +14,9 @@ for (int i=0; i>& A) 根据所给的矩阵维度初始化(A本身的值没有用处) +2. void set(int x0, int y0, int x1, int y1, int val) 将以(x0,y0)为左上角、(x1,y1)为右下角的矩形区域统一加上val +3. void compute() 输出重构的二维数组前必须做这步操作 +4. f[i][j] 直接输出重构的二维数组的任意值 From f36ab068f94a45ccedb662280b47937c3df28ca0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Jan 2022 03:56:21 -0800 Subject: [PATCH 0328/2729] Update Readme.md --- Others/2132.Stamping-the-Grid/Readme.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Others/2132.Stamping-the-Grid/Readme.md b/Others/2132.Stamping-the-Grid/Readme.md index 872fb761b..efbbeb62b 100644 --- a/Others/2132.Stamping-the-Grid/Readme.md +++ b/Others/2132.Stamping-the-Grid/Readme.md @@ -4,3 +4,27 @@ 遍历grid的每一个位置(i,j),考察以(i,j)为左上角、(x,y)为右下角、形状等同于邮票的区间,如何快算判断这个区域是否可以合法放置邮票呢?显然用一个预处理的二维区间和查询即可。这样我们就可以求出所有可以合法放置邮票的区域,将右下角的位置都标记为1,存储在二维数组stamps里面。 然后我们再遍历grid里面的每一个非1的点位(i,j),考察它是否可能被某一个stamp覆盖。怎么做到呢?只要考察以(i,j)为左上角、(x,y)为右下角、形状等同于邮票的区间,看看stamps数组在这个区间里的元素和是否大于0. 是的话那么必然有一个合法的stamp能够覆盖(i,j),否则的话就可以返回false。 + +#### 解法2:二维差分数组 +我们来复习一下二维差分的模板。假设二维矩阵为f[i][j]。我们构造与之对应的差分数组diff[i][j]. 如果我们想将以(x0,y0)为左上角、(x1,y1)为右下角的矩形区域统一加上val,那么我们只需要在diff数组上做标记: +``` +diff[x0][y0]+=1; +diff[x0][y1+1]-=1; +diff[x1+1][y0]-=1; +diff[x1+1][y1+1]+=1; +``` +这样的操作可以进行多次。如果我们想重构更新后的f的值,需要做如下操作: +``` +for (int i=0; i Date: Tue, 11 Jan 2022 03:59:30 -0800 Subject: [PATCH 0329/2729] Update 2132.Stamping-the-Grid_v1.cpp --- Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp index ab1938249..6c7b3a17a 100644 --- a/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp +++ b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v1.cpp @@ -5,7 +5,9 @@ class RegionSum { { int m = A.size(); int n = A[0].size(); - vector>presum(m, vector(n)); + presum.resize(m); + for (int i=0; ipresum = presum; } int query(int i, int j, int x, int y) { From 92b9ef45be8a285f836185b04ab76dda9aecb4e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Jan 2022 15:18:48 -0800 Subject: [PATCH 0330/2729] Update 2132.Stamping-the-Grid_v2.cpp --- Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp index fdbfa332c..290709971 100644 --- a/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp +++ b/Others/2132.Stamping-the-Grid/2132.Stamping-the-Grid_v2.cpp @@ -60,7 +60,7 @@ class Solution { if (Grid.f[x][y]>0) continue; int i = x-stampHeight+1; int j = y-stampWidth+1; - Stamps.set(i,j,x,y); + Stamps.set(i,j,x,y,1); } Stamps.compute(); From 64b49902978e2414df0f1b1047c3d14f4671d736 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Jan 2022 15:19:34 -0800 Subject: [PATCH 0331/2729] Update code.cpp --- Template/Diff_Array_2D/code.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Template/Diff_Array_2D/code.cpp b/Template/Diff_Array_2D/code.cpp index 3dcaebfaa..c03dd2374 100644 --- a/Template/Diff_Array_2D/code.cpp +++ b/Template/Diff_Array_2D/code.cpp @@ -3,10 +3,10 @@ class Diff2d { vector>f; vector>diff; int m,n; - Diff2d(vector>& A) + Diff2d(vectorm = m; + this->n = n; diff.resize(m+1); f.resize(m+1); for (int i=0; i Date: Tue, 11 Jan 2022 15:26:16 -0800 Subject: [PATCH 0332/2729] Update code.cpp --- Template/Diff_Array_2D/code.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/Diff_Array_2D/code.cpp b/Template/Diff_Array_2D/code.cpp index c03dd2374..24db0b7c8 100644 --- a/Template/Diff_Array_2D/code.cpp +++ b/Template/Diff_Array_2D/code.cpp @@ -3,7 +3,7 @@ class Diff2d { vector>f; vector>diff; int m,n; - Diff2d(vectorm = m; this->n = n; From 6b197dba05094c7966d5a92e7c87955c91b10316 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Jan 2022 15:29:04 -0800 Subject: [PATCH 0333/2729] Update 850.Rectangle-Area-II_v2.cpp --- .../850.Rectangle-Area-II_v2.cpp | 80 +++++++++++++------ 1 file changed, 56 insertions(+), 24 deletions(-) diff --git a/Others/850.Rectangle-Area-II/850.Rectangle-Area-II_v2.cpp b/Others/850.Rectangle-Area-II/850.Rectangle-Area-II_v2.cpp index 8f99682c8..52f43352c 100644 --- a/Others/850.Rectangle-Area-II/850.Rectangle-Area-II_v2.cpp +++ b/Others/850.Rectangle-Area-II/850.Rectangle-Area-II_v2.cpp @@ -1,5 +1,44 @@ -typedef long long ll; +using ll = long long; +class Diff2d { +public: + vector>f; + vector>diff; + int m,n; + Diff2d(int m, int n) + { + this->m = m; + this->n = n; + diff.resize(m+1); + f.resize(m+1); + for (int i=0; i>& rectangles) { @@ -24,37 +63,30 @@ class Solution { Y2idx[col[i]] = i; int m = row.size(), n = col.size(); - vector>sum(m, vector(n)); - vector>diff(m, vector(n)); - + Diff2d grid(m,n); + for (auto rect: rectangles) { - ll x0 = rect[0]; - ll y0 = rect[1]; - ll x1 = rect[2]; - ll y1 = rect[3]; - diff[X2idx[x0]][Y2idx[y0]]+=1; - diff[X2idx[x0]][Y2idx[y1]]-=1; - diff[X2idx[x1]][Y2idx[y0]]-=1; - diff[X2idx[x1]][Y2idx[y1]]+=1; + int i = X2idx[rect[0]]; + int j = Y2idx[rect[1]]; + int x = X2idx[rect[2]]-1; + int y = Y2idx[rect[3]]-1; + grid.set(i,j,x,y,1); } - - + grid.compute(); + ll ret = 0; - ll M = 1e9+7; - sum[0][0] = diff[0][0]; - if (diff[0][0]>0) - ret += (row[1]-row[0])*(col[1]-col[0])%M; - for (int i=0; i=1?sum[i-1][j]:0) + (j>=1?sum[i][j-1]:0) - ((i>=1&&j>=1)?sum[i-1][j-1]:0) + diff[i][j]; - if (sum[i][j] > 0) - ret = (ret + (row[i+1]-row[i])*(col[j+1]-col[j])) % M; + if (grid.f[i][j]>0) + { + ll dx = row[i+1]-row[i]; + ll dy = col[j+1]-col[j]; + ret += dx*dy%M; + ret %= M; + } } - return ret; } }; From c9a66d6b616cc360e2ea054e63893587c07743e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Jan 2022 15:51:01 -0800 Subject: [PATCH 0334/2729] Update Readme.md --- Template/Diff_Array_2D/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Template/Diff_Array_2D/Readme.md b/Template/Diff_Array_2D/Readme.md index 6adfd2086..e2ae5aeeb 100644 --- a/Template/Diff_Array_2D/Readme.md +++ b/Template/Diff_Array_2D/Readme.md @@ -5,6 +5,8 @@ diff[x0][y1+1]-=1; diff[x1+1][y0]-=1; diff[x1+1][y1+1]+=1; ``` +其中diff[i][j]的物理意义是,以(i,j)为左上角、延伸至大矩阵的右下角,这样的区域我们整体赋值. + 这样的操作可以进行多次。如果我们想重构更新后的f的值,需要做如下操作: ``` for (int i=0; i Date: Thu, 13 Jan 2022 01:55:32 -0800 Subject: [PATCH 0335/2729] Create 1685.Sum-of-Absolute-Differences-in-a-Sorted-Array.cpp --- ...Absolute-Differences-in-a-Sorted-Array.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array.cpp diff --git a/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array.cpp b/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array.cpp new file mode 100644 index 000000000..2cd16885f --- /dev/null +++ b/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector getSumAbsoluteDifferences(vector& nums) + { + int n = nums.size(); + vectorret(n); + int sum = 0; + for (int i=1; i Date: Thu, 13 Jan 2022 01:56:44 -0800 Subject: [PATCH 0336/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index bf84f9b28..8ea42a54e 100644 --- a/Readme.md +++ b/Readme.md @@ -1143,6 +1143,8 @@ [1904.The-Number-of-Full-Rounds-You-Have-Played](https://github.com/wisdompeak/LeetCode/tree/master/Others/1904.The-Number-of-Full-Rounds-You-Have-Played) (M) [1997.First-Day-Where-You-Have-Been-in-All-the-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/1997.First-Day-Where-You-Have-Been-in-All-the-Rooms) (H) [2018.Check-if-Word-Can-Be-Placed-In-Crossword](https://github.com/wisdompeak/LeetCode/tree/master/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword) (M+) +* ``结论转移`` +[1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 38474bd2d499ef6fabf009f5272624098720a974 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 02:07:18 -0800 Subject: [PATCH 0337/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/Readme.md diff --git a/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/Readme.md b/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/Readme.md new file mode 100644 index 000000000..72b8f5e73 --- /dev/null +++ b/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/Readme.md @@ -0,0 +1,11 @@ +### 1685.Sum-of-Absolute-Differences-in-a-Sorted-Array + +假设我们已知“所有元素与nums[i-1]的差的绝对值的和是sum”,那么我们可以推论出“所有元素与nums[i]的差的绝对值的和”。见下图的分析。我们称被比较的那个数是“目标值”(即上一个回合是nums[i-1],这一个回合是nums[i]). +``` +X X X X, i-1, i, X X X X +``` +随着目标值的移动,原先目标值左边的元素(包括自身,即nums[0:i-1])与新目标值的差值全部都增加了```nums[i]-nums[i-1]```,总共增加了```(nums[i]-nums[i-1])*i```. + +同时,原先目标值右边的元素(即nums[i:n-1])与新目标值的差值全部都减少了```nums[i]-nums[i-1]```,总共减少了```(nums[i]-nums[i-1])*(n-i)```. + +可见```sum[i] = sum[i-1]+(nums[i]-nums[i-1])*i-(nums[i]-nums[i-1])*(n-i)```. From cab921c517ceba8b1f3cbc73f6bc1c7d0a325543 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 02:07:46 -0800 Subject: [PATCH 0338/2729] Update Readme.md --- .../Readme.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/Readme.md b/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/Readme.md index 72b8f5e73..e2e2bd947 100644 --- a/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/Readme.md +++ b/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array/Readme.md @@ -4,8 +4,6 @@ ``` X X X X, i-1, i, X X X X ``` -随着目标值的移动,原先目标值左边的元素(包括自身,即nums[0:i-1])与新目标值的差值全部都增加了```nums[i]-nums[i-1]```,总共增加了```(nums[i]-nums[i-1])*i```. +随着目标值的移动,原先目标值左边的元素(包括自身,即nums[0:i-1])与新目标值的差值全部都增加了```nums[i]-nums[i-1]```,总共增加了```(nums[i]-nums[i-1])*i```. 随着目标值的移动,原先目标值右边的元素(即nums[i:n-1])与新目标值的差值全部都减少了```nums[i]-nums[i-1]```,总共减少了```(nums[i]-nums[i-1])*(n-i)```. -同时,原先目标值右边的元素(即nums[i:n-1])与新目标值的差值全部都减少了```nums[i]-nums[i-1]```,总共减少了```(nums[i]-nums[i-1])*(n-i)```. - -可见```sum[i] = sum[i-1]+(nums[i]-nums[i-1])*i-(nums[i]-nums[i-1])*(n-i)```. +可见我们有递推关系```sum[i] = sum[i-1]+(nums[i]-nums[i-1])*i-(nums[i]-nums[i-1])*(n-i)```. From 9ec8fd0f96efe05d7866d7f6973d0b52d6f876fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 15:30:59 -0800 Subject: [PATCH 0339/2729] Create 654.Maximum-Binary-Tree_v2.cpp --- .../654.Maximum-Binary-Tree_v2.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v2.cpp diff --git a/Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v2.cpp b/Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v2.cpp new file mode 100644 index 000000000..50c1a6d64 --- /dev/null +++ b/Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v2.cpp @@ -0,0 +1,33 @@ +/** + * 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* constructMaximumBinaryTree(vector& nums) + { + stackStack; + for (int i=0; ival < nums[i]) + { + node->left = Stack.top(); + Stack.pop(); + } + if (!Stack.empty()) + Stack.top()->right = node; + Stack.push(node); + } + while (Stack.size()>1) + Stack.pop(); + return Stack.top(); + } +}; From 39745c6cf266dc9487ddf8cfe5524e1a8644c46c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 15:31:28 -0800 Subject: [PATCH 0340/2729] Create 654.Maximum-Binary-Tree_v1.cpp --- .../654.Maximum-Binary-Tree_v1.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v1.cpp diff --git a/Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v1.cpp b/Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v1.cpp new file mode 100644 index 000000000..b560b8071 --- /dev/null +++ b/Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v1.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* constructMaximumBinaryTree(vector& nums) + { + return DFS(nums,0,nums.size()-1); + } + + TreeNode* DFS(vector& nums, int start, int end) + { + int MAX=INT_MIN; + int index=0; + if (start>end) return NULL; + + for (int i=start; i<=end; i++) + { + if (nums[i]>MAX) + { + MAX=nums[i]; + index=i; + } + } + + TreeNode* root=new TreeNode(nums[index]); + root->left=DFS(nums,start,index-1); + root->right=DFS(nums,index+1,end); + return root; + } +}; From 0fb535994f907d0095a767ded18c5af7f1136e08 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 15:33:27 -0800 Subject: [PATCH 0341/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 8ea42a54e..42912c216 100644 --- a/Readme.md +++ b/Readme.md @@ -236,6 +236,7 @@ [106.Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/106.Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal) (M+) [331.Verify-Preorder-Serialization-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/331.Verify-Preorder-Serialization-of-a-Binary-Tree) (H) [449.Serialize-and-Deserialize-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/449.Serialize-and-Deserialize-BST) (H) +[654.Maximum-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/654.Maximum-Binary-Tree) (H) [971.Flip-Binary-Tree-To-Match-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/971.Flip-Binary-Tree-To-Match-Preorder-Traversal) (M+) [1028.Recover-a-Tree-From-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1028.Recover-a-Tree-From-Preorder-Traversal) (H-) [1569.Number-of-Ways-to-Reorder-Array-to-Get-Same-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1569.Number-of-Ways-to-Reorder-Array-to-Get-Same-BST) (H) @@ -319,6 +320,7 @@ [496.Next-Greater-Element-I](https://github.com/wisdompeak/LeetCode/tree/master/Stack/496.Next-Greater-Element-I) (H-) [503.Next-Greater-Element-II](https://github.com/wisdompeak/LeetCode/blob/master/Stack/503.Next-Greater-Element-II) (H-) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) +[654.Maximum-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/654.Maximum-Binary-Tree) (H) [739.Daily-Temperatures](https://github.com/wisdompeak/LeetCode/tree/master/Stack/739.Daily-Temperatures) (H-) [768.Max-Chunks-To-Make-Sorted-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/768.Max-Chunks-To-Make-Sorted-II) (H-) [901.Online-Stock-Span](https://github.com/wisdompeak/LeetCode/tree/master/Stack/901.Online-Stock-Span) (H-) From a6db12f11dcc4bd369ea2ccf052f122797859d9d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 15:47:22 -0800 Subject: [PATCH 0342/2729] Create Readme.md --- Stack/654.Maximum-Binary-Tree/Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Stack/654.Maximum-Binary-Tree/Readme.md diff --git a/Stack/654.Maximum-Binary-Tree/Readme.md b/Stack/654.Maximum-Binary-Tree/Readme.md new file mode 100644 index 000000000..b7740cdb6 --- /dev/null +++ b/Stack/654.Maximum-Binary-Tree/Readme.md @@ -0,0 +1,18 @@ +### 654.Maximum-Binary-Tree + +#### 解法1:暴力递归 +每一次遍历一段区间寻找里面的最大值,然后以其为根,左右两侧的子区间各自递归建树、并作为根的左节点和右节点。 + +这样的时间复杂度是Nlog(N),其中log(N)表示树的层树。如果这个序列是递增的,那么树的层数会是o(N),算法退化成o(N^2). + +#### 解法2:单调栈 +此处单调栈的用法非常巧妙,并没有相似的题目,有一定的难度。 + +我们维护一个单调递减的序列。我们想象一下,如果当前数组元素里都是递减的,那么他们必然组成连续的右节点的关系。OK,此时突然出现了一个较大的数A,那么A的左节点必然连接目前栈里面恰好比A小的那个元素。所以你需要不停地腾退栈顶元素,并且把最后一个恰好比A小的那个元素B接到A的左节点上。同时,A需要设置为当前栈顶元素C的右节点。如下图所示,相当于把A插入了C的右子树里,原先B子树都移到了A的左子树。这样就实现了题目所要求的目的。 +``` + C + \ A + B + \ +``` +最终,栈底的元素(最大值)就是全局的根节点。 From 67f8671a2d4ebb2d54af458037aeac08bf2b6f5e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 15:52:02 -0800 Subject: [PATCH 0343/2729] Create 2121.Intervals-Between-Identical-Elements.cpp --- ...1.Intervals-Between-Identical-Elements.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Others/2121.Intervals-Between-Identical-Elements/2121.Intervals-Between-Identical-Elements.cpp diff --git a/Others/2121.Intervals-Between-Identical-Elements/2121.Intervals-Between-Identical-Elements.cpp b/Others/2121.Intervals-Between-Identical-Elements/2121.Intervals-Between-Identical-Elements.cpp new file mode 100644 index 000000000..6451c4bc2 --- /dev/null +++ b/Others/2121.Intervals-Between-Identical-Elements/2121.Intervals-Between-Identical-Elements.cpp @@ -0,0 +1,42 @@ +using LL = long long; +class Solution { +public: + vector getDistances(vector& arr) + { + unordered_map>Map; + for (int i=0; i>rets; + for (auto x:Map) + { + int val = x.first; + auto pos = x.second; + int n = pos.size(); + + LL sum0 = 0; + LL sum1 = 0; + for (int i=1; ians; + unordered_mapindex; + for (auto x: arr) + { + int idx = index[x]; + ans.push_back(rets[x][idx]); + index[x]+=1; + } + return ans; + + } +}; From a4add20f74b287b5876738c27b5fbe63a695e0e2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 15:52:41 -0800 Subject: [PATCH 0344/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 42912c216..d326eba48 100644 --- a/Readme.md +++ b/Readme.md @@ -1147,6 +1147,7 @@ [2018.Check-if-Word-Can-Be-Placed-In-Crossword](https://github.com/wisdompeak/LeetCode/tree/master/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) +[2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From a9c3d2eb900b3a73b185aaf236ab4fa6f8358319 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 16:01:36 -0800 Subject: [PATCH 0345/2729] Create Readme.md --- Others/2121.Intervals-Between-Identical-Elements/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/2121.Intervals-Between-Identical-Elements/Readme.md diff --git a/Others/2121.Intervals-Between-Identical-Elements/Readme.md b/Others/2121.Intervals-Between-Identical-Elements/Readme.md new file mode 100644 index 000000000..48cbe0a5c --- /dev/null +++ b/Others/2121.Intervals-Between-Identical-Elements/Readme.md @@ -0,0 +1,3 @@ +### 2121.Intervals-Between-Identical-Elements + +此题是1685的升级版。我们需要对于每个数值,找出数组里存在该数值的index,然后直接用1685的思想,计算该index数组里所有元素到某一个元素的差的绝对值之和。 From 3b41dea58a9974c0c00b08c175e56ebb7c7ac196 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 13 Jan 2022 16:02:32 -0800 Subject: [PATCH 0346/2729] Update Readme.md --- Others/2121.Intervals-Between-Identical-Elements/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2121.Intervals-Between-Identical-Elements/Readme.md b/Others/2121.Intervals-Between-Identical-Elements/Readme.md index 48cbe0a5c..c57596f92 100644 --- a/Others/2121.Intervals-Between-Identical-Elements/Readme.md +++ b/Others/2121.Intervals-Between-Identical-Elements/Readme.md @@ -1,3 +1,3 @@ ### 2121.Intervals-Between-Identical-Elements -此题是1685的升级版。我们需要对于每个数值,找出数组里存在该数值的index,然后直接用1685的思想,计算该index数组里所有元素到某一个元素的差的绝对值之和。 +此题是1685的升级版。我们需要对于每个数值,找出数组里存在该数值的index,然后直接用1685的思想,计算该index数组里所有元素到某一个元素的差的绝对值之和。利用结论转移的特性,我们用o(1)就可以更新一个ret[i]. From 842855fb59fb04c6092b1d4e03ae4426ab7ca294 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 14 Jan 2022 00:13:52 -0800 Subject: [PATCH 0347/2729] Update 1027.Longest-Arithmetic-Sequence.cpp --- .../1027.Longest-Arithmetic-Sequence.cpp | 62 ++++++------------- 1 file changed, 18 insertions(+), 44 deletions(-) diff --git a/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.cpp b/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.cpp index a770b3b66..4c4985e30 100644 --- a/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.cpp +++ b/Dynamic_Programming/1027.Longest-Arithmetic-Sequence/1027.Longest-Arithmetic-Sequence.cpp @@ -1,49 +1,23 @@ class Solution { public: - int longestArithSeqLength(vector& nums) - { - // dynamic algorithm to solve longest arith sequence length - // dp[i][diff] = dp[j][diff] + 1 if diff exist in dp[j] - // else 2 - // where j < i - // and, it is guaranteed that if diff exists in both j and k where j < k - // dp[j][diff] <= dp[k][diff] - - int n = nums.size(); - - static int lASL_MAX = 1000; - static int lASL_MIN = 2; - - // the maximum diff to form a longer arith sequence by looking forward - static int DIFF = (lASL_MAX-lASL_MIN)/2; - - // biggest size the diff array should be maintained - static int DIFF_MAX_SIZE = 2 * DIFF + 1; - - // the 2d dp array, row label is array index, column label is diff + DIFF - - // if one num is not formed an arith sequence, we think it has potential - // to form any arith sequence - std::vector> dp(n, std::vector(DIFF_MAX_SIZE, 1)); - - int lasl = 2; - - for (auto r = 0; r != n; ++r) + int longestArithSeqLength(vector& A) { - for (auto l = 0; l < r; ++l) - { - int diff = nums[r] - nums[l]; - if (diff > DIFF || diff < -DIFF) - continue; - - diff += DIFF; - - dp[r][diff] = dp[l][diff] + 1; - - lasl = std::max(lasl, dp[r][diff]); - } + int n = A.size(); + int offset = 500; + vector>dp(n,vector(1001)); + int result = 1; + for (int i=0; i Date: Sat, 15 Jan 2022 14:57:40 -0800 Subject: [PATCH 0348/2729] Update 1531.String-Compression-II.cpp --- .../1531.String-Compression-II.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Dynamic_Programming/1531.String-Compression-II/1531.String-Compression-II.cpp b/Dynamic_Programming/1531.String-Compression-II/1531.String-Compression-II.cpp index ab0b8c964..36c909dd2 100644 --- a/Dynamic_Programming/1531.String-Compression-II/1531.String-Compression-II.cpp +++ b/Dynamic_Programming/1531.String-Compression-II/1531.String-Compression-II.cpp @@ -3,6 +3,21 @@ class Solution { public: int getLengthOfOptimalCompression(string s, int K) { + // Handling the special case of "a...a" where there are 100 as + if (s.size()==100 && K==0) + { + int flag = 1; + for (int i=1; i Date: Sat, 15 Jan 2022 15:06:49 -0800 Subject: [PATCH 0349/2729] Update 446.Arithmetic-Slices-II-Subsequence.cpp --- .../446.Arithmetic-Slices-II-Subsequence.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Hash/446.Arithmetic-Slices-II-Subsequence/446.Arithmetic-Slices-II-Subsequence.cpp b/Hash/446.Arithmetic-Slices-II-Subsequence/446.Arithmetic-Slices-II-Subsequence.cpp index 5ba9c0407..f5981f7eb 100644 --- a/Hash/446.Arithmetic-Slices-II-Subsequence/446.Arithmetic-Slices-II-Subsequence.cpp +++ b/Hash/446.Arithmetic-Slices-II-Subsequence/446.Arithmetic-Slices-II-Subsequence.cpp @@ -3,7 +3,7 @@ class Solution { int numberOfArithmeticSlices(vector& A) { int n = A.size(); - vector>dp(n); + unordered_mapdp[1000]; int count = 0; for (int i=1; i Date: Sat, 15 Jan 2022 15:17:17 -0800 Subject: [PATCH 0350/2729] Update Readme.md --- Hash/446.Arithmetic-Slices-II-Subsequence/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Hash/446.Arithmetic-Slices-II-Subsequence/Readme.md b/Hash/446.Arithmetic-Slices-II-Subsequence/Readme.md index d3d3b03f5..79474e441 100644 --- a/Hash/446.Arithmetic-Slices-II-Subsequence/Readme.md +++ b/Hash/446.Arithmetic-Slices-II-Subsequence/Readme.md @@ -14,7 +14,7 @@ 核心代码如下: ```cpp -vector>DP(N); +unorderd_mapDP[1000]; int count = 0; for (int i=0; i>Map. +想通过A[k]值找到k,需要提前处理,用到一个一对应多的hash表unordered_map>Map. 注意这种解法的时间复杂度是o(N^3). [Leetcode Link](https://leetcode.com/problems/arithmetic-slices-ii-subsequence) From 88639809ce608a0ae9fdf6bdee8ba0d3675282e6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 15 Jan 2022 15:20:35 -0800 Subject: [PATCH 0351/2729] Create 2007.Find-Original-Array-From-Doubled-Array.cpp --- ...Find-Original-Array-From-Doubled-Array.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array.cpp diff --git a/Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array.cpp b/Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array.cpp new file mode 100644 index 000000000..7d99a460c --- /dev/null +++ b/Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector findOriginalArray(vector& changed) + { + int n = changed.size(); + if (n%2!=0) return {}; + + multisetSet(changed.begin(), changed.end()); + vectorrets; + for (int t=0; t Date: Sat, 15 Jan 2022 15:23:30 -0800 Subject: [PATCH 0352/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d326eba48..80b9e5b3b 100644 --- a/Readme.md +++ b/Readme.md @@ -1102,6 +1102,7 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) [932.Beautiful-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/932.Beautiful-Array) (H) +[2007.Find-Original-Array-From-Doubled-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2007.Find-Original-Array-From-Doubled-Array) (M) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 2957719ac41cb4cfe249ce3b93c9423a97403071 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 15 Jan 2022 15:31:05 -0800 Subject: [PATCH 0353/2729] Create Readme.md --- Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md diff --git a/Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md b/Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md new file mode 100644 index 000000000..2c0e21e35 --- /dev/null +++ b/Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md @@ -0,0 +1,5 @@ +### 2007.Find-Original-Array-From-Doubled-Array + +很显然,changed里面的最大值,一定是original里面的最大值的两倍。这样,我们就把这两个数确定,并且从changed里面剔除。这样此时changed里面的最大值,就是original里面的第二大的值。我们同样可以把这两个元素从changed里面剔除,直至把所有元素都确定。 + +如果我们在这个过程中,发现changed里面的最大值x与x/2不同时存在于changed里面,说明无解。 From 01ffcea764f7f8523c1bbbb5a78673d1494037e2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jan 2022 01:20:04 -0800 Subject: [PATCH 0354/2729] Create 2122.Recover-the-Original-Array.cpp --- .../2122.Recover-the-Original-Array.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Greedy/2122.Recover-the-Original-Array/2122.Recover-the-Original-Array.cpp diff --git a/Greedy/2122.Recover-the-Original-Array/2122.Recover-the-Original-Array.cpp b/Greedy/2122.Recover-the-Original-Array/2122.Recover-the-Original-Array.cpp new file mode 100644 index 000000000..25109dcbf --- /dev/null +++ b/Greedy/2122.Recover-the-Original-Array/2122.Recover-the-Original-Array.cpp @@ -0,0 +1,45 @@ +using LL = long long; +class Solution { +public: + vector recoverArray(vector& nums) + { + int n = nums.size()/2; + sort(nums.begin(), nums.end()); + + for (int i=1; i<=n; i++) + { + if (nums[i]==nums[0]) continue; + if ((nums[i]+nums[0])%2==1) continue; + int mn = (nums[i]+nums[0])/2; + int k = (nums[i]-nums[0])/2; + + int left = 0, right = 1; + int flag = 1; + vectorvisited(2*n); + vectorrets; + for (int t=0; t Date: Sun, 16 Jan 2022 01:20:36 -0800 Subject: [PATCH 0355/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 80b9e5b3b..54a24db6e 100644 --- a/Readme.md +++ b/Readme.md @@ -1103,6 +1103,7 @@ [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) [932.Beautiful-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/932.Beautiful-Array) (H) [2007.Find-Original-Array-From-Doubled-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2007.Find-Original-Array-From-Doubled-Array) (M) +[2122.Recover-the-Original-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2122.Recover-the-Original-Array) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 49f3c27d494ee672b63b2f0e33469e3aaa607035 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jan 2022 08:23:11 -0800 Subject: [PATCH 0356/2729] Create 2007.Find-Original-Array-From-Doubled-Array_v2.cpp --- ...d-Original-Array-From-Doubled-Array_v2.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array_v2.cpp diff --git a/Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array_v2.cpp b/Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array_v2.cpp new file mode 100644 index 000000000..0f6049e4f --- /dev/null +++ b/Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array_v2.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector findOriginalArray(vector& changed) + { + int n =changed.size(); + if (n%2!=0) return {}; + + sort(changed.begin(), changed.end()); + + vectorrets; + int left = 0, right = 0; + vectorused(n); + for (int i=0; i Date: Sun, 16 Jan 2022 08:23:29 -0800 Subject: [PATCH 0357/2729] Rename 2007.Find-Original-Array-From-Doubled-Array.cpp to 2007.Find-Original-Array-From-Doubled-Array_v1.cpp --- ...ray.cpp => 2007.Find-Original-Array-From-Doubled-Array_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/2007.Find-Original-Array-From-Doubled-Array/{2007.Find-Original-Array-From-Doubled-Array.cpp => 2007.Find-Original-Array-From-Doubled-Array_v1.cpp} (100%) diff --git a/Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array.cpp b/Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array_v1.cpp similarity index 100% rename from Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array.cpp rename to Greedy/2007.Find-Original-Array-From-Doubled-Array/2007.Find-Original-Array-From-Doubled-Array_v1.cpp From 3259e1b7518cb6d1a09557df0f1121f5ea595773 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jan 2022 08:28:22 -0800 Subject: [PATCH 0358/2729] Update Readme.md --- .../2007.Find-Original-Array-From-Doubled-Array/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md b/Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md index 2c0e21e35..0fa3efd00 100644 --- a/Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md +++ b/Greedy/2007.Find-Original-Array-From-Doubled-Array/Readme.md @@ -3,3 +3,11 @@ 很显然,changed里面的最大值,一定是original里面的最大值的两倍。这样,我们就把这两个数确定,并且从changed里面剔除。这样此时changed里面的最大值,就是original里面的第二大的值。我们同样可以把这两个元素从changed里面剔除,直至把所有元素都确定。 如果我们在这个过程中,发现changed里面的最大值x与x/2不同时存在于changed里面,说明无解。 + +#### 解法1:multiset +上述的思想可以粗暴地用multiset来实现。每个回合,直接从multiset里面删除最大的元素x,然后再删除其中数值为x/2的元素。这样的时间复杂度是NlogN. + +#### 解法2:双指针 +更高效的解法是双指针。将changed排序之后,我们设置left和right两个指针。对于changed[left]而言,我们一定是单调递增地移动right,试图寻找满足```changed[right]==changed[left]*2```的位置。找到这对之后,将used[left]和used[right]都标记为1,这样在后续的寻找中,无论left和right都不能指向已经用过的位置。 + +双指针遍历的过程中,我们期望恰好找到n/2对。任何时候,left或right越界了,说明我们无法找到下一个合适的配对,就返回空集。 From bc0f36f94f14a10b2d1d4db05261415f9a1a29a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jan 2022 08:49:15 -0800 Subject: [PATCH 0359/2729] Create Readme.md --- Greedy/2122.Recover-the-Original-Array/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2122.Recover-the-Original-Array/Readme.md diff --git a/Greedy/2122.Recover-the-Original-Array/Readme.md b/Greedy/2122.Recover-the-Original-Array/Readme.md new file mode 100644 index 000000000..cf006052a --- /dev/null +++ b/Greedy/2122.Recover-the-Original-Array/Readme.md @@ -0,0 +1,7 @@ +### 2122.Recover-the-Original-Array + +我们将nums排序后,可以肯定的是,最小值一定是原先original里面的最小值mn减去k。那么如何能够知道mn或者k呢?自然我们想到original里面一定还存在mn+k,如果我们遍历元素并假设它是mn+k,那么我们就可以得到k,于是整个original的元素就可以试图从小到大依次确定下来(和LC 2007差不多的思想);如果不成功就换一个元素作为mn+k。所以此题用o(N^2)可解。 + +更具体地,如果我们知道了k,可以用双指针的解法来确定original。将nums排序之后,我们设置left和right两个指针。对于nums[left]而言,我们一定是单调递增地移动right,试图寻找满足```nums[right]==nums[left]+2k```的位置。找到这对之后,将used[left]和used[right]都标记为1,这样在后续的寻找中,无论left和right都不能指向已经用过的位置。 + +双指针遍历的过程中,我们期望恰好找到n对。任何时候,left或right越界了,说明我们无法找到下一个合适的配对,就返回空集。 From d126366776d07fa868aa79798d59d160d8d8775f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jan 2022 15:35:23 -0800 Subject: [PATCH 0360/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 54a24db6e..ee0aa8bfd 100644 --- a/Readme.md +++ b/Readme.md @@ -1027,7 +1027,6 @@ [1818.Minimum-Absolute-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1818.Minimum-Absolute-Sum-Difference) (M+) [1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number) (M+) [1911.Maximum-Alternating-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1911.Maximum-Alternating-Subsequence-Sum) (M+) -[1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) [2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses) (M+) [2136.Earliest-Possible-Day-of-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom) (M+) * ``LIS`` @@ -1104,6 +1103,7 @@ [932.Beautiful-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/932.Beautiful-Array) (H) [2007.Find-Original-Array-From-Doubled-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2007.Find-Original-Array-From-Doubled-Array) (M) [2122.Recover-the-Original-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2122.Recover-the-Original-Array) (H-) +[1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From ccb67576f97d18e860041063b4b13a8c3e6f07c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jan 2022 23:30:45 -0800 Subject: [PATCH 0361/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ee0aa8bfd..725b9475f 100644 --- a/Readme.md +++ b/Readme.md @@ -1079,6 +1079,7 @@ [448.Find-All-Numbers-Disappeared-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/448.Find-All-Numbers-Disappeared-in-an-Array) (M) [645.Set-Mismatch](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/645.Set-Mismatch) (M) * ``Parenthesis`` +[032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) [921.Minimum-Add-to-Make-Parentheses-Valid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/921.Minimum-Add-to-Make-Parentheses-Valid) (M+) [1249.Minimum-Remove-to-Make-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1249.Minimum-Remove-to-Make-Valid-Parentheses) (M+) [1541.Minimum-Insertions-to-Balance-a-Parentheses-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1541.Minimum-Insertions-to-Balance-a-Parentheses-String) (M+) From f02cb114e41d0b490b8148965db2f1a422eda31d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Jan 2022 00:17:28 -0800 Subject: [PATCH 0362/2729] Create 2140.Solving-Questions-With-Brainpower_v1.cpp --- .../2140.Solving-Questions-With-Brainpower_v1.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v1.cpp diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v1.cpp b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v1.cpp new file mode 100644 index 000000000..e60ba9d28 --- /dev/null +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v1.cpp @@ -0,0 +1,15 @@ +using LL = long long; +class Solution { +public: + long long mostPoints(vector>& questions) + { + int n = questions.size(); + vectordp(n+1, 0); + for (int i=n-1; i>=0; i--) + { + int skip = questions[i][1]; + dp[i] = max(dp[i+1], dp[min(i+skip+1, n)] + questions[i][0]); + } + return dp[0]; + } +}; From 0c69c26fc8005a1eb2e8a124b8bac58268d2d8d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Jan 2022 17:56:34 -0800 Subject: [PATCH 0363/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 725b9475f..7027030d2 100644 --- a/Readme.md +++ b/Readme.md @@ -731,6 +731,7 @@ [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) * ``Infer future from current`` [2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) +[2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H-) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From f0c7dde7a254be709c5f87d7e8628109b3545e5d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Jan 2022 21:05:34 -0800 Subject: [PATCH 0364/2729] Create 2140.Solving-Questions-With-Brainpower_v2.cpp --- ...0.Solving-Questions-With-Brainpower_v2.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v2.cpp diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v2.cpp b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v2.cpp new file mode 100644 index 000000000..967089aa5 --- /dev/null +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v2.cpp @@ -0,0 +1,21 @@ +using LL = long long; +class Solution { +public: + long long mostPoints(vector>& questions) + { + int n = questions.size(); + LL ret = 0; + vectordp(n, 0); // dp[i]: the maximum gain before making deicisions on i-th problem + for (int i=0; i Date: Mon, 17 Jan 2022 21:25:34 -0800 Subject: [PATCH 0365/2729] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md new file mode 100644 index 000000000..ea8b3341d --- /dev/null +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md @@ -0,0 +1,19 @@ +### 2140.Solving-Questions-With-Brainpower + + +#### 解法3 (错误) +令dp[i]表示处理前i个元素能取得的最大值。 +```cpp +for (int i=0; i Date: Tue, 18 Jan 2022 00:44:01 -0800 Subject: [PATCH 0366/2729] Update 2140.Solving-Questions-With-Brainpower_v2.cpp --- ...0.Solving-Questions-With-Brainpower_v2.cpp | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v2.cpp b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v2.cpp index 967089aa5..cc1cc9aa9 100644 --- a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v2.cpp +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v2.cpp @@ -1,21 +1,30 @@ using LL = long long; class Solution { public: - long long mostPoints(vector>& questions) - { + long long mostPoints(vector>& questions) { int n = questions.size(); - LL ret = 0; - vectordp(n, 0); // dp[i]: the maximum gain before making deicisions on i-th problem + vector> dp(n, vector(2)); + dp[0][1] = questions[0][0]; + + vector>endTimes; for (int i=0; i Date: Tue, 18 Jan 2022 00:51:17 -0800 Subject: [PATCH 0367/2729] Update Readme.md --- .../Readme.md | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md index ea8b3341d..da0793822 100644 --- a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md @@ -1,19 +1,24 @@ ### 2140.Solving-Questions-With-Brainpower +#### 解法1 -#### 解法3 (错误) -令dp[i]表示处理前i个元素能取得的最大值。 -```cpp -for (int i=0; i Date: Wed, 19 Jan 2022 00:27:28 -0800 Subject: [PATCH 0368/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7027030d2..c49aa5080 100644 --- a/Readme.md +++ b/Readme.md @@ -584,6 +584,7 @@ [1937.Maximum-Number-of-Points-with-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1937.Maximum-Number-of-Points-with-Cost) (H-) [1955.Count-Number-of-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1955.Count-Number-of-Special-Subsequences) (H-) [2088.Count-Fertile-Pyramids-in-a-Land](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land) (H-) +[2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) @@ -731,7 +732,6 @@ [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) * ``Infer future from current`` [2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) -[2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H-) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From 37713273a1de971680a86279301e796b5685987f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Jan 2022 00:32:54 -0800 Subject: [PATCH 0369/2729] Update Readme.md --- .../2140.Solving-Questions-With-Brainpower/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md index da0793822..d4d6f7767 100644 --- a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md @@ -19,6 +19,6 @@ dp[i][0] = max(dp[i-1][0], dp[i-1][1]); dp[i][1] = max{dp[j][1]} + val[i]; ``` -其中第二项中的j是所有小于i的位置里、满足j的冷冻期不包括i、且dp[j][1]最大那个位置。我们如何不遍历全部、高效地找到那个j呢?我们提前把所有的index按照冷冻期结束的先后顺序排序。我们在从小到大遍历i的过程中,就可以顺序解锁那些j+skip[j] Date: Wed, 19 Jan 2022 00:53:52 -0800 Subject: [PATCH 0370/2729] Update Readme.md --- .../Readme.md | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md index d4d6f7767..034a17ad3 100644 --- a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md @@ -12,7 +12,7 @@ #### 解法2 -事实上本题存在传统的“填表”法DP,不过需要分别定义dp[i][0]和dp[i][1]表示第i个元素不取、取各自所能得到最大价值。 +事实上本题存在传统的“填表法”DP,不过需要分别定义dp[i][0]和dp[i][1]表示第i个元素不取、取各自所能得到最大价值。 我们有状态转移方程: ``` @@ -21,4 +21,20 @@ dp[i][1] = max{dp[j][1]} + val[i]; ``` 其中第二项中的j是所有小于i的位置里、满足j的冷冻期不包括i、且dp[j][1]最大那个位置。我们如何不遍历全部、高效地找到那个j呢?我们提前把所有的index按照冷冻期结束(即j+skip[j])的先后顺序排序。我们在从小到大遍历i的过程中,就可以顺序解锁那些j+skip[j]i+skip[i] +``` +第一项比较容易理解,第i+1个元素不取的话,dp[i+1]一定就完全取决于dp[i]了. + +对于第二项,我们注意到,我们必须同时更新多个dp[j][1]的值。如何高效地实现这个操作呢?我们联想到差分数组的策略。第二项的意思是从j=i+skip[i]+1开始到结束,每一个j的dp[j][1]都至少被抬升到了dp[i][1]的大小。所以我们可以新建一个数组```base[i+skip[i]+1]```来表示从j=i+skip[i]+1开始到结束,所有的dp[j][1]都被统一抬升dp[i][1]。 + +我们在遍历i的过程中,需要滚动更新当前的抬升```diff = max(diff, base[i])```,然后更新```dp[i][1] = diff + questions[i][0]```。最后根据当前的dp[i][1]来更新未来的base[j]。 + +最终返回的答案是max{dp[n-1][0],dp[n-1][1]}。 From eba99f262e97fb18f688230212f1d602b0b866b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Jan 2022 00:54:51 -0800 Subject: [PATCH 0371/2729] Update Readme.md --- .../2140.Solving-Questions-With-Brainpower/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md index 034a17ad3..cee0cffdb 100644 --- a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md @@ -4,7 +4,7 @@ 因为n是1e5数量级,我们期望能用o(n)的时间复杂度解决。我们尝试令dp[i]表示前i个元素能取得的最大值,特别注意到,dp一定是递增的序列。 -第一种“填表”思路是用已知的dp来计算当前的dp[i]。显然,如果我们不取第i个元素,那么dp[i]=dp[i+1];如果我们取第i个元素,那么就有```dp[i] = dp[j] + val[i], where j Date: Thu, 20 Jan 2022 00:44:47 -0800 Subject: [PATCH 0372/2729] Create 2140.Solving-Questions-With-Brainpower_v3.cpp --- ...0.Solving-Questions-With-Brainpower_v3.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v3.cpp diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v3.cpp b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v3.cpp new file mode 100644 index 000000000..ee83bdb25 --- /dev/null +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v3.cpp @@ -0,0 +1,27 @@ +using LL = long long; +class Solution { +public: + long long mostPoints(vector>& questions) { + int n = questions.size(); + vector> dp(n, vector(2)); + dp[0][1] = questions[0][0]; + + vectorbase(n); + LL diff = 0; + + LL maxPre = 0; + for (int i = 0; i < n; ++i) + { + diff = max(diff, base[i]); + dp[i][1] = diff + questions[i][0]; + + int skip = questions[i][1]; + if (i+1 Date: Thu, 20 Jan 2022 00:49:42 -0800 Subject: [PATCH 0373/2729] Update Readme.md --- .../2140.Solving-Questions-With-Brainpower/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md index cee0cffdb..9e9d106c1 100644 --- a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/Readme.md @@ -4,7 +4,7 @@ 因为n是1e5数量级,我们期望能用o(n)的时间复杂度解决。我们尝试令dp[i]表示前i个元素能取得的最大值,特别注意到,dp一定是递增的序列。 -第一种“填表”思路是用已知的dp来计算当前的dp[i]。显然,如果我们不取第i个元素,那么dp[i]=dp[i-1];如果我们取第i个元素,那么就有```dp[i] = dp[j] + val[i], where j Date: Thu, 20 Jan 2022 01:52:30 -0800 Subject: [PATCH 0374/2729] Update 2140.Solving-Questions-With-Brainpower_v1.cpp --- .../2140.Solving-Questions-With-Brainpower_v1.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v1.cpp b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v1.cpp index e60ba9d28..e9718ed49 100644 --- a/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v1.cpp +++ b/Dynamic_Programming/2140.Solving-Questions-With-Brainpower/2140.Solving-Questions-With-Brainpower_v1.cpp @@ -4,12 +4,12 @@ class Solution { long long mostPoints(vector>& questions) { int n = questions.size(); - vectordp(n+1, 0); + vectordp(n+1); for (int i=n-1; i>=0; i--) { - int skip = questions[i][1]; - dp[i] = max(dp[i+1], dp[min(i+skip+1, n)] + questions[i][0]); + int j = i+questions[i][1]+1; + dp[i] = max(dp[i+1], (j Date: Sat, 22 Jan 2022 00:15:27 +0800 Subject: [PATCH 0375/2729] Create 2121.Intervals-Between-Identical-Elements_v2.cpp A faster way to get return values. --- ...ntervals-Between-Identical-Elements_v2.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Others/2121.Intervals-Between-Identical-Elements/2121.Intervals-Between-Identical-Elements_v2.cpp diff --git a/Others/2121.Intervals-Between-Identical-Elements/2121.Intervals-Between-Identical-Elements_v2.cpp b/Others/2121.Intervals-Between-Identical-Elements/2121.Intervals-Between-Identical-Elements_v2.cpp new file mode 100644 index 000000000..627c0693e --- /dev/null +++ b/Others/2121.Intervals-Between-Identical-Elements/2121.Intervals-Between-Identical-Elements_v2.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + vector getDistances(vector& arr) { + int n = arr.size(); + vector rets(n, 0); + unordered_map> Map; + + for(int i = 0; i < arr.size(); ++i) { + Map[arr[i]].push_back(i); + } + + for(auto& [val, pos]: Map) { + for(int x: pos) { + rets[pos[0]] += x - pos[0]; + } + + for(int i = 1; i < pos.size(); ++i) { + rets[pos[i]] = rets[pos[i-1]] + (pos[i] - pos[i-1]) * i - (pos[i] - pos[i-1]) * (pos.size() - i); + } + } + + return rets; + } +}; + +// 0 1 2 3 4 5 6 +// 2,1,3,1,2,3,3 + +// 1: 1 3 +// 2: 0 4 +// 3: 2 5 6 + +// i m - i +// {X X X i-1} {i X X X X} From 0045cb57f9ad10162e814c260c040cf091926570 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 21 Jan 2022 23:46:58 -0800 Subject: [PATCH 0376/2729] Create 2141.Maximum-Running-Time-of-N-Computers.cpp --- ...41.Maximum-Running-Time-of-N-Computers.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Binary_Search/2141.Maximum-Running-Time-of-N-Computers/2141.Maximum-Running-Time-of-N-Computers.cpp diff --git a/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/2141.Maximum-Running-Time-of-N-Computers.cpp b/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/2141.Maximum-Running-Time-of-N-Computers.cpp new file mode 100644 index 000000000..698336057 --- /dev/null +++ b/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/2141.Maximum-Running-Time-of-N-Computers.cpp @@ -0,0 +1,37 @@ +using LL = long long; +class Solution { +public: + long long maxRunTime(int n, vector& batteries) + { + LL left = 0, right = LLONG_MAX/2; + // sort(batteries.rbegin(), batteries.rend()); + + while (left < right) + { + LL mid = right-(right-left)/2; + if (checkOK(mid, batteries, n)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool checkOK(LL T, vector&nums, int n) + { + int count = 0; + LL cur = 0; + for (int i=0; i= T) + { + count++; + cur-=T; + } + if (count >= n) + return true; + } + return false; + } +}; From f0d278e82ac0153cd7982f719cd17523db979f78 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 21 Jan 2022 23:47:25 -0800 Subject: [PATCH 0377/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c49aa5080..3a14ef52c 100644 --- a/Readme.md +++ b/Readme.md @@ -82,6 +82,7 @@ [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) +[2141.Maximum-Running-Time-of-N-Computers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2141.Maximum-Running-Time-of-N-Computers) (M+) * ``Binary Processing`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) From 03740e8668b69c93da50b5937f495f3db35c7991 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 21 Jan 2022 23:54:08 -0800 Subject: [PATCH 0378/2729] Create Readme.md --- .../2141.Maximum-Running-Time-of-N-Computers/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2141.Maximum-Running-Time-of-N-Computers/Readme.md diff --git a/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/Readme.md b/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/Readme.md new file mode 100644 index 000000000..7b54eb85a --- /dev/null +++ b/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/Readme.md @@ -0,0 +1,5 @@ +### 2141.Maximum-Running-Time-of-N-Computers + +万事不决用二分。本题的本质就是设计检验函数checkOK(int T),看看是否能支持N台电脑运行T时间。因为电池可以任意分配给各个电脑和各个时段,所以策略很简单,把所有的电池容量加起来,查看能否支撑```T*N```即可。唯一需要注意的就是,任意一个电池都不能贡献超过时间T(因为我们只会让电脑运行时间T)。所以我们在算电池总容量的时候,取T为上限。 + +有了checkOK函数,那么我们不断猜测T。如果返回true,说明T可能是解,但也许还可以更大,那么我们就可以再往上猜;如果返回false,说明T太长了,就往下猜。本题一定有解,那么收敛解就是最终解。 From 4ad01fd604d4494b3fa7d0e12cf80815f1d593a3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jan 2022 00:07:46 -0800 Subject: [PATCH 0379/2729] Update 662.Maximum-Width-of-Binary-Tree.cpp --- .../662.Maximum-Width-of-Binary-Tree.cpp | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/Tree/662.Maximum-Width-of-Binary-Tree/662.Maximum-Width-of-Binary-Tree.cpp b/Tree/662.Maximum-Width-of-Binary-Tree/662.Maximum-Width-of-Binary-Tree.cpp index f12a8b9d0..63d3f829d 100644 --- a/Tree/662.Maximum-Width-of-Binary-Tree/662.Maximum-Width-of-Binary-Tree.cpp +++ b/Tree/662.Maximum-Width-of-Binary-Tree/662.Maximum-Width-of-Binary-Tree.cpp @@ -21,29 +21,25 @@ class Solution { int len = q.size(); ans = max(ans, q.back()->val - q.front()->val + 1); - int flag = (len == 1); + int base = q.front()->val; while (len--) { TreeNode* node = q.front(); q.pop_front(); - - if (flag==1) node->val = 0; if (node->left) { - node->left->val = node->val*2+1; + node->left->val = (node->val-base)*2+1; q.push_back(node->left); } if (node->right) { - node->right->val = node->val*2+2; + node->right->val = (node->val-base)*2+2; q.push_back(node->right); } } } return ans; } - - }; From a0c9ea9d337ebd33838bc630a173221acb52ca98 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jan 2022 00:09:27 -0800 Subject: [PATCH 0380/2729] Update Readme.md --- Tree/662.Maximum-Width-of-Binary-Tree/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tree/662.Maximum-Width-of-Binary-Tree/Readme.md b/Tree/662.Maximum-Width-of-Binary-Tree/Readme.md index 7d962f4b9..effa93a79 100644 --- a/Tree/662.Maximum-Width-of-Binary-Tree/Readme.md +++ b/Tree/662.Maximum-Width-of-Binary-Tree/Readme.md @@ -2,8 +2,8 @@ 利用二叉树的这个性质:若一个节点的深度是level,在该层的序号是order,则其左子树的深度是level+1且在该层的序号是```order*2```,其右子树的深度是level+1且在该层的序号是```order*2+1```。 -我们可以用BFS的思想,对这棵树做层级遍历。那么每层的的第一个节点和最后一个节点的序号之差就代表了这一层的宽度。数据结构的使用上,deque比queue更方便一些。 +我们可以用BFS的思想,对这棵树做层级遍历。那么每层的的第一个节点和最后一个节点的序号之差就代表了这一层的宽度。 -本题需要优化的第一个地方是:随着层级的深入,节点序号的数值也会膨胀,可以想象,当超过128层的时候,序号连long long都无法记录了。优化的方法是:如果某一层只有一个节点的话,我们可以把那个节点看做成根节点,并将其序号reset成为0. 这样它之后层级的节点序号就又变小了,同时也不影响最终结果。 +本题需要优化的第一个地方是:随着层级的深入,节点序号的数值也会膨胀,可以想象,当超过128层的时候,序号连long long都无法记录了。优化的方法是:将同一层的节点的序号统一削减掉该层第一个节点的序号,这样不会影响每一层宽度的计算。 [Leetcode Link](https://leetcode.com/problems/maximum-width-of-binary-tree) From 5bafa88808c1a25a444e882afcf3b99667a036d1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jan 2022 15:22:16 -0800 Subject: [PATCH 0381/2729] Create 5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp --- ...mber-of-Ways-to-Divide-a-Long-Corridor.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Others/5974.Number-of-Ways-to-Divide-a-Long-Corridor/5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp diff --git a/Others/5974.Number-of-Ways-to-Divide-a-Long-Corridor/5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp b/Others/5974.Number-of-Ways-to-Divide-a-Long-Corridor/5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp new file mode 100644 index 000000000..8a471d3dd --- /dev/null +++ b/Others/5974.Number-of-Ways-to-Divide-a-Long-Corridor/5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp @@ -0,0 +1,29 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int numberOfWays(string corridor) + { + int n = corridor.size(); + + vectorseats; + for (int i=0; i Date: Sat, 22 Jan 2022 15:22:54 -0800 Subject: [PATCH 0382/2729] Rename Others/5974.Number-of-Ways-to-Divide-a-Long-Corridor/5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp to Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor/2147.Number-of-Ways-to-Divide-a-Long-Corridor.cpp --- .../2147.Number-of-Ways-to-Divide-a-Long-Corridor.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Others/{5974.Number-of-Ways-to-Divide-a-Long-Corridor/5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp => 2147.Number-of-Ways-to-Divide-a-Long-Corridor/2147.Number-of-Ways-to-Divide-a-Long-Corridor.cpp} (100%) diff --git a/Others/5974.Number-of-Ways-to-Divide-a-Long-Corridor/5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp b/Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor/2147.Number-of-Ways-to-Divide-a-Long-Corridor.cpp similarity index 100% rename from Others/5974.Number-of-Ways-to-Divide-a-Long-Corridor/5974.Number-of-Ways-to-Divide-a-Long-Corridor.cpp rename to Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor/2147.Number-of-Ways-to-Divide-a-Long-Corridor.cpp From 5afc7baeac9aa9ccaf0ca5c08a4b374ac877bfef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jan 2022 15:23:47 -0800 Subject: [PATCH 0383/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3a14ef52c..aa5ebbd3e 100644 --- a/Readme.md +++ b/Readme.md @@ -1150,6 +1150,7 @@ [1904.The-Number-of-Full-Rounds-You-Have-Played](https://github.com/wisdompeak/LeetCode/tree/master/Others/1904.The-Number-of-Full-Rounds-You-Have-Played) (M) [1997.First-Day-Where-You-Have-Been-in-All-the-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/1997.First-Day-Where-You-Have-Been-in-All-the-Rooms) (H) [2018.Check-if-Word-Can-Be-Placed-In-Crossword](https://github.com/wisdompeak/LeetCode/tree/master/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword) (M+) +[2147.Number-of-Ways-to-Divide-a-Long-Corridor](https://github.com/wisdompeak/LeetCode/tree/master/Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor) (M) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 85ec016074e836e49d6405fcaf53d0761ac7e804 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jan 2022 15:31:27 -0800 Subject: [PATCH 0384/2729] Create Readme.md --- .../2147.Number-of-Ways-to-Divide-a-Long-Corridor/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor/Readme.md diff --git a/Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor/Readme.md b/Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor/Readme.md new file mode 100644 index 000000000..6fe7aea6a --- /dev/null +++ b/Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor/Readme.md @@ -0,0 +1,5 @@ +### 2147.Number-of-Ways-to-Divide-a-Long-Corridor + +本题的思想非常简单,就是将每两个沙发作为一组,然后查看每组之间有几个植物。这些植物之间、植物与两侧的沙发之间都可以插板。然后用乘法原理计算总的策略数目。 + +本题如果在原数组上操作,会显得有些繁琐。直接将沙发的index拿出来放在一个新数组里,这样每相邻两个元素一组,每组之间的间隔就一目了然。 From e287106c007b5ce282741d940734469814624a50 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 01:35:27 -0800 Subject: [PATCH 0385/2729] Create 2127.Maximum-Employees-to-Be-Invited-to-a-Meeting.cpp --- ...m-Employees-to-Be-Invited-to-a-Meeting.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting.cpp diff --git a/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting.cpp b/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting.cpp new file mode 100644 index 000000000..0c40b4971 --- /dev/null +++ b/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + int maximumInvitations(vector& favorite) + { + int n = favorite.size(); + vectorindegree(n); + for (int i=0; iq; + vectorvisited(n); + vectordepth(n,1); + for (int i=0; i2) + max_circle_size = max(max_circle_size, count); + else if (count==2) + max_link_size += depth[i]+depth[favorite[i]]; + } + + return max(max_circle_size, max_link_size); + } +}; From 6cf4daa5eca5f8040e84970f676f27e741f27b51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 01:35:54 -0800 Subject: [PATCH 0386/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index aa5ebbd3e..4c5beb65d 100644 --- a/Readme.md +++ b/Readme.md @@ -488,6 +488,7 @@ [1857.Largest-Color-Value-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1857.Largest-Color-Value-in-a-Directed-Graph) (H-) [2050.Parallel-Courses-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2050.Parallel-Courses-III) (M+) [2115.Find-All-Possible-Recipes-from-Given-Supplies](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies) (M) +[2127.Maximum-Employees-to-Be-Invited-to-a-Meeting](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting) (H) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From d44f97624e3521a760c0ab5c4ab58c18bf2967aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 02:00:24 -0800 Subject: [PATCH 0387/2729] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md diff --git a/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md b/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md new file mode 100644 index 000000000..d38433979 --- /dev/null +++ b/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md @@ -0,0 +1,14 @@ +### 2127.Maximum-Employees-to-Be-Invited-to-a-Meeting + +我们设想一下从任意一个人出发,不停地沿着“舔狗链”传递,最终会出现什么情况?一定会出现一个环。因为本题里规定了所有的人都有出度(即有喜欢的人),否则没有环的话那就一定有出度为0的dead end。所以题目中构造出的图,一定长得是这样的模式:一个连通图以一个环为主体,另外可能有若干单链指向环上的节点。当然,这种连通图可能会有多个(即彼此不相连)。 + +此时我们可以想到的是,选择这些环一定是满足条件的策略。因为只有环才能满足每个人都与喜欢的人相邻,否则引入任何其他分支(单链)都无法满足条件(因为在接入点处,会有一个出度,两个入度,但每个人在圆桌上只允许有两个邻居)。于是,选择其中最大的环,似乎就是最佳选择。 + +但是以上的分析只适用于环的节点个数>=3的时候。如果存在一个节点数为2的环(即两个人A和B互相喜欢),那么任何指向A的单链和指向B的单链加入其中,依然是合法的圆桌策略。所以我们需要考虑这一种可能:大小为2的环,加上两个节点所外接的各自最长单链。更神奇的时候,事实上我们把所有这种“二元环+二单链”模式的连通图的节点都围坐起来,依然是一个合法的策略。 + +所以本题的答案应该是```max{“最大的多元环”的大小,“所有二元环+二单链模式”的大小之和}```. + +具体的做法如下: +1. 利用拓扑排序,把所有非环的外围单链砍掉。同时有一个附加的好处,我们从每个入度为0的点开始标记深度,待拓扑排序结束后,我们就能得到所有环上的节点所外接的其中最长单链的长度。 +2. 将剩余的节点(一定都在环上)任取一个开始遍历,可以得到一个完整的环的大小。由此遍历所有的环。每遍历一个环,需要考察是二元环还是多元环。 +3. 输出答案:```max{“最大的多元环”的大小,“所有二元环+二单链模式”的大小之和}```. From b149fefa5f2725b3009b1146c898caab2c260e1d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 14:45:22 -0800 Subject: [PATCH 0388/2729] Update Readme.md --- BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md b/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md index d38433979..1dd523a65 100644 --- a/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md +++ b/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting/Readme.md @@ -6,7 +6,7 @@ 但是以上的分析只适用于环的节点个数>=3的时候。如果存在一个节点数为2的环(即两个人A和B互相喜欢),那么任何指向A的单链和指向B的单链加入其中,依然是合法的圆桌策略。所以我们需要考虑这一种可能:大小为2的环,加上两个节点所外接的各自最长单链。更神奇的时候,事实上我们把所有这种“二元环+二单链”模式的连通图的节点都围坐起来,依然是一个合法的策略。 -所以本题的答案应该是```max{“最大的多元环”的大小,“所有二元环+二单链模式”的大小之和}```. +所以本题的答案应该是```max{“最大的多元环”的大小,所有“二元环+二单链模式”的大小之和}```. 具体的做法如下: 1. 利用拓扑排序,把所有非环的外围单链砍掉。同时有一个附加的好处,我们从每个入度为0的点开始标记深度,待拓扑排序结束后,我们就能得到所有环上的节点所外接的其中最长单链的长度。 From fc60b53bcd0ce4e79b61edab5b7e078d3bbba5c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 15:29:07 -0800 Subject: [PATCH 0389/2729] Create 2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words.cpp --- ...rome-by-Concatenating-Two-Letter-Words.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words.cpp diff --git a/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words.cpp b/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words.cpp new file mode 100644 index 000000000..8c902abea --- /dev/null +++ b/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int longestPalindrome(vector& words) + { + unordered_mapcount1; + unordered_mapcount2; + unordered_mapcount3; + + for (auto str: words) + { + string str2 = str; + reverse(str2.begin(), str2.end()); + + if (str2==str) + count3[str]++; + else + { + string key = min(str2, str); + if (key==str) + count1[key]++; + else + count2[key]++; + } + } + + int ret = 0; + for (auto& [key, val]: count1) + { + int a = count1[key]; + int b = count2[key]; + ret += min(a,b)*2*2; + } + int flag = 0; + for (auto& [key, val]: count3) + { + ret += val/2*2*2; + if (val%2==1) + flag = 1; + } + + return ret+flag*2; + } +}; From d859a624d2776b46cb45c042b4bfb74a67cc587a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 15:32:47 -0800 Subject: [PATCH 0390/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4c5beb65d..7d8312dfa 100644 --- a/Readme.md +++ b/Readme.md @@ -146,6 +146,7 @@ 1224.Maximum-Equal-Frequency (H-) [1487.Making-File-Names-Unique](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1487.Making-File-Names-Unique) (M+) [1573.Number-of-Ways-to-Split-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1573.Number-of-Ways-to-Split-a-String) (M) +[2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words) (M) * ``Hash+Prefix`` [525.Contiguous-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/525.Contiguous-Array) (M) [930.Binary-Subarrays-With-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/930.Binary-Subarrays-With-Sum) (M) From c86e9cc4cb30011b7c84254d6cfc9b3cf171e822 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 15:36:11 -0800 Subject: [PATCH 0391/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words/Readme.md diff --git a/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words/Readme.md b/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words/Readme.md new file mode 100644 index 000000000..c84f56687 --- /dev/null +++ b/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words/Readme.md @@ -0,0 +1,5 @@ +### 2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words + +假设有字符串ab出现了count1次,字符串ba出现了count2次。那么我们就可以用min(count1,count2)个ab和ba对称放置组成回文串。 + +假设有字符串cc出现了count3次,那么我们就可以用```count3/2*2```个cc对称放置组成回文串。特别注意,如果有落单的、但是形如xx的字符串,我们可以额外放在正中间增加回文串的长度by 2. From 6a9cd659c53431578ca062269858db40022b3942 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 16:12:53 -0800 Subject: [PATCH 0392/2729] Create 2151.Maximum-Good-People-Based-on-Statements.cpp --- ...aximum-Good-People-Based-on-Statements.cpp | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements/2151.Maximum-Good-People-Based-on-Statements.cpp diff --git a/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements/2151.Maximum-Good-People-Based-on-Statements.cpp b/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements/2151.Maximum-Good-People-Based-on-Statements.cpp new file mode 100644 index 000000000..b10356233 --- /dev/null +++ b/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements/2151.Maximum-Good-People-Based-on-Statements.cpp @@ -0,0 +1,65 @@ +class Solution { +public: + bool checkOK(int state, vector>& statements) + { + int n = statements.size(); + vectorjudge(n, -1); + int flag = 1; + for (int i=0; i>i)&1); + if (t==0) continue; + + for (int j=0; j>i)&1); + if (t==1 && judge[i]==0) + { + flag = 0; + break; + } + + if (t==0 && judge[i]==1) + { + flag = 0; + break; + } + } + + return flag; + } + + int maximumGood(vector>& statements) + { + int m = statements.size(); + for (int k=m; k>=1; k--) + { + int state = (1 << k) - 1; + while (state < (1 << m)) + { + if (checkOK(state, statements)) + return k; + + int c = state & - state; + int r = state + c; + state = (((r ^ state) >> 2) / c) | r; + } + } + return 0; + } +}; From a1c4bc8a830a59dee4961f4d978613602476b09e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 16:13:24 -0800 Subject: [PATCH 0393/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7d8312dfa..5ddba53ce 100644 --- a/Readme.md +++ b/Readme.md @@ -763,6 +763,7 @@ [2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) [1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) +[2151.Maximum-Good-People-Based-on-Statements](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements) (M+) #### [Divide and Conquer](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer) From addfe5cd3342e62618a721ee66eb86432d7074fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 16:19:41 -0800 Subject: [PATCH 0394/2729] Create Readme.md --- .../2151.Maximum-Good-People-Based-on-Statements/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements/Readme.md diff --git a/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements/Readme.md b/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements/Readme.md new file mode 100644 index 000000000..ef6e01766 --- /dev/null +++ b/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements/Readme.md @@ -0,0 +1,7 @@ +### 2151.Maximum-Good-People-Based-on-Statements + +本题的人数只有n<=15,这就非常强烈地暗示了我们用二进制的bit mask来暴力枚举所有“好人”的可能组合。对于任意一种组合,我们只需要用o(n^2)的时间检查一遍。所以总的时间复杂度是```2^15*15^2=7e6```是可以接受的。 + +当我们考虑一种好人组合,如何判定它是否可行呢?我们需要注意三点:就是这些好人做出的判断不能彼此矛盾;好人认定的“好人”一定要出现在组合中;好人认定的“坏人”一定不能出现在组合中。满足这三点,那么这种好人组合就没有问题。 + +此外,本题可以用Gosper's hack,从好人多到好人少的组合依次遍历,找到合适的组合后即可提前终止。 From fed455a0bc32943e1b3bae4ec9f7f0d81550e069 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jan 2022 16:41:44 -0800 Subject: [PATCH 0395/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5ddba53ce..a7419b35f 100644 --- a/Readme.md +++ b/Readme.md @@ -762,7 +762,7 @@ [1755.Closest-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1755.Closest-Subsequence-Sum) (H) [2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) [1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) -[2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) +[2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) (M) [2151.Maximum-Good-People-Based-on-Statements](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements) (M+) From fa5a2b21044fc4a5e12994669f18efdd413d67a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Jan 2022 09:43:56 -0800 Subject: [PATCH 0396/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a7419b35f..6d60a2fd7 100644 --- a/Readme.md +++ b/Readme.md @@ -931,7 +931,6 @@ [1103.Distribute-Candies-to-People](https://github.com/wisdompeak/LeetCode/tree/master/Math/1103.Distribute-Candies-to-People) (M+) 1330.Reverse-Subarray-To-Maximize-Array-Value (TBD) [1250.Check-If-It-Is-a-Good-Array](https://github.com/wisdompeak/LeetCode/tree/master/Math/1250.Check-If-It-Is-a-Good-Array) (M+) -[1605.Find-Valid-Matrix-Given-Row-and-Column-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Math/1605.Find-Valid-Matrix-Given-Row-and-Column-Sums) (M+) [1680.Concatenation-of-Consecutive-Binary-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Math/1680.Concatenation-of-Consecutive-Binary-Numbers) (M) [1739.Building-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/Math/1739.Building-Boxes) (H-) [1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Math/1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation) (H) @@ -1107,6 +1106,7 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) [932.Beautiful-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/932.Beautiful-Array) (H) +[1605.Find-Valid-Matrix-Given-Row-and-Column-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Math/1605.Find-Valid-Matrix-Given-Row-and-Column-Sums) (H-) [2007.Find-Original-Array-From-Doubled-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2007.Find-Original-Array-From-Doubled-Array) (M) [2122.Recover-the-Original-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2122.Recover-the-Original-Array) (H-) [1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) From ba66b3ce3337567ddb7b083890c36ee5982d2bf4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Jan 2022 11:54:39 -0800 Subject: [PATCH 0397/2729] Update Readme.md --- Math/1605.Find-Valid-Matrix-Given-Row-and-Column-Sums/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Math/1605.Find-Valid-Matrix-Given-Row-and-Column-Sums/Readme.md b/Math/1605.Find-Valid-Matrix-Given-Row-and-Column-Sums/Readme.md index f764d6e7d..d423a00b4 100644 --- a/Math/1605.Find-Valid-Matrix-Given-Row-and-Column-Sums/Readme.md +++ b/Math/1605.Find-Valid-Matrix-Given-Row-and-Column-Sums/Readme.md @@ -1,5 +1,7 @@ ### 1605.Find-Valid-Matrix-Given-Row-and-Column-Sums +首先我们要知道,我们有n^2个元素要填,但是只有2n个约束(即行与列的和),所以这是一个欠定方程组,一定有无穷多个解。即使任意指定第一行的n个元素(再不违反约束的情况下),那么剩下的n^2-n个待定元素也一定会有相应合适的解。所以整体的策略是:可以任意填充第一个元素,然后更新约束,相应填充后面的元素。不断重复。 + 从一个例子入手:我们考虑一个3x3的矩阵,并且```a+b+c==x+y+z``` ``` O O O | a From 1047e1b820b512859a5499a627e5d045ce5d5ecd Mon Sep 17 00:00:00 2001 From: gma Date: Wed, 26 Jan 2022 03:02:17 -0500 Subject: [PATCH 0398/2729] implement 315 using binary indexed tree --- CMakeLists.txt | 2 +- ...15.Count-of-Smaller-Numbers-After-Self.cpp | 86 +++++++++++++++++++ tests/CMakeLists.txt | 3 +- ....Count-of-Smaller-Numbers-After-Self.t.cpp | 60 +++++++++++++ .../CMakeLists.txt | 9 ++ tests/Divide_Conquer/CMakeLists.txt | 1 + 6 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp create mode 100644 tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt create mode 100644 tests/Divide_Conquer/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 19850dfb6..fee2f7523 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.10) project(LeetCode VERSION 1.0) -set (CMAKE_CXX_STANDARD 11) +set (CMAKE_CXX_STANDARD 17) include_directories(PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp index bbeebc6a3..b780061f4 100644 --- a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp +++ b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp @@ -33,4 +33,90 @@ class Solution { // 如果写归并排序的code会更快一些。这里就偷懒了,直接用sort函数。 sort(sortedNums.begin()+start,sortedNums.begin()+end+1); } + + std::vector count_smaller_binary_indexed_tree(std::vector &nums) + { + // when iterating to index i, we want to efficiently + // know how many elements on the right are less than nums[i] + + // it may be impossible to get to know this information in O(1) + // therefore, O(logn) is the best achievement. + + // considering O(logn), there are two data structure candidates + + // binary indexed tree and segment tree + + // since, we only want to count element of which value < nums[i] + // instead of ? < value < nums[i] + + // binary indexed tree is the choice. + + if (nums.empty()) + return std::vector(); + + auto [min_it, max_it] = std::minmax_element(nums.begin(), nums.end()); + + // mapping *min_it to be 1 + int delta = 1 - *min_it; + + int min = *min_it + delta; + int max = *max_it + delta; + + // There are 2107 trees on the dota 2 map. + binary_indexed_tree tree(max); + + std::vector counts(nums.size(), 0); + + for (int i = nums.size()-1; i >= 0; --i) + { + // query how many elements are less than nums[i] + int num = nums[i] + delta; + counts[i] = tree.query(num-1); + + tree.update(num, 1); + } + + return counts; + } + +private: + struct binary_indexed_tree + { + std::vector _arr; + + binary_indexed_tree(int max_val) + : _arr(max_val+1, 0) + { + // for binary indexed tree, index 0 means nothing, + // therefore, if we want to store the information of max_val + // we need an array of which the length is equal to max_val+1 + } + + /** @brief query prefix sum of range [0, i] of internal array + * @param: i int inclusive end pos of prefix sum array + * @return: prefix sum value + **/ + int query(int i) + { + assert (i < _arr.size()); + + int ret = 0; + + for (auto j = i; j > 0; j -= lowbit(j)) + ret += _arr[j]; + + return ret; + } + + void update(int i, int val) + { + assert (i > 0); // logical error to touch array[i] + assert (i < _arr.size()); + + for (auto j = i; j < _arr.size(); j += lowbit(j)) + _arr[j] += val; + } + + int lowbit(int i) { return i & (-i); } + }; }; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2b8c1c028..5f89c1d96 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,4 +10,5 @@ FetchContent_MakeAvailable(googletest) include(GoogleTest) add_subdirectory(BFS) -add_subdirectory(Dynamic_Programming) \ No newline at end of file +add_subdirectory(Divide_Conquer) +add_subdirectory(Dynamic_Programming) diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp new file mode 100644 index 000000000..c203fcf4e --- /dev/null +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp @@ -0,0 +1,60 @@ +#include "gtest/gtest.h" +#include +#include +using namespace std; + +#include +#include + +#include // benchmark + + +#include + +TEST(count_of_smaller_numbers_after_self, consistency) +{ + Solution s; + + std::vector nums{5,2,6,1}; + std::vector expected{2,1,1,0}; + + ASSERT_EQ(s.countSmaller(nums), expected); + ASSERT_EQ(s.count_smaller_binary_indexed_tree(nums), expected); +} + +TEST(count_of_smaller_numbers_after_self, benchmark) +{ + std::vector nums(1e5, 0); + + for (auto &num: nums) + num = rand() % static_cast(2 * 1e4) - 1e4; + + Solution s; + std::vector counts1; + std::vector counts2; + + counts1.reserve(1e5); + counts2.reserve(1e5); + + { + auto start = chrono::steady_clock::now(); + counts1 = s.countSmaller(nums); + auto end = chrono::steady_clock::now(); + + printf("time cost of countSmaller using merge sort is %ld [ms]\n", + chrono::duration_cast(end - start).count()); + } + + { + auto start = chrono::steady_clock::now(); + counts2 = s.count_smaller_binary_indexed_tree(nums); + auto end = chrono::steady_clock::now(); + + printf("time cost of countSmaller using binary indexed tree is %ld [ms]\n", + chrono::duration_cast(end - start).count()); + } + + ASSERT_EQ(counts1, counts2); +} + + diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt new file mode 100644 index 000000000..68c99fec0 --- /dev/null +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt @@ -0,0 +1,9 @@ +set(BINARY count_of_smaller_numbers_after_self) + +add_executable(${BINARY} 315.Count-of-Smaller-Numbers-After-Self.t.cpp) + +target_link_libraries(${BINARY} gtest_main) + +include(GoogleTest) + +gtest_discover_tests(${BINARY}) \ No newline at end of file diff --git a/tests/Divide_Conquer/CMakeLists.txt b/tests/Divide_Conquer/CMakeLists.txt new file mode 100644 index 000000000..09860cf7d --- /dev/null +++ b/tests/Divide_Conquer/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(315.Count-of-Smaller-Numbers-After-Self) \ No newline at end of file From b02303bab3df7b6d20a607e6e50b4caa8e44fc77 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 27 Jan 2022 00:30:26 -0800 Subject: [PATCH 0399/2729] Update 310.Minimum Height Trees.cpp --- .../310.Minimum Height Trees.cpp | 70 ++++++++++--------- 1 file changed, 37 insertions(+), 33 deletions(-) diff --git a/Tree/310.Minimum-Height-Trees/310.Minimum Height Trees.cpp b/Tree/310.Minimum-Height-Trees/310.Minimum Height Trees.cpp index eea21b859..566e195a7 100644 --- a/Tree/310.Minimum-Height-Trees/310.Minimum Height Trees.cpp +++ b/Tree/310.Minimum-Height-Trees/310.Minimum Height Trees.cpp @@ -1,53 +1,57 @@ class Solution { public: - vector findMinHeightTrees(int n, vector>& edges) + vector findMinHeightTrees(int n, vector>& edges) { if (n==1) return {0}; if (n==2) return {0,1}; - - unordered_mapDegree; - unordered_map>Up; - + + vectorinDegree(n); + vector>next(n); for (auto edge:edges) { - Degree[edge.first]++; - Degree[edge.second]++; - Up[edge.second].push_back(edge.first); - Up[edge.first].push_back(edge.second); + inDegree[edge[0]]++; + inDegree[edge[1]]++; + next[edge[0]].push_back(edge[1]); + next[edge[1]].push_back(edge[0]); } queueq; - for (auto a:outDegree) - if (a.second==1) q.push(a.first); + vectorvisited(n); + for (int i=0; iresults; - while (!q.empty()) + visited[cur] = 1; + count++; + for (int nxt: next[cur]) { - results.push_back(q.front()); - q.pop(); - } - return results; - } + inDegree[nxt]--; + if (inDegree[nxt]==1) + q.push(nxt); + } + } + if (count==n-1 || count==n-2) + break; } + + vectorrets; + for (int i=0; i Date: Thu, 27 Jan 2022 00:30:47 -0800 Subject: [PATCH 0400/2729] Rename 310.Minimum Height Trees.cpp to 310.Minimum-Height-Trees.cpp --- ...{310.Minimum Height Trees.cpp => 310.Minimum-Height-Trees.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/310.Minimum-Height-Trees/{310.Minimum Height Trees.cpp => 310.Minimum-Height-Trees.cpp} (100%) diff --git a/Tree/310.Minimum-Height-Trees/310.Minimum Height Trees.cpp b/Tree/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp similarity index 100% rename from Tree/310.Minimum-Height-Trees/310.Minimum Height Trees.cpp rename to Tree/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp From 20f89240e8c4b5d30f053c208b2940b8551b70a9 Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Thu, 27 Jan 2022 00:36:06 -0800 Subject: [PATCH 0401/2729] mv 310 --- .../310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp | 0 .../310.Minimum-Height-Trees/310.Minimum-Height-Trees.py | 0 {Tree => BFS}/310.Minimum-Height-Trees/Readme.md | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {Tree => BFS}/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp (100%) rename {Tree => BFS}/310.Minimum-Height-Trees/310.Minimum-Height-Trees.py (100%) rename {Tree => BFS}/310.Minimum-Height-Trees/Readme.md (100%) diff --git a/Tree/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp b/BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp similarity index 100% rename from Tree/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp rename to BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp diff --git a/Tree/310.Minimum-Height-Trees/310.Minimum-Height-Trees.py b/BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.py similarity index 100% rename from Tree/310.Minimum-Height-Trees/310.Minimum-Height-Trees.py rename to BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.py diff --git a/Tree/310.Minimum-Height-Trees/Readme.md b/BFS/310.Minimum-Height-Trees/Readme.md similarity index 100% rename from Tree/310.Minimum-Height-Trees/Readme.md rename to BFS/310.Minimum-Height-Trees/Readme.md From ed9be62d28e8e486937ef81669990a11b8094101 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 27 Jan 2022 00:36:43 -0800 Subject: [PATCH 0402/2729] Update Readme.md --- Readme.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 6d60a2fd7..a264030d0 100644 --- a/Readme.md +++ b/Readme.md @@ -207,7 +207,6 @@ [173.Binary-Search-Tree-Iterator](https://github.com/wisdompeak/LeetCode/tree/master/Stack/173.Binary-Search-Tree-Iterator) (M) [545.Boundary-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/545.Boundary-of-Binary-Tree) (H-) [272.Closest-Binary-Search-Tree-Value-II](https://github.com/wisdompeak/LeetCode/tree/master/Tree/272.Closest-Binary-Search-Tree-Value-II) (M+) -[310.Minimum-Height-Trees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/310.Minimum-Height-Trees) (H-) [226.Invert-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/226.Invert-Binary-Tree) (M) [655.Print-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/655.Print-Binary-Tree) (M+) [897.Increasing-Order-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/897.Increasing-Order-Search-Tree) (M+) @@ -479,7 +478,7 @@ [207.Course-Schedule](https://github.com/wisdompeak/LeetCode/tree/master/BFS/207.Course-Schedule) (H-) [210.Course-Schedule-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/210.Course-Schedule-II) (M) [269.Alien-Dictionary](https://github.com/wisdompeak/LeetCode/tree/master/BFS/269.Alien-Dictionary) (H-) -[310.Minimum-Height-Trees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/310.Minimum-Height-Trees) (H-) +[310.Minimum-Height-Trees](https://github.com/wisdompeak/LeetCode/tree/master/BFS/310.Minimum-Height-Trees) (H-) [444.Sequence-Reconstruction](https://github.com/wisdompeak/LeetCode/tree/master/BFS/444.Sequence-Reconstruction) (H) [802.Find-Eventual-Safe-States](https://github.com/wisdompeak/LeetCode/tree/master/BFS/802.Find-Eventual-Safe-States) (H-) [1136.Parallel-Courses](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1136.Parallel-Courses) (M) From 2c2fef93be21d5f1506de487523742f17a28c2d0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 27 Jan 2022 23:22:20 -0800 Subject: [PATCH 0403/2729] Update 310.Minimum-Height-Trees.cpp --- .../310.Minimum-Height-Trees.cpp | 42 ++++++++++--------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp b/BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp index 566e195a7..45a2e69df 100644 --- a/BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp +++ b/BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp @@ -4,24 +4,26 @@ class Solution { { if (n==1) return {0}; if (n==2) return {0,1}; - - vectorinDegree(n); + vector>next(n); - for (auto edge:edges) + vectordegree(n); + + for (auto edge: edges) { - inDegree[edge[0]]++; - inDegree[edge[1]]++; - next[edge[0]].push_back(edge[1]); - next[edge[1]].push_back(edge[0]); + int a = edge[0], b = edge[1]; + degree[a]++; + degree[b]++; + next[a].push_back(b); + next[b].push_back(a); } queueq; vectorvisited(n); for (int i=0; irets; - for (int i=0; i Date: Fri, 28 Jan 2022 16:44:22 -0800 Subject: [PATCH 0404/2729] Create 1982.Find-Array-Given-Subset-Sums_v2.cpp --- .../1982.Find-Array-Given-Subset-Sums_v2.cpp | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Greedy/1982.Find-Array-Given-Subset-Sums/1982.Find-Array-Given-Subset-Sums_v2.cpp diff --git a/Greedy/1982.Find-Array-Given-Subset-Sums/1982.Find-Array-Given-Subset-Sums_v2.cpp b/Greedy/1982.Find-Array-Given-Subset-Sums/1982.Find-Array-Given-Subset-Sums_v2.cpp new file mode 100644 index 000000000..8d89f6281 --- /dev/null +++ b/Greedy/1982.Find-Array-Given-Subset-Sums/1982.Find-Array-Given-Subset-Sums_v2.cpp @@ -0,0 +1,98 @@ +class Solution { +public: + vector recoverArray(int n, vector& sums) + { + vectorrets; + if (dfs(sums, n, rets)) + return rets; + return {}; + } + + vectorsplit1(vector&sums, int x) + { + int k = sums.size(); + vectorvisited(k); + vectorrets; + int i = k-1, j = k-1; + for (int t=0; t=0 && visited[i]) + i--; + if (i<0) return {}; + visited[i] = 1; + + while (j>=0 && (visited[j]||sums[j]!=sums[i]-x)) + j--; + if (j<0) return {}; + visited[j] = 1; + + rets.push_back(sums[j]); + } + return rets; + } + + vectorsplit2(vector&sums, int x) + { + int k = sums.size(); + vectorvisited(k); + vectorrets; + int i = 0, j = 0; + for (int t=0; t=k) return {}; + visited[i] = 1; + + while (j=k) return {}; + visited[j] = 1; + + rets.push_back(sums[j]); + } + return rets; + } + + + bool dfs(vectorsums, int n, vector&rets) + { + if (n==1) + { + if (sums[0]!=0 && sums[1]!=0) + return false; + else + { + rets.push_back(sums[0]==0? sums[1]:sums[0]); + return true; + } + } + + int k = sums.size(); + sort(sums.begin(), sums.end()); + + // suppose x is the minimum positive number + int x = sums[k-1]-sums[k-2]; + vectorsums1 = split1(sums, x); + if (sums1.size()==k/2) + { + rets.push_back(x); + if (dfs(sums1, n-1, rets)) + return true; + rets.pop_back(); + } + + // suppose x is the maximum negative number + x = -(sums[k-1]-sums[k-2]); + vectorsums2 = split2(sums, x); + if (sums2.size()==k/2) + { + rets.push_back(x); + if (dfs(sums2, n-1, rets)) + return true; + rets.pop_back(); + } + + return false; + } +}; From b85d9e4b21e504878c148d2591e50b19460cb26e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 28 Jan 2022 16:52:41 -0800 Subject: [PATCH 0405/2729] Update Readme.md --- Greedy/1982.Find-Array-Given-Subset-Sums/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Greedy/1982.Find-Array-Given-Subset-Sums/Readme.md b/Greedy/1982.Find-Array-Given-Subset-Sums/Readme.md index 265db0cfe..4b54dc0e8 100644 --- a/Greedy/1982.Find-Array-Given-Subset-Sums/Readme.md +++ b/Greedy/1982.Find-Array-Given-Subset-Sums/Readme.md @@ -9,3 +9,10 @@ OK,我们接下来考虑数字元素有正有负的情况。我们有没有机 注意,当我们根据-x做sums的分解时,因为(-x)是负数,方法略有不同。此时sums里面的最小值a才是包含了(-x)的子集和,对应的a+x才是剔除了(-x)的子集和。所以我们需要从小到大遍历sums的元素。 递归的边界条件是当n=1时,sums里有两个元素。其中一个元素必须是0,另一个元素就是返回值(原始元素)。 + +#### 关于重构的具体方法 +根据前面的分析,我们会遇到这样一个问题。已知一系列数字{nums[i]},和该系列数字与某正数x的和{nums[i]+x},将这两者混合在一起记做arr之后,如何将原先的{nums[i]}解析出来? + +第一种方法是用multiset,每一个回合可以实时取出arr里面的最大值,它必然对应了某个nums[j]+x,于是我们就可以知道了nums[j]是谁。这样我们就可以把nums[j]和nums[j]+x都从multiset里面直接删除。然后递归处理。 + +另一种方法是用双指针。将arr排序之后从高到低遍历。对于任何一个未访问过的元素arr[i],必然对应着另一个arr[j]+x。于是我们就可以把arr[i]和arr[j]标记出来。然后再剩下的arr元素里递归处理。注意到,i与j都一定是单调递减遍历的。这个技巧和2007和2122是一样的。 From 17a0b8086cf58451cfc3a003dce41ca8014a38af Mon Sep 17 00:00:00 2001 From: gma Date: Tue, 1 Feb 2022 02:00:26 -0500 Subject: [PATCH 0406/2729] separate the solution into two implementations --- ...Count-of-Smaller-Numbers-After-Self-v2.cpp | 88 ++++++++++++++++++ ...15.Count-of-Smaller-Numbers-After-Self.cpp | 86 ----------------- ....Count-of-Smaller-Numbers-After-Self.t.cpp | 60 ------------ ...unt-of-Smaller-Numbers-After-Self.t.cpp.in | 93 +++++++++++++++++++ .../315.binary-indexed-tree.cpp | 10 ++ .../315.binary-indexed-tree.h | 12 +++ .../315.divided-conquer.cpp | 10 ++ .../315.divided-conquer.h | 12 +++ .../CMakeLists.txt | 27 +++++- 9 files changed, 250 insertions(+), 148 deletions(-) create mode 100644 Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self-v2.cpp delete mode 100644 tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp create mode 100644 tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp.in create mode 100644 tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.binary-indexed-tree.cpp create mode 100644 tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.binary-indexed-tree.h create mode 100644 tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.divided-conquer.cpp create mode 100644 tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.divided-conquer.h diff --git a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self-v2.cpp b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self-v2.cpp new file mode 100644 index 000000000..d6b10caac --- /dev/null +++ b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self-v2.cpp @@ -0,0 +1,88 @@ +class Solution { +public: + std::vector countSmaller(std::vector &nums) + { + // when iterating to index i, we want to efficiently + // know how many elements on the right are less than nums[i] + + // it may be impossible to get to know this information in O(1) + // therefore, O(logn) is the best achievement. + + // considering O(logn), there are two data structure candidates + + // binary indexed tree and segment tree + + // since, we only want to count element of which value < nums[i] + // instead of ? < value < nums[i] + + // binary indexed tree is the choice. + + if (nums.empty()) + return std::vector(); + + auto [min_it, max_it] = std::minmax_element(nums.begin(), nums.end()); + + // mapping *min_it to be 1 + int delta = 1 - *min_it; + + int min = *min_it + delta; + int max = *max_it + delta; + + // There are 2107 trees on the dota 2 map. + binary_indexed_tree tree(max); + + std::vector counts(nums.size(), 0); + + for (int i = nums.size()-1; i >= 0; --i) + { + // query how many elements are less than nums[i] + int num = nums[i] + delta; + counts[i] = tree.query(num-1); + + tree.update(num, 1); + } + + return counts; + } + +private: + struct binary_indexed_tree + { + std::vector _arr; + + binary_indexed_tree(int max_val) + : _arr(max_val+1, 0) + { + // for binary indexed tree, index 0 means nothing, + // therefore, if we want to store the information of max_val + // we need an array of which the length is equal to max_val+1 + } + + /** @brief query prefix sum of range [0, i] of internal array + * @param: i int inclusive end pos of prefix sum array + * @return: prefix sum value + **/ + int query(int i) + { + assert (i < _arr.size()); + + int ret = 0; + + for (auto j = i; j > 0; j -= lowbit(j)) + ret += _arr[j]; + + return ret; + } + + void update(int i, int val) + { + assert (i > 0); // logical error to touch array[i] + assert (i < _arr.size()); + + for (auto j = i; j < _arr.size(); j += lowbit(j)) + _arr[j] += val; + } + + int lowbit(int i) { return i & (-i); } + }; +}; diff --git a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp index b780061f4..bbeebc6a3 100644 --- a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp +++ b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp @@ -33,90 +33,4 @@ class Solution { // 如果写归并排序的code会更快一些。这里就偷懒了,直接用sort函数。 sort(sortedNums.begin()+start,sortedNums.begin()+end+1); } - - std::vector count_smaller_binary_indexed_tree(std::vector &nums) - { - // when iterating to index i, we want to efficiently - // know how many elements on the right are less than nums[i] - - // it may be impossible to get to know this information in O(1) - // therefore, O(logn) is the best achievement. - - // considering O(logn), there are two data structure candidates - - // binary indexed tree and segment tree - - // since, we only want to count element of which value < nums[i] - // instead of ? < value < nums[i] - - // binary indexed tree is the choice. - - if (nums.empty()) - return std::vector(); - - auto [min_it, max_it] = std::minmax_element(nums.begin(), nums.end()); - - // mapping *min_it to be 1 - int delta = 1 - *min_it; - - int min = *min_it + delta; - int max = *max_it + delta; - - // There are 2107 trees on the dota 2 map. - binary_indexed_tree tree(max); - - std::vector counts(nums.size(), 0); - - for (int i = nums.size()-1; i >= 0; --i) - { - // query how many elements are less than nums[i] - int num = nums[i] + delta; - counts[i] = tree.query(num-1); - - tree.update(num, 1); - } - - return counts; - } - -private: - struct binary_indexed_tree - { - std::vector _arr; - - binary_indexed_tree(int max_val) - : _arr(max_val+1, 0) - { - // for binary indexed tree, index 0 means nothing, - // therefore, if we want to store the information of max_val - // we need an array of which the length is equal to max_val+1 - } - - /** @brief query prefix sum of range [0, i] of internal array - * @param: i int inclusive end pos of prefix sum array - * @return: prefix sum value - **/ - int query(int i) - { - assert (i < _arr.size()); - - int ret = 0; - - for (auto j = i; j > 0; j -= lowbit(j)) - ret += _arr[j]; - - return ret; - } - - void update(int i, int val) - { - assert (i > 0); // logical error to touch array[i] - assert (i < _arr.size()); - - for (auto j = i; j < _arr.size(); j += lowbit(j)) - _arr[j] += val; - } - - int lowbit(int i) { return i & (-i); } - }; }; diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp deleted file mode 100644 index c203fcf4e..000000000 --- a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "gtest/gtest.h" -#include -#include -using namespace std; - -#include -#include - -#include // benchmark - - -#include - -TEST(count_of_smaller_numbers_after_self, consistency) -{ - Solution s; - - std::vector nums{5,2,6,1}; - std::vector expected{2,1,1,0}; - - ASSERT_EQ(s.countSmaller(nums), expected); - ASSERT_EQ(s.count_smaller_binary_indexed_tree(nums), expected); -} - -TEST(count_of_smaller_numbers_after_self, benchmark) -{ - std::vector nums(1e5, 0); - - for (auto &num: nums) - num = rand() % static_cast(2 * 1e4) - 1e4; - - Solution s; - std::vector counts1; - std::vector counts2; - - counts1.reserve(1e5); - counts2.reserve(1e5); - - { - auto start = chrono::steady_clock::now(); - counts1 = s.countSmaller(nums); - auto end = chrono::steady_clock::now(); - - printf("time cost of countSmaller using merge sort is %ld [ms]\n", - chrono::duration_cast(end - start).count()); - } - - { - auto start = chrono::steady_clock::now(); - counts2 = s.count_smaller_binary_indexed_tree(nums); - auto end = chrono::steady_clock::now(); - - printf("time cost of countSmaller using binary indexed tree is %ld [ms]\n", - chrono::duration_cast(end - start).count()); - } - - ASSERT_EQ(counts1, counts2); -} - - diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp.in b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp.in new file mode 100644 index 000000000..35dfcc7ee --- /dev/null +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.t.cpp.in @@ -0,0 +1,93 @@ +#include "gtest/gtest.h" +#include +#include +using namespace std; + +#include +#include + +#include // benchmark + +#include <315.binary-indexed-tree.h> +#include <315.divided-conquer.h> + +#include // atexit +#include +#include +#include +#include + + +static std::vector + count_of_smaller_numbers_after_self_dc(std::vector &nums) +{ + static void * handle = dlopen("@DC_315_SO@", RTLD_LAZY); + assert (handle); + + static auto counter = + (std::vector (*)(std::vector &))dlsym(handle, "count_v1"); + + // handle keep alive, no need to release + + return counter(nums); +} + +static std::vector + count_of_smaller_numbers_after_self_bit(std::vector &nums) +{ + static void * handle = dlopen("@BIT_315_SO@", RTLD_LAZY); + + assert (handle); + + static auto counter = + (std::vector (*)(std::vector &))dlsym(handle, "count_v2"); + + // handle keep alive, no need to release + + return counter(nums); +} + +TEST(count_of_smaller_numbers_after_self, consistency) +{ + std::vector nums{5,2,6,1}; + std::vector expected{2,1,1,0}; + + ASSERT_EQ(count_of_smaller_numbers_after_self_dc(nums), expected); + ASSERT_EQ(count_of_smaller_numbers_after_self_bit(nums), expected); +} + +TEST(count_of_smaller_numbers_after_self, benchmark) +{ + std::vector nums(1e5, 0); + + for (auto &num: nums) + num = rand() % static_cast(2 * 1e4) - 1e4; + + std::vector counts1; + std::vector counts2; + + counts1.reserve(1e5); + counts2.reserve(1e5); + + { + auto start = chrono::steady_clock::now(); + counts1 = count_of_smaller_numbers_after_self_dc(nums); + auto end = chrono::steady_clock::now(); + + printf("time cost of countSmaller using merge sort is %ld [ms]\n", + chrono::duration_cast(end - start).count()); + } + + { + auto start = chrono::steady_clock::now(); + counts2 = count_of_smaller_numbers_after_self_bit(nums); + auto end = chrono::steady_clock::now(); + + printf("time cost of countSmaller using binary indexed tree is %ld [ms]\n", + chrono::duration_cast(end - start).count()); + } + + ASSERT_EQ(counts1, counts2); +} + + diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.binary-indexed-tree.cpp b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.binary-indexed-tree.cpp new file mode 100644 index 000000000..63fffc3f0 --- /dev/null +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.binary-indexed-tree.cpp @@ -0,0 +1,10 @@ +#include <315.binary-indexed-tree.h> +#include + +#include + +std::vector count_v2(std::vector &nums) +{ + static Solution s; + return s.countSmaller(nums); +} \ No newline at end of file diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.binary-indexed-tree.h b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.binary-indexed-tree.h new file mode 100644 index 000000000..caa34acbc --- /dev/null +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.binary-indexed-tree.h @@ -0,0 +1,12 @@ +#ifndef TESTS_DIVIDE_CONQUER_315_BINARY_INDEXED_TREE +#define TESTS_DIVIDE_CONQUER_315_BINARY_INDEXED_TREE + +#include +#include +using namespace std; +#include + +// binary indexed tree +extern "C" { std::vector count_v2(std::vector &nums); } + +#endif \ No newline at end of file diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.divided-conquer.cpp b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.divided-conquer.cpp new file mode 100644 index 000000000..4482d806e --- /dev/null +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.divided-conquer.cpp @@ -0,0 +1,10 @@ +#include <315.divided-conquer.h> +#include + +#include + +std::vector count_v1(std::vector &nums) +{ + static Solution s; + return s.countSmaller(nums); +} \ No newline at end of file diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.divided-conquer.h b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.divided-conquer.h new file mode 100644 index 000000000..3133174a1 --- /dev/null +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.divided-conquer.h @@ -0,0 +1,12 @@ +#ifndef TESTS_DIVIDE_CONQUER_315_DIVIDE_CONQUER +#define TESTS_DIVIDE_CONQUER_315_DIVIDE_CONQUER + +#include +#include +using namespace std; +#include + +// divided conquer +extern "C" { std::vector count_v1(std::vector &nums); } + +#endif \ No newline at end of file diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt index 68c99fec0..e363020d7 100644 --- a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt @@ -1,8 +1,31 @@ set(BINARY count_of_smaller_numbers_after_self) -add_executable(${BINARY} 315.Count-of-Smaller-Numbers-After-Self.t.cpp) +# binary indexed tree solution +add_library(divided_conquer_315 SHARED 315.divided-conquer.cpp) +target_include_directories(divided_conquer_315 PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}) -target_link_libraries(${BINARY} gtest_main) +# divided conquer solution +add_library(binary_indexed_tree_315 SHARED 315.binary-indexed-tree.cpp) +target_include_directories(binary_indexed_tree_315 PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}) + +# configure file for compilation +set(BIT_315_SO ${CMAKE_CURRENT_BINARY_DIR}/libbinary_indexed_tree_315.so) +set(DC_315_SO ${CMAKE_CURRENT_BINARY_DIR}/libdivided_conquer_315.so) + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/315.Count-of-Smaller-Numbers-After-Self.t.cpp.in + ${CMAKE_CURRENT_BINARY_DIR}/315.Count-of-Smaller-Numbers-After-Self.t.cpp) + +set(SRC_FILE + ${CMAKE_CURRENT_BINARY_DIR}/315.Count-of-Smaller-Numbers-After-Self.t.cpp) + +# main test +add_executable(${BINARY} ${SRC_FILE}) + +target_link_libraries(${BINARY} gtest_main dl) +target_include_directories(${BINARY} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) include(GoogleTest) From 0672db7e3cc3fe32de21a9f2b0c4729d3ccb227e Mon Sep 17 00:00:00 2001 From: gma Date: Tue, 1 Feb 2022 02:04:13 -0500 Subject: [PATCH 0407/2729] typo in cmake comments --- .../315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt index e363020d7..80ecc3c54 100644 --- a/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt +++ b/tests/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/CMakeLists.txt @@ -1,11 +1,11 @@ set(BINARY count_of_smaller_numbers_after_self) -# binary indexed tree solution +# divided conquer solution add_library(divided_conquer_315 SHARED 315.divided-conquer.cpp) target_include_directories(divided_conquer_315 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -# divided conquer solution +# binary indexed tree solution add_library(binary_indexed_tree_315 SHARED 315.binary-indexed-tree.cpp) target_include_directories(binary_indexed_tree_315 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) From 026b0f4066217d0fd0f45ef16372a17e36b5b190 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 31 Jan 2022 23:44:38 -0800 Subject: [PATCH 0408/2729] Create 2156.Find-Substring-With-Given-Hash-Value.cpp --- ...6.Find-Substring-With-Given-Hash-Value.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 String/2156.Find-Substring-With-Given-Hash-Value/2156.Find-Substring-With-Given-Hash-Value.cpp diff --git a/String/2156.Find-Substring-With-Given-Hash-Value/2156.Find-Substring-With-Given-Hash-Value.cpp b/String/2156.Find-Substring-With-Given-Hash-Value/2156.Find-Substring-With-Given-Hash-Value.cpp new file mode 100644 index 000000000..b80c83828 --- /dev/null +++ b/String/2156.Find-Substring-With-Given-Hash-Value/2156.Find-Substring-With-Given-Hash-Value.cpp @@ -0,0 +1,31 @@ +using LL = long long; +class Solution { +public: + string subStrHash(string s, int power, int modulo, int k, int hashValue) + { + int n = s.size(); + LL sum = 0, M = modulo; + + LL pk = 1; + for (int i=0; i=0; i--) + { + if (i+k Date: Mon, 31 Jan 2022 23:45:09 -0800 Subject: [PATCH 0409/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a264030d0..b3e7f3902 100644 --- a/Readme.md +++ b/Readme.md @@ -800,6 +800,7 @@ [1554.Strings-Differ-by-One-Character](https://github.com/wisdompeak/LeetCode/tree/master/String/1554.Strings-Differ-by-One-Character) (H) [1698.Number-of-Distinct-Substrings-in-a-String](https://github.com/wisdompeak/LeetCode/tree/master/String/1698.Number-of-Distinct-Substrings-in-a-String) (H-) [1923.Longest-Common-Subpath](https://github.com/wisdompeak/LeetCode/tree/master/String/1923.Longest-Common-Subpath) (H) +[2156.Find-Substring-With-Given-Hash-Value](https://github.com/wisdompeak/LeetCode/tree/master/String/2156.Find-Substring-With-Given-Hash-Value) (M) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) From b3289366cb4f24bf514e2045ea5bf4ca531fc3e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 1 Feb 2022 00:47:27 -0800 Subject: [PATCH 0410/2729] Create Readme.md --- String/2156.Find-Substring-With-Given-Hash-Value/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 String/2156.Find-Substring-With-Given-Hash-Value/Readme.md diff --git a/String/2156.Find-Substring-With-Given-Hash-Value/Readme.md b/String/2156.Find-Substring-With-Given-Hash-Value/Readme.md new file mode 100644 index 000000000..723347f6d --- /dev/null +++ b/String/2156.Find-Substring-With-Given-Hash-Value/Readme.md @@ -0,0 +1,7 @@ +### 2156.Find-Substring-With-Given-Hash-Value + +这是一道Rolling Hash的裸题,就是将一个字符串转化为26进制的整数。注意到Hash的高位在右边,所以我们需要从右往左进行滑窗滚定。 + +每个回合里,先砍掉原先的最高位乘以26^(k-1),然后整体乘上26,再加上新引入的最低位。 + +由于涉及到减法,可能会产生负数,所以每次取模时采用```(x+M)%M```的方式更为稳妥。 From 29d36c837a21c9a0c4e2fd2c3171dcab12799de1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 2 Feb 2022 21:53:06 -0800 Subject: [PATCH 0411/2729] Create 2157.Groups-of-Strings.cpp --- .../2157.Groups-of-Strings.cpp | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Union_Find/2157.Groups-of-Strings/2157.Groups-of-Strings.cpp diff --git a/Union_Find/2157.Groups-of-Strings/2157.Groups-of-Strings.cpp b/Union_Find/2157.Groups-of-Strings/2157.Groups-of-Strings.cpp new file mode 100644 index 000000000..606f382fc --- /dev/null +++ b/Union_Find/2157.Groups-of-Strings/2157.Groups-of-Strings.cpp @@ -0,0 +1,74 @@ +class Solution { + int Father[20000]; + int states[20000]; + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (x groupStrings(vector& words) + { + int n = words.size(); + for (int i=0; iMap; // num -> idx + for (int i=0; i>j)&1)==0) continue; + int newState = states[i] - (1<group; + for (int i=0; i Date: Wed, 2 Feb 2022 22:39:16 -0800 Subject: [PATCH 0412/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b3e7f3902..51c0c17a7 100644 --- a/Readme.md +++ b/Readme.md @@ -844,6 +844,7 @@ [1970.Last-Day-Where-You-Can-Still-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1970.Last-Day-Where-You-Can-Still-Cross) (H-) [2076.Process-Restricted-Friend-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2076.Process-Restricted-Friend-Requests) (H-) [2092.Find-All-People-With-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2092.Find-All-People-With-Secret) (H-) +[2157.Groups-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2157.Groups-of-Strings) (H) * ``Prime Factors`` [952.Largest-Component-Size-by-Common-Factor](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/952.Largest-Component-Size-by-Common-Factor) (H) [1627.Graph-Connectivity-With-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1627.Graph-Connectivity-With-Threshold) (M+) From 42bf3c366fe7b053b806246e5b41893200ed0ec0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 2 Feb 2022 23:06:54 -0800 Subject: [PATCH 0413/2729] Create Readme.md --- Union_Find/2157.Groups-of-Strings/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Union_Find/2157.Groups-of-Strings/Readme.md diff --git a/Union_Find/2157.Groups-of-Strings/Readme.md b/Union_Find/2157.Groups-of-Strings/Readme.md new file mode 100644 index 000000000..464b324de --- /dev/null +++ b/Union_Find/2157.Groups-of-Strings/Readme.md @@ -0,0 +1,15 @@ +### 2157.Groups-of-Strings + +本题明显是Union Find。暴力的方法就是将每个单词两两进行比较,如果满足三个条件之一,就可以将它们Union。判定的时候可以将字母集合用bit mask来表示,这样更方便。比如集合A添加一个字母等于B,就可以写成判断是否存在j,使得```A+(1< Date: Wed, 2 Feb 2022 23:11:04 -0800 Subject: [PATCH 0414/2729] Update Readme.md --- Union_Find/2157.Groups-of-Strings/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Union_Find/2157.Groups-of-Strings/Readme.md b/Union_Find/2157.Groups-of-Strings/Readme.md index 464b324de..c7b756008 100644 --- a/Union_Find/2157.Groups-of-Strings/Readme.md +++ b/Union_Find/2157.Groups-of-Strings/Readme.md @@ -2,9 +2,9 @@ 本题明显是Union Find。暴力的方法就是将每个单词两两进行比较,如果满足三个条件之一,就可以将它们Union。判定的时候可以将字母集合用bit mask来表示,这样更方便。比如集合A添加一个字母等于B,就可以写成判断是否存在j,使得```A+(1< Date: Wed, 2 Feb 2022 23:13:06 -0800 Subject: [PATCH 0415/2729] Update Readme.md --- Union_Find/2157.Groups-of-Strings/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Union_Find/2157.Groups-of-Strings/Readme.md b/Union_Find/2157.Groups-of-Strings/Readme.md index c7b756008..23ea88afd 100644 --- a/Union_Find/2157.Groups-of-Strings/Readme.md +++ b/Union_Find/2157.Groups-of-Strings/Readme.md @@ -6,10 +6,10 @@ 但是本题有还有更好的```o(N*26)```的算法。事实上,本题中三个条件,其中第一个条件和第二个条件显然是等价的。我们依然可以用上述的方法,循环26次将每个单词的编码A扣掉一个1 bit得到B,将i与家族B的代表进行Union即可。 -而第三个条件,本质也是如此。假设任意单词word[i]的编码A任意去掉一个字母,等于单词word[j]的编码B任意去掉一个字母,那么根据题意,i和j必须Union。那么这就意味着,我们将编码A的家族与它任意去掉一个字母后的编码A'家族进行Union,其他单词也做类似的操作,就可以将满足条件三的任意一对单词必然会被Union起来。 +而第三个条件,本质也是如此。假设任意单词word[i]的编码A任意去掉一个字母,等于单词word[j]的编码C任意去掉一个字母,那么根据题意,i和j必须Union。那么这就意味着,我们将编码A的家族与它任意去掉一个字母后的编码B家族进行Union,其他单词也做类似的操作,就可以将满足条件三的任意一对单词必然会被Union起来。 所以本题的算法如下: 1. 将每个单词i翻译成编码A,将i与编码A的家族进行Union。 -2. 将每个单词i的编码A,任意去掉一个字母变成编码A',将编码A的家族与A'的家族进行Union +2. 将每个单词i的编码A,任意去掉一个字母变成编码B,将编码A的家族与B家族进行Union 满足以上操作之后,所有需要Union的单词一定已经做了归并。我们根据每个家族的族长进行分组统计,得到家族的数量和最大的家族。 From 61d51dc617d2cf7f91a507b3fac43a9681ceb79e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 3 Feb 2022 11:31:44 -0800 Subject: [PATCH 0416/2729] Create 2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp --- ...imum-Cost-to-Reach-City-With-Discounts.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp diff --git a/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp b/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp new file mode 100644 index 000000000..ed2e5eaf3 --- /dev/null +++ b/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp @@ -0,0 +1,41 @@ +using PII = pair; +using AI3 = array; +class Solution { +public: + int minimumCost(int n, vector>& highways, int discounts) + { + vector>next(n); + for (auto x: highways) + { + next[x[0]].push_back({x[1], x[2]}); + next[x[1]].push_back({x[0], x[2]}); + } + + vector>dist(n, vector(discounts+1, INT_MAX)); + + priority_queue, greater<>>pq; + pq.push({0,0,discounts}); // {dist, node, discounts} + + while (!pq.empty()) + { + auto [d, curNode, times] = pq.top(); + pq.pop(); + + if (d >= dist[curNode][times]) continue; + dist[curNode][times] = d; + if (curNode==n-1) return d; + + for (auto nxt: next[curNode]) + { + auto [nxtNode, len] = nxt; + if (dist[nxtNode][times]!=INT_MAX) continue; + pq.push({d+len, nxtNode, times}); + if (times>=1) + pq.push({d+len/2, nxtNode, times-1}); + } + } + + return -1; + + } +}; From 05dc112157154949053ea6316270ca05cce6b6f1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 3 Feb 2022 11:32:18 -0800 Subject: [PATCH 0417/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 51c0c17a7..ee1aba1f5 100644 --- a/Readme.md +++ b/Readme.md @@ -504,6 +504,7 @@ [1786.Number-of-Restricted-Paths-From-First-to-Last-Node](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1786.Number-of-Restricted-Paths-From-First-to-Last-Node) (H-) [1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (H-) +[2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) #### [Trie](https://github.com/wisdompeak/LeetCode/tree/master/Trie) [208.Implement-Trie--Prefix-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Trie/208.Implement-Trie--Prefix-Tree) (M+) From 039b9ca869069ad2ccab108948873c9ce1ab2796 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 3 Feb 2022 11:47:24 -0800 Subject: [PATCH 0418/2729] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/Readme.md diff --git a/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/Readme.md b/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/Readme.md new file mode 100644 index 000000000..55a6f3f28 --- /dev/null +++ b/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/Readme.md @@ -0,0 +1,14 @@ +### 2093.Minimum-Cost-to-Reach-City-With-Discounts + +本题看上去就像最短路径问题。难点在于,我们在某个位置时,无法知道当前使用折扣的权利是否为最优方案。因此本题的“图”的节点定义应该设计为二元参数 {node, discountsLeft}。在用Dijsktra遍历图的过程中,即使多次来到相同的位置,但是剩余折扣次数的不同的话,应当视为不同的“状态”。所以我们记录答案的数据应该是为二位的:dist[node][discounts]。 + +在PQ里弹出当前的{curNode, discountsLeft}后,可以扩展加入PQ的“状态”包括两部分,“使用折扣权利”或者“不使用”: +```cpp +for (auto nxt: next[curNode]) +{ + auto [nxtNode, len] = nxt; + pq.push(curDist+len, nxtNode, discountsLeft); + if (discountsLeft >= 1) + pq.push(curDist+len/2, nxtNode, discountsLeft-1); +} +``` From 383b806111018026f0efd12cd0d9fdcb225fe935 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 3 Feb 2022 14:29:24 -0800 Subject: [PATCH 0419/2729] Update Readme.md --- Others/2132.Stamping-the-Grid/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2132.Stamping-the-Grid/Readme.md b/Others/2132.Stamping-the-Grid/Readme.md index efbbeb62b..17d621dd4 100644 --- a/Others/2132.Stamping-the-Grid/Readme.md +++ b/Others/2132.Stamping-the-Grid/Readme.md @@ -25,6 +25,6 @@ for (int i=0; i Date: Thu, 3 Feb 2022 22:59:25 -0800 Subject: [PATCH 0420/2729] Create 2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum.cpp --- ...ce-of-Size-K-With-the-Largest-Even-Sum.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum.cpp diff --git a/Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum.cpp b/Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum.cpp new file mode 100644 index 000000000..b1b7e7bac --- /dev/null +++ b/Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { +public: + long long largestEvenSum(vector& nums, int k) + { + vectorodd; + vectoreven; + for (int x: nums) + { + if (x%2==0) even.push_back(x); + if (x%2==1) odd.push_back(x); + } + sort(odd.rbegin(), odd.rend()); + sort(even.rbegin(), even.rend()); + + int m = odd.size(); + vectorprefix1(m+1); + for (int i=1; i<=m; i++) + prefix1[i] = prefix1[i-1] + odd[i-1]; + + int n = even.size(); + vectorprefix2(n+1); + for (int i=1; i<=n; i++) + prefix2[i] = prefix2[i-1] + even[i-1]; + + LL ret = -1; + int j = even.size(); + for (int i=0; i<=min(k, (int)odd.size()); i++) + { + while (i+j>k) j--; + if (j<0) break; + if (i+j==k && (prefix1[i]+prefix2[j])%2==0) + ret = max(ret, prefix1[i]+prefix2[j]); + } + + return ret; + } +}; From 6cdb7232087344c5eb17f24f195e549d4aecc616 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 3 Feb 2022 22:59:47 -0800 Subject: [PATCH 0421/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ee1aba1f5..61ecfce0f 100644 --- a/Readme.md +++ b/Readme.md @@ -56,6 +56,7 @@ [1577.Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1577.Number-of-Ways-Where-Square-of-Number-Is-Equal-to-Product-of-Two-Numbers) (H-) [1775.Equal-Sum-Arrays-With-Minimum-Number-of-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1775.Equal-Sum-Arrays-With-Minimum-Number-of-Operations) (M+) [1868.Product-of-Two-Run-Length-Encoded-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1868.Product-of-Two-Run-Length-Encoded-Arrays) (M+) +[2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum) (M+) #### [Binary Search](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) From 24c622b710b332b84beee7614b64ffb9b51685c1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 3 Feb 2022 23:11:52 -0800 Subject: [PATCH 0422/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum/Readme.md diff --git a/Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum/Readme.md b/Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum/Readme.md new file mode 100644 index 000000000..ef3518d7c --- /dev/null +++ b/Two_Pointers/2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum/Readme.md @@ -0,0 +1,5 @@ +### 2098.Subsequence-of-Size-K-With-the-Largest-Even-Sum + +本题的解法有很多。但想写得简洁不容易。比较优秀的切入角度是将nums分成奇数组和偶数组,各自从大到小排序。显然,如果奇数取0个,那么偶数就取前k个;如果奇数取前1个,那么偶数就取前k-1个...于是只要两个指针(i,j),i在奇数组从前往后移动,j在偶数组从后往前移动,用k次找出最大的presum1+presum2. + +需要注意的有两点。首先,不是每一种(i,j)组合得到的presum1+presum2都是偶数,我们肯定会舍弃掉不合条件的组合。其次,偶数组不见得有k个元素,指针移动的过程中需要时刻检查i+j是否等于k。 From b89b0a4ea198a415697e6d57d916c3a40bd2d4f4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 4 Feb 2022 00:27:41 -0800 Subject: [PATCH 0423/2729] Create 068.Text-Justification.cpp --- .../068.Text-Justification.cpp | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 String/068.Text-Justification/068.Text-Justification.cpp diff --git a/String/068.Text-Justification/068.Text-Justification.cpp b/String/068.Text-Justification/068.Text-Justification.cpp new file mode 100644 index 000000000..bcdf1ef56 --- /dev/null +++ b/String/068.Text-Justification/068.Text-Justification.cpp @@ -0,0 +1,74 @@ +class Solution { +public: + vector fullJustify(vector& words, int maxWidth) + { + vectorrets; + + for (int i=0; i maxWidth) + { + count -= 1 + words[j].size(); + j--; + } + + if (j==words.size()-1) + { + string temp; + for (int k=i; k<=j; k++) + temp += words[k]+" "; + temp.pop_back(); + temp += addspace(maxWidth - temp.size()); + rets.push_back(temp); + } + else + { + rets.push_back(printline(words, i, j, maxWidth)); + } + + i = j; + } + return rets; + } + + string printline(vector&words, int a, int b, int maxWidth) + { + if (a==b) + { + return words[a] + addspace(maxWidth-words[a].size()); + } + + int total = 0; + for (int i=a; i<=b; i++) total += words[i].size(); + int space = (maxWidth - total)/max(1, b-a); + int extra = maxWidth - total - space * (b-a); + + string ret; + for (int i=a; i Date: Fri, 4 Feb 2022 00:28:55 -0800 Subject: [PATCH 0424/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 61ecfce0f..bd067777d 100644 --- a/Readme.md +++ b/Readme.md @@ -775,6 +775,7 @@ #### [String](https://github.com/wisdompeak/LeetCode/tree/master/String) [006.ZigZag-Conversion](https://github.com/wisdompeak/LeetCode/tree/master/String/006.ZigZag-Conversion) (M+) +[068.Text-Justification](https://github.com/wisdompeak/LeetCode/tree/master/String/068.Text-Justification) (H) [336.Palindrome-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/String/336.Palindrome-Pairs) (H-) [388.Longest-Absolute-File-Path](https://github.com/wisdompeak/LeetCode/tree/master/String/388.Longest-Absolute-File-Path) (M+) [418.Sentence-Screen-Fitting](https://github.com/wisdompeak/LeetCode/tree/master/String/418.Sentence-Screen-Fitting) (M+) From 343de5e99e3d0e2704be0a32cc6f761aad5bd3d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 4 Feb 2022 00:49:07 -0800 Subject: [PATCH 0425/2729] Create Readme.md --- String/068.Text-Justification/Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 String/068.Text-Justification/Readme.md diff --git a/String/068.Text-Justification/Readme.md b/String/068.Text-Justification/Readme.md new file mode 100644 index 000000000..c0b46d2e0 --- /dev/null +++ b/String/068.Text-Justification/Readme.md @@ -0,0 +1,14 @@ +### 068.Text-Justification + +这是一道比较复杂的模拟题,需要耐心地做。 + +首先我们要做的是找出每一行需要打印多少单词。假设某行开始,我们需要从words[i]开始打印直到到words[j]为止,确定这个[i:j]的区间需要满足的条件是:words[i:j]的字符长度加上(j-i)个空格,必须恰好小于等于maxWidth。然后我们就可以调用一个自定义的printLine的函数来控制如何在maxWidth里面打印这么多单词。唯一例外的是,如果发现j是最后一个单词,那么需要特殊处理一下,空格不需要在单词之间平均分布。 + +接下来我们写函数```string printLine(i,j)```. 我们需要先计算空格总数```m = maxWidth - words[i:j]的长度和```,试图均分给(j-i)个间隙,可以得到基础间隙大小是```s = m/(j-i)```. 此时我们可能存留有```k = m-s*(j-i)```个空格需要分配,根据规则这些空格会给前k个间隙的位置上每个加1. 代码大致是 +```cpp + for (int i=a; i Date: Fri, 4 Feb 2022 00:50:18 -0800 Subject: [PATCH 0426/2729] Update Readme.md --- String/068.Text-Justification/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/068.Text-Justification/Readme.md b/String/068.Text-Justification/Readme.md index c0b46d2e0..78cb8bd79 100644 --- a/String/068.Text-Justification/Readme.md +++ b/String/068.Text-Justification/Readme.md @@ -2,7 +2,7 @@ 这是一道比较复杂的模拟题,需要耐心地做。 -首先我们要做的是找出每一行需要打印多少单词。假设某行开始,我们需要从words[i]开始打印直到到words[j]为止,确定这个[i:j]的区间需要满足的条件是:words[i:j]的字符长度加上(j-i)个空格,必须恰好小于等于maxWidth。然后我们就可以调用一个自定义的printLine的函数来控制如何在maxWidth里面打印这么多单词。唯一例外的是,如果发现j是最后一个单词,那么需要特殊处理一下,空格不需要在单词之间平均分布。 +首先我们要做的是找出每一行需要打印多少单词。假设某行开始,我们需要从words[i]开始打印直到到words[j]为止,确定这个[i:j]的区间需要满足的条件是:words[i:j]的字符长度加上(j-i)个空格,必须恰好小于等于maxWidth。然后我们就可以调用一个自定义的```printLine```的函数来控制如何在maxWidth里面打印这么多单词。唯一例外的是,如果发现j是最后一个单词,那么需要特殊处理一下,空格不需要在单词之间平均分布。 接下来我们写函数```string printLine(i,j)```. 我们需要先计算空格总数```m = maxWidth - words[i:j]的长度和```,试图均分给(j-i)个间隙,可以得到基础间隙大小是```s = m/(j-i)```. 此时我们可能存留有```k = m-s*(j-i)```个空格需要分配,根据规则这些空格会给前k个间隙的位置上每个加1. 代码大致是 ```cpp From 4ad17abbbbae4c05e4e65d471a0038482cd4a1d4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 4 Feb 2022 22:28:26 -0800 Subject: [PATCH 0427/2729] Create 2143.Choose-Numbers-From-Two-Arrays-in-Range.cpp --- ...hoose-Numbers-From-Two-Arrays-in-Range.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range/2143.Choose-Numbers-From-Two-Arrays-in-Range.cpp diff --git a/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range/2143.Choose-Numbers-From-Two-Arrays-in-Range.cpp b/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range/2143.Choose-Numbers-From-Two-Arrays-in-Range.cpp new file mode 100644 index 000000000..df354eed7 --- /dev/null +++ b/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range/2143.Choose-Numbers-From-Two-Arrays-in-Range.cpp @@ -0,0 +1,47 @@ +using LL = long long; +class Solution { + LL dp[105][20005]; + LL offset = 10000; + LL M = 1e9+7; +public: + int countSubranges(vector& nums1, vector& nums2) + { + int n = nums1.size(); + nums1.insert(nums1.begin(), 0); + nums2.insert(nums2.begin(), 0); + + dp[1][0+offset] = 0; + LL ret = 0; + + for (int i=1; i<=n; i++) + { + dp[i][offset+nums1[i]] += 1; + dp[i][offset-nums2[i]] += 1; + + for (int sum = -offset; sum <= offset; sum++) + { + if (inbound(sum-nums1[i])) + { + dp[i][sum+offset] += dp[i-1][sum+offset-nums1[i]]; + dp[i][sum+offset] %= M; + } + + if (inbound(sum+nums2[i])) + { + dp[i][sum+offset] += dp[i-1][sum+offset+nums2[i]]; + dp[i][sum+offset] %= M; + } + } + + ret += dp[i][0+offset]; + ret %= M; + } + + return ret; + } + + bool inbound(int x) + { + return x>=-offset && x<=offset; + } +}; From bed8a3897b6c95ffc0d0ea1090a21ea80e6d8562 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 4 Feb 2022 22:29:20 -0800 Subject: [PATCH 0428/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bd067777d..0d09ed57f 100644 --- a/Readme.md +++ b/Readme.md @@ -615,6 +615,7 @@ [1839.Longest-Substring-Of-All-Vowels-in-Order](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1839.Longest-Substring-Of-All-Vowels-in-Order) (M) [1883.Minimum-Skips-to-Arrive-at-Meeting-On-Time](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1883.Minimum-Skips-to-Arrive-at-Meeting-On-Time) (H) [2036.Maximum-Alternating-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum) (M+) +[2143.Choose-Numbers-From-Two-Arrays-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range) (H) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From 397a9437c5a345d9d5d0e57a0e12195eb3bf287a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 4 Feb 2022 22:57:45 -0800 Subject: [PATCH 0429/2729] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range/Readme.md diff --git a/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range/Readme.md b/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range/Readme.md new file mode 100644 index 000000000..aade55e43 --- /dev/null +++ b/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range/Readme.md @@ -0,0 +1,14 @@ +### 2143.Choose-Numbers-From-Two-Arrays-in-Range + +为了方便,我们将两个数组看成一个数组。我们定义```diff[i] = nums1[i]-nums2[i]```,那么对于第i个位置,如果选择num1的元素,可以认为是加上diff,如果选择nums2的元素,可以认为是减去diff。本题就是要找子区间个数,使得子区间的的元素之和是0。 + +因为目标0是多个元素累加起来的和,所以我们必然会需要考虑元素累加过程中出现的各种可能的“和”。所以,我们需要定义状态dp[i][sum],表示以i为结尾、区间和是sum的子区间的个数。显然,因为对于元素i我们只有两种策略(加上diff或者减去diff),所以d[i][sum]必然依赖于i-1处的两个前趋状态,即```dp[i-1][sum-diff] + dp[i-1][sum+diff]```。 + +另外注意,符合要求的子区间也可能和i-1没有关系,直接从元素i开始(即只有一个元素)。所以我们需要补上: +``` +dp[i][diff[i]] += 1; +dp[i][-diff[i]] += 1; +``` +这样我们就可以计算出所有dp[i][sum]。最终答案就是累加所有的dp[i][0]. + +因为dp状态的第二个下标可能会是负数,所以我们需要统一抬升```offset=10000```. offset根据sum的最大值而定(即nums1或nums2的所有元素之和)。 From e6a8d54e4d5b45543ac0e116bdfb3758706ca851 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 4 Feb 2022 23:15:48 -0800 Subject: [PATCH 0430/2729] Create 2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal.cpp --- ...een-Buckets-to-Make-Water-Levels-Equal.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal.cpp diff --git a/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal.cpp b/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal.cpp new file mode 100644 index 000000000..02217fd9b --- /dev/null +++ b/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + double equalizeWater(vector& buckets, int loss) + { + double left = 0; + double right = 0; + for (int x: buckets) + right += x; + + while (abs(right-left)>1e-5) + { + double mid = (left+right)/2; + double s1 = 0; + double s2 = 0; + for (int x: buckets) + { + if (x>mid) + s1 += x-mid; + else + s2 += mid -x; + } + + if (s1*(100-loss)*0.01 > s2) + left = mid; + else + right = mid; + } + + return left; + + } +}; From f0758fd87f79a8182462b97b0badab00afd5825f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 4 Feb 2022 23:16:14 -0800 Subject: [PATCH 0431/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0d09ed57f..a4b0913b7 100644 --- a/Readme.md +++ b/Readme.md @@ -121,6 +121,7 @@ [2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store) (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) +[2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal) (M) #### [Hash Table](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From e67e175fcd44f9e5e57b473494e5283693692934 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 4 Feb 2022 23:18:28 -0800 Subject: [PATCH 0432/2729] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/Readme.md diff --git a/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/Readme.md b/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/Readme.md new file mode 100644 index 000000000..a7ba45058 --- /dev/null +++ b/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal/Readme.md @@ -0,0 +1,3 @@ +### 2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal + +二分搜值,猜测一个最终水位level。然后遍历所有水桶,将所有高于level的水量累计起来记做s1,将所有低于level的水量累计起来记做s2,如果s1扣除损耗之后仍然大于s2,那么就可以上调level,否则就下调level。 From 5aa01231c740d7750661c7459f0375c8a799c656 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 00:05:59 -0800 Subject: [PATCH 0433/2729] Create 2128.Remove-All-Ones-With-Row-and-Column-Flips.cpp --- ...ove-All-Ones-With-Row-and-Column-Flips.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Math/2128.Remove-All-Ones-With-Row-and-Column-Flips/2128.Remove-All-Ones-With-Row-and-Column-Flips.cpp diff --git a/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips/2128.Remove-All-Ones-With-Row-and-Column-Flips.cpp b/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips/2128.Remove-All-Ones-With-Row-and-Column-Flips.cpp new file mode 100644 index 000000000..f279f0e5a --- /dev/null +++ b/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips/2128.Remove-All-Ones-With-Row-and-Column-Flips.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + bool removeOnes(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + + for (int i=1; i>& grid, int a, int b) + { + int n = grid[0].size(); + for (int j=0; j>& grid, int a, int b) + { + int n = grid[0].size(); + for (int j=0; j Date: Sat, 5 Feb 2022 00:06:31 -0800 Subject: [PATCH 0434/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a4b0913b7..bfd4fdc13 100644 --- a/Readme.md +++ b/Readme.md @@ -941,6 +941,7 @@ [1739.Building-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/Math/1739.Building-Boxes) (H-) [1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Math/1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation) (H) [1969.Minimum-Non-Zero-Product-of-the-Array-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/1969.Minimum-Non-Zero-Product-of-the-Array-Elements) (M+) +[2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) From 260a7539554530a3677c7d1c48c0b6b1b6ddacbb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 00:19:06 -0800 Subject: [PATCH 0435/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Math/2128.Remove-All-Ones-With-Row-and-Column-Flips/Readme.md diff --git a/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips/Readme.md b/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips/Readme.md new file mode 100644 index 000000000..9c6e81c68 --- /dev/null +++ b/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips/Readme.md @@ -0,0 +1,9 @@ +### 2128.Remove-All-Ones-With-Row-and-Column-Flips + +假设有一系列的操作能够实现全部翻转为0,那么这些操作的顺序任意打乱,应该不影响最终效果。所以我们不妨先只做列翻转,再做行翻转。 + +可以想象,我想通过某些行的翻转最终实现全部为0,只可能是一种情况:这些行的元素之前已经通过若干次列翻转全部变成了1。考虑到列翻转的操作会影响到多行,这就意味着这些行的列元素必然相等。 + +同理,如果某些行不需要通过行翻转就能实现全部为0,只有一种情况:这些行的元素之前已经通过若干次列翻转全部变成了0。考虑到列翻转的操作会影响到多行,这就意味着这些行的列元素必然相等。 + +综上,原矩阵中,所有行的pattern只可能是有两种,并且这两种pattern恰好都是互斥的(即001101和110010的关系)。这样通过若干次列翻转后,就能得到若干个全部是1的行,以及若干个全部是0的行。 From 5ded2ffff9f5015ad8a099de7e9d654138c5796e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 17:23:20 -0800 Subject: [PATCH 0436/2729] Create 2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp --- ...ence-in-Sums-After-Removal-of-Elements.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp diff --git a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp new file mode 100644 index 000000000..803f51024 --- /dev/null +++ b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp @@ -0,0 +1,56 @@ +using LL = long long; +class Solution { +public: + long long minimumDifference(vector& nums) + { + int n = nums.size()/3; + + multisetSet; + LL sum = 0; + + for (int i=0; ileft(3*n); + left[n-1] = sum; + for (int i=n; i<2*n; i++) + { + Set.insert(nums[i]); + sum += nums[i]; + sum -= *(Set.rbegin()); + left[i] = sum; + int t = *(Set.rbegin()); + Set.erase(Set.lower_bound(t)); + } + for (int i=n; i<2*n; i++) + left[i] = min(left[i], left[i-1]); + + + Set.clear(); + sum = 0; + for (int i=3*n-1; i>=2*n; i--) + { + Set.insert(nums[i]); + sum += nums[i]; + } + vectorright(3*n); + right[2*n] = sum; + for (int i=2*n-1; i>=n; i--) + { + Set.insert(nums[i]); + sum += nums[i]; + sum -= *(Set.begin()); + right[i] = sum; + Set.erase(Set.begin()); + } + for (int i=2*n-1; i>=0; i--) + right[i] = max(right[i], right[i+1]); + + LL ret = LLONG_MAX; + for (int i=n-1; i<2*n; i++) + ret = min(ret, left[i]-right[i+1]); + return ret; + } +}; From 6960cf538adb310475b1878ab3164eab6dd3ccd7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 17:27:59 -0800 Subject: [PATCH 0437/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bfd4fdc13..e6d960802 100644 --- a/Readme.md +++ b/Readme.md @@ -1061,6 +1061,7 @@ [1671.Minimum-Number-of-Removals-to-Make-Mountain-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1671.Minimum-Number-of-Removals-to-Make-Mountain-Array) (M+) [1769.Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1769.Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box) (M+) [1888.Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1888.Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating) (M+) +[2163.Minimum-Difference-in-Sums-After-Removal-of-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements) (M+) * ``State Machine`` [524.Longest-Word-in-Dictionary-through-Deleting](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/524.Longest-Word-in-Dictionary-through-Deleting) (M+) [727.Minimum-Window-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/727.Minimum-Window-Subsequence) (H-) From e8aa5681a16a16e3ee7c6e507a3d89681d6ccb29 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 23:23:46 -0800 Subject: [PATCH 0438/2729] Update 2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp --- ...ence-in-Sums-After-Removal-of-Elements.cpp | 68 +++++++++---------- 1 file changed, 32 insertions(+), 36 deletions(-) diff --git a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp index 803f51024..6263c3acd 100644 --- a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp +++ b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp @@ -3,54 +3,50 @@ class Solution { public: long long minimumDifference(vector& nums) { - int n = nums.size()/3; + int n = nums.size()/3; + - multisetSet; - LL sum = 0; - - for (int i=0; ileft(3*n); - left[n-1] = sum; - for (int i=n; i<2*n; i++) - { - Set.insert(nums[i]); + LL sum = 0; + vectorleftMin(3*n); + priority_queuepq; + for (int i=0; i<2*n; i++) + { + pq.push(nums[i]); sum += nums[i]; - sum -= *(Set.rbegin()); - left[i] = sum; - int t = *(Set.rbegin()); - Set.erase(Set.lower_bound(t)); + if (i>=n) + { + sum -= pq.top(); + pq.pop(); + } + if (i>=n-1) + leftMin[i] = sum; + else if (i>n-1) + leftMin[i] = min(leftMin[i-1], sum); } - for (int i=n; i<2*n; i++) - left[i] = min(left[i], left[i-1]); - Set.clear(); + sum = 0; - for (int i=3*n-1; i>=2*n; i--) + priority_queue,greater<>>pq2; + vectorrightMax(3*n); + for (int i=3*n-1; i>=n; i--) { - Set.insert(nums[i]); + pq2.push(nums[i]); sum += nums[i]; + if (i<=2*n-1) + { + sum -= pq2.top(); + pq2.pop(); + } + if (i==2*n) + rightMax[i] = sum; + else if (i<2*n) + rightMax[i] = max(rightMax[i+1], sum); } - vectorright(3*n); - right[2*n] = sum; - for (int i=2*n-1; i>=n; i--) - { - Set.insert(nums[i]); - sum += nums[i]; - sum -= *(Set.begin()); - right[i] = sum; - Set.erase(Set.begin()); - } - for (int i=2*n-1; i>=0; i--) - right[i] = max(right[i], right[i+1]); LL ret = LLONG_MAX; for (int i=n-1; i<2*n; i++) - ret = min(ret, left[i]-right[i+1]); + ret = min(ret, leftMin[i]-rightMax[i+1]); return ret; } }; From 51d937c6842913fb267753c509afee64004fe736 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 23:23:58 -0800 Subject: [PATCH 0439/2729] Update 2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp --- ....Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp index 6263c3acd..70be327bd 100644 --- a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp +++ b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp @@ -4,8 +4,7 @@ class Solution { long long minimumDifference(vector& nums) { int n = nums.size()/3; - - + LL sum = 0; vectorleftMin(3*n); priority_queuepq; @@ -24,8 +23,6 @@ class Solution { leftMin[i] = min(leftMin[i-1], sum); } - - sum = 0; priority_queue,greater<>>pq2; vectorrightMax(3*n); From 62ffedfdf9d4b7a31e0440f385a73ad7892179e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 23:39:27 -0800 Subject: [PATCH 0440/2729] Update 2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp --- ...ence-in-Sums-After-Removal-of-Elements.cpp | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp index 70be327bd..2c55a3607 100644 --- a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp +++ b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp @@ -5,40 +5,44 @@ class Solution { { int n = nums.size()/3; - LL sum = 0; + LL minSum = LLONG_MAX; + LL rollingSum = 0; vectorleftMin(3*n); priority_queuepq; for (int i=0; i<2*n; i++) { pq.push(nums[i]); - sum += nums[i]; - if (i>=n) + rollingSum += nums[i]; + if (pq.size() > n) { - sum -= pq.top(); + rollingSum -= pq.top(); pq.pop(); } - if (i>=n-1) - leftMin[i] = sum; - else if (i>n-1) - leftMin[i] = min(leftMin[i-1], sum); + if (pq.size() == n) + { + minSum = min(minSum, rollingSum); + leftMin[i] = minSum; + } } - sum = 0; + LL maxSum = LLONG_MIN; + rollingSum = 0; priority_queue,greater<>>pq2; vectorrightMax(3*n); for (int i=3*n-1; i>=n; i--) { pq2.push(nums[i]); - sum += nums[i]; + rollingSum += nums[i]; if (i<=2*n-1) { - sum -= pq2.top(); + rollingSum -= pq2.top(); pq2.pop(); } - if (i==2*n) - rightMax[i] = sum; - else if (i<2*n) - rightMax[i] = max(rightMax[i+1], sum); + if (pq.size() == n) + { + maxSum = max(maxSum, rollingSum); + rightMax[i] = maxSum; + } } LL ret = LLONG_MAX; From 46879872d55eb9ef6eddc543c43d99fbf61327e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 23:42:41 -0800 Subject: [PATCH 0441/2729] Update 2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp --- ...ifference-in-Sums-After-Removal-of-Elements.cpp | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp index 2c55a3607..b06095b15 100644 --- a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp +++ b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp @@ -5,7 +5,6 @@ class Solution { { int n = nums.size()/3; - LL minSum = LLONG_MAX; LL rollingSum = 0; vectorleftMin(3*n); priority_queuepq; @@ -18,14 +17,10 @@ class Solution { rollingSum -= pq.top(); pq.pop(); } - if (pq.size() == n) - { - minSum = min(minSum, rollingSum); - leftMin[i] = minSum; - } + if (pq.size() == n) + leftMin[i] = rollingSum; } - LL maxSum = LLONG_MIN; rollingSum = 0; priority_queue,greater<>>pq2; vectorrightMax(3*n); @@ -39,10 +34,7 @@ class Solution { pq2.pop(); } if (pq.size() == n) - { - maxSum = max(maxSum, rollingSum); - rightMax[i] = maxSum; - } + rightMax[i] = rollingSum; } LL ret = LLONG_MAX; From c3e278e456e204d0217036aa2c050fe4fbd969c8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 23:45:56 -0800 Subject: [PATCH 0442/2729] Update 2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp --- ...163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp index b06095b15..4c6498db3 100644 --- a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp +++ b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp @@ -28,7 +28,7 @@ class Solution { { pq2.push(nums[i]); rollingSum += nums[i]; - if (i<=2*n-1) + if (pq2.size() > n) { rollingSum -= pq2.top(); pq2.pop(); From d9c4a5bc27d5c54ca5a6a052b53fcf392f1e6910 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Feb 2022 23:46:06 -0800 Subject: [PATCH 0443/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/Readme.md diff --git a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/Readme.md b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/Readme.md new file mode 100644 index 000000000..023550ff5 --- /dev/null +++ b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/Readme.md @@ -0,0 +1,7 @@ +### 2163.Minimum-Difference-in-Sums-After-Removal-of-Elements + +因为删除n个元素之后,剩余的2n个元素会自然地分成前后两个部分,所以我们很自然地会考察这两个部分的分界点在哪里。假设分界点在位置k,那么sum_first怎么选?自然就是nums[0:k]里面和最小的n个元素;sum_second怎么选?自然就是nums[k+1:n-1]里面和最大的n个元素。 + +于是问题转化为,如何高效地在前k个元素里找和最小的n个元素?显然我们就找最小的n个元素即可。从做往右遍历的时候,用一个优先队列始终保存n个最小的元素,就可以得到k左边最小的n个元素的和,记做leftMin[k]。同理我们可以用NlogN的时候,从右往左遍历,得到rightMax[k],表示k右边最大的n个元素的和。 + +本题的答案就是找一个全局最小的```leftMin[k]-rightMax[k+1]```. From 2276183f7866f07880665b1df67761b77bef0005 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Feb 2022 01:54:13 -0800 Subject: [PATCH 0444/2729] Update 2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp --- ...ence-in-Sums-After-Removal-of-Elements.cpp | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp index 4c6498db3..cf46fcdad 100644 --- a/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp +++ b/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements.cpp @@ -3,43 +3,43 @@ class Solution { public: long long minimumDifference(vector& nums) { - int n = nums.size()/3; - - LL rollingSum = 0; - vectorleftMin(3*n); + int n = nums.size()/3; + + vectorleftMin(3*n); priority_queuepq; - for (int i=0; i<2*n; i++) - { + LL sum = 0; + for (int i=0; i<3*n; i++) + { pq.push(nums[i]); - rollingSum += nums[i]; + sum += nums[i]; if (pq.size() > n) { - rollingSum -= pq.top(); + sum -= pq.top(); pq.pop(); } - if (pq.size() == n) - leftMin[i] = rollingSum; + leftMin[i] = sum; } - rollingSum = 0; - priority_queue,greater<>>pq2; - vectorrightMax(3*n); - for (int i=3*n-1; i>=n; i--) + vectorrightMax(3*n); + priority_queue, greater<>>pq2; + sum = 0; + for (int i=3*n-1; i>=0; i--) { pq2.push(nums[i]); - rollingSum += nums[i]; + sum += nums[i]; if (pq2.size() > n) { - rollingSum -= pq2.top(); + sum -= pq2.top(); pq2.pop(); } - if (pq.size() == n) - rightMax[i] = rollingSum; - } + rightMax[i] = sum; + } LL ret = LLONG_MAX; for (int i=n-1; i<2*n; i++) ret = min(ret, leftMin[i]-rightMax[i+1]); - return ret; + + return ret; } }; + From 9d1f10b242ce3eff83566dd8ccce179bcfb1aac1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Feb 2022 02:05:07 -0800 Subject: [PATCH 0445/2729] Create 2166.Design-Bitset.cpp --- .../2166.Design-Bitset/2166.Design-Bitset.cpp | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Design/2166.Design-Bitset/2166.Design-Bitset.cpp diff --git a/Design/2166.Design-Bitset/2166.Design-Bitset.cpp b/Design/2166.Design-Bitset/2166.Design-Bitset.cpp new file mode 100644 index 000000000..82a7c182a --- /dev/null +++ b/Design/2166.Design-Bitset/2166.Design-Bitset.cpp @@ -0,0 +1,78 @@ +class Bitset { + int flips[100000]; + int m; + int totalFlip = 0; + int cnt = 0; +public: + Bitset(int size) { + m = size; + for (int i=0; i= 1; + } + + int count() + { + return cnt; + } + + string toString() + { + string s; + for (int i=0; ifix(idx); + * obj->unfix(idx); + * obj->flip(); + * bool param_4 = obj->all(); + * bool param_5 = obj->one(); + * int param_6 = obj->count(); + * string param_7 = obj->toString(); + */ From 16c9d2e43bc96ad142f513cd72adc2d20f50fe06 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Feb 2022 02:05:33 -0800 Subject: [PATCH 0446/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e6d960802..a8f88b825 100644 --- a/Readme.md +++ b/Readme.md @@ -299,6 +299,7 @@ [1418.Display-Table-of-Food-Orders-in-a-Restaurant](https://github.com/wisdompeak/LeetCode/tree/master/Design/1418.Display-Table-of-Food-Orders-in-a-Restaurant) (H-) [1622.Fancy-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Design/1622.Fancy-Sequence) (H+) [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Design/1801.Number-of-Orders-in-the-Backlog) (M+) +[2166.Design-Bitset](https://github.com/wisdompeak/LeetCode/tree/master/Design/2166.Design-Bitset) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) From 7d7bc52933212a7edf4cefef660896783071ea94 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Feb 2022 17:07:20 -0800 Subject: [PATCH 0447/2729] Create Readme.md --- Design/2166.Design-Bitset/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Design/2166.Design-Bitset/Readme.md diff --git a/Design/2166.Design-Bitset/Readme.md b/Design/2166.Design-Bitset/Readme.md new file mode 100644 index 000000000..5b983b2a8 --- /dev/null +++ b/Design/2166.Design-Bitset/Readme.md @@ -0,0 +1,5 @@ +### 2166.Design-Bitset + +本题不要试图用C++自带的bitset做。C++的bitset在初始化时不能自定义空间大小,如果开满了N=1e5,那么就会TLE。 + +本题设立两个变量分别是flip[i]和totalFlip。前者表示第i个元素被单独翻转了几次,后者表示所有元素被翻转了几次。那么任意元素在任意时刻的最终状态就是```(flip[i]+totalFlip)%2```. From 13313cc6c11112eb82c80ec8245db043a3498750 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Feb 2022 17:40:24 -0800 Subject: [PATCH 0448/2729] Create 2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v1.cpp --- ...e-All-Cars-Containing-Illegal-Goods_v1.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v1.cpp diff --git a/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v1.cpp b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v1.cpp new file mode 100644 index 000000000..d2bea6e35 --- /dev/null +++ b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v1.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int minimumTime(string s) + { + int n = s.size(); + vectorpre(n); + + vectorleft(n); + left[0] = s[0]=='0'?0:1; + for (int i=1; iright(n); + right[n-1] = s[n-1]=='0'?0:1; + for (int i=n-2; i>=0; i--) + { + if (s[i]=='0') + right[i] = right[i+1]; + else + right[i] = min(2+right[i+1], n-i); + } + + int ret = min(left[n-1], right[0]); + for (int i=1; i Date: Sun, 6 Feb 2022 17:40:58 -0800 Subject: [PATCH 0449/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a8f88b825..d92b2ab53 100644 --- a/Readme.md +++ b/Readme.md @@ -1063,6 +1063,7 @@ [1769.Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1769.Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box) (M+) [1888.Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1888.Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating) (M+) [2163.Minimum-Difference-in-Sums-After-Removal-of-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements) (M+) +[2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods) (H-) * ``State Machine`` [524.Longest-Word-in-Dictionary-through-Deleting](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/524.Longest-Word-in-Dictionary-through-Deleting) (M+) [727.Minimum-Window-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/727.Minimum-Window-Subsequence) (H-) From 2888194132c15e9100a3781c6d8c3760cd4db1c4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Feb 2022 18:12:04 -0800 Subject: [PATCH 0450/2729] Update 2166.Design-Bitset.cpp --- .../2166.Design-Bitset/2166.Design-Bitset.cpp | 48 +++++-------------- 1 file changed, 13 insertions(+), 35 deletions(-) diff --git a/Design/2166.Design-Bitset/2166.Design-Bitset.cpp b/Design/2166.Design-Bitset/2166.Design-Bitset.cpp index 82a7c182a..5799e6162 100644 --- a/Design/2166.Design-Bitset/2166.Design-Bitset.cpp +++ b/Design/2166.Design-Bitset/2166.Design-Bitset.cpp @@ -1,10 +1,10 @@ -class Bitset { +class Bitset { int flips[100000]; - int m; int totalFlip = 0; + int m; int cnt = 0; public: - Bitset(int size) { + Bitset(int size) { m = size; for (int i=0; i= 1; } - int count() - { + int count() { return cnt; } - string toString() - { + string toString() { string s; for (int i=0; ifix(idx); - * obj->unfix(idx); - * obj->flip(); - * bool param_4 = obj->all(); - * bool param_5 = obj->one(); - * int param_6 = obj->count(); - * string param_7 = obj->toString(); - */ From 1311f525f0b429947f5e54266f30cdfbd13439c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Feb 2022 23:14:12 -0800 Subject: [PATCH 0451/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md diff --git a/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md new file mode 100644 index 000000000..4b9d1791a --- /dev/null +++ b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md @@ -0,0 +1,21 @@ +### 2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods + +#### 解法1 +我们可以知道,左边有一部分元素是用法则一处理,右边有一部分元素是用法则二处理,中间有一部分是用法则三处理。这里就涉及到了三部分的两个边界,这意味着我们可能要用N^2的复杂度来遍历这些边界并计算代价。本题有一个巧妙的解法,就是令dp1[i]表示[0:i]这些元素用法则一、三处理(即删除元素1)需要的最少代价;同理令dp2[i]表示[i:n-1]这些元素用法则二、三处理需要的最少代价。这样我们只需要遍历一个边界即可。 + +对于dp1[i],我们需要根据s[i]是否是1来做不一样的决策. 如果s[i]本身是0,那么0不需要删除也就不需要增加额外的代价,故有```dp1[i]=dp1[i-1]```. + +如果s[i]是1,那么我们有两种方法: + 1. 如果元素i是按照法则一删除,那么意味着[0:i]都是逐个从左往右删除的,故有```dp1[i]=i+1```. + 2. 如果元素i是按照法则三删除,那么删除s[i]本身需要付出2的代价,在此之前,我们就可以复用dp1[i-1],因为我们并不关心在元素i之前具体使用什么法则实现dp[i-1]的,无论法则一还是三,都不影响我用法则三来删除s[i]。 + +综上,我们有```dp1[i] = min(i+1, dp[i-1]+2)``` + +同理我们可以得到dp2[i],那么最终答案就是找全局最大的```dp`[i]+dp2[i+1]```. + +#### 解法2 +本题就是要找两个分界点i和j,使得[0:i-1]这部分按照法则1删除,代价就是i; [j+1:n-1]这部分按照法则2删除,代价就是n-j-1; 中间部分按照法则3删除,代价是[i:j]之间的元素1的个数乘以2。 + +于是我们可以将本题转化为求解最小化的```i + 2*(presum[j]-presum[i-1]) + n-j-1```,其中presum[k]表示[0:k]区间内有多少个元素1. + +将上式再转化一下,即```min {(2*presum[j]-j) - (2*presum[i-1]-(i-1)) + n}```. 很显然,我们构造新的数列```nums[i]=2*presum[i]-i```,即求```min (arr[j] - arr[i-1]) + n```. 这就转化为了在arr数组里找最大值和最小值。注意特别地,i是可以取0的, 故arr[-1]需要取值为```2*presum[-1]+1 = 1```. 因此我们要在arr数组里额外加上1. From e58637b0339fa5efac44d2d15d3332efaf297abb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Feb 2022 23:15:49 -0800 Subject: [PATCH 0452/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md index 4b9d1791a..18309599e 100644 --- a/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md +++ b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md @@ -18,4 +18,4 @@ 于是我们可以将本题转化为求解最小化的```i + 2*(presum[j]-presum[i-1]) + n-j-1```,其中presum[k]表示[0:k]区间内有多少个元素1. -将上式再转化一下,即```min {(2*presum[j]-j) - (2*presum[i-1]-(i-1)) + n}```. 很显然,我们构造新的数列```nums[i]=2*presum[i]-i```,即求```min (arr[j] - arr[i-1]) + n```. 这就转化为了在arr数组里找最大值和最小值。注意特别地,i是可以取0的, 故arr[-1]需要取值为```2*presum[-1]+1 = 1```. 因此我们要在arr数组里额外加上1. +将上式再转化一下,即```min {(2*presum[j]-j) - (2*presum[i-1]-(i-1)) + n}```. 很显然,我们构造新的数列```nums[i]=2*presum[i]-i```,即求```min (arr[j] - arr[i-1]) + n```,其中i Date: Sun, 6 Feb 2022 23:25:59 -0800 Subject: [PATCH 0453/2729] Update Readme.md --- .../Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md index 18309599e..ac426cfe1 100644 --- a/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md +++ b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/Readme.md @@ -18,4 +18,6 @@ 于是我们可以将本题转化为求解最小化的```i + 2*(presum[j]-presum[i-1]) + n-j-1```,其中presum[k]表示[0:k]区间内有多少个元素1. -将上式再转化一下,即```min {(2*presum[j]-j) - (2*presum[i-1]-(i-1)) + n}```. 很显然,我们构造新的数列```nums[i]=2*presum[i]-i```,即求```min (arr[j] - arr[i-1]) + n```,其中i Date: Sun, 6 Feb 2022 23:40:29 -0800 Subject: [PATCH 0454/2729] Create 2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v2.cpp --- ...e-All-Cars-Containing-Illegal-Goods_v2.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v2.cpp diff --git a/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v2.cpp b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v2.cpp new file mode 100644 index 000000000..1c4de79ee --- /dev/null +++ b/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods_v2.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minimumTime(string s) + { + int n = s.size(); + + vectorpre(n); + pre[0] = (s[0]=='1'); + for (int i=1; iarr(n); + for (int i=0; i Date: Mon, 7 Feb 2022 00:51:57 -0800 Subject: [PATCH 0455/2729] Create 2158.Amount-of-New-Area-Painted-Each-Day.cpp --- ...58.Amount-of-New-Area-Painted-Each-Day.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Others/2158.Amount-of-New-Area-Painted-Each-Day/2158.Amount-of-New-Area-Painted-Each-Day.cpp diff --git a/Others/2158.Amount-of-New-Area-Painted-Each-Day/2158.Amount-of-New-Area-Painted-Each-Day.cpp b/Others/2158.Amount-of-New-Area-Painted-Each-Day/2158.Amount-of-New-Area-Painted-Each-Day.cpp new file mode 100644 index 000000000..3190ac4a9 --- /dev/null +++ b/Others/2158.Amount-of-New-Area-Painted-Each-Day/2158.Amount-of-New-Area-Painted-Each-Day.cpp @@ -0,0 +1,36 @@ +using AI3 = array; +class Solution { +public: + vector amountPainted(vector>& paint) + { + vectorarr; + for (int i=0; iSet; + int n = paint.size(); + vectorrets(n); + for (int i=0; i Date: Mon, 7 Feb 2022 00:52:40 -0800 Subject: [PATCH 0456/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d92b2ab53..351aa8dcb 100644 --- a/Readme.md +++ b/Readme.md @@ -1184,6 +1184,7 @@ 1893.Check if All the Integers in a Range Are Covered (E) [1943.Describe-the-Painting](https://github.com/wisdompeak/LeetCode/tree/master/Others/1943.Describe-the-Painting) (H-) [2015.Average-Height-of-Buildings-in-Each-Segment](https://github.com/wisdompeak/LeetCode/tree/master/Others/2015.Average-Height-of-Buildings-in-Each-Segment) (H-) +[2158.Amount-of-New-Area-Painted-Each-Day](https://github.com/wisdompeak/LeetCode/tree/master/Others/2158.Amount-of-New-Area-Painted-Each-Day) (H-) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 92f97055782bf00679787669c0896a2af258ae94 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Feb 2022 01:00:54 -0800 Subject: [PATCH 0457/2729] Create Readme.md --- Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md diff --git a/Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md b/Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md new file mode 100644 index 000000000..69b400739 --- /dev/null +++ b/Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md @@ -0,0 +1,7 @@ +### 2158.Amount-of-New-Area-Painted-Each-Day + +此题是扫描线一例非常特别的应用。 + +通常的扫描线算法跟踪的是每个分割区间的重叠数目(比如说这一段区间有三条线段重叠,下一个区间有两条线段重叠),但本题跟踪的是每个区间的重叠信息。我们可以用于扫描线一样的算法,用一个有序集合来跟踪在每个分割区间内,有哪些线段在此重叠:如果是线段开头就加入,如果是线段结尾就删除。显然,编号最小的线段最先拥有这个区间的打印权,故把这段分割区间的长度记在这条线段上即可。 + +最终输出每条线段的打印总长度。 From 621cf97d341f07875c6466ba51ec2351d4689139 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Feb 2022 22:14:48 -0800 Subject: [PATCH 0458/2729] Update Readme.md --- Dynamic_Programming/518.Coin-Change-2/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/518.Coin-Change-2/Readme.md b/Dynamic_Programming/518.Coin-Change-2/Readme.md index 44cd0112c..69f1f03a9 100644 --- a/Dynamic_Programming/518.Coin-Change-2/Readme.md +++ b/Dynamic_Programming/518.Coin-Change-2/Readme.md @@ -38,7 +38,7 @@ for (int i=0; i Date: Mon, 7 Feb 2022 22:33:08 -0800 Subject: [PATCH 0459/2729] Update Readme.md --- Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md b/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md index c6ce5b1cc..62c0bd5f5 100644 --- a/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md +++ b/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md @@ -1,6 +1,6 @@ ### 1820.Maximum-Number-of-Accepted-Invitations -这题是求无权二分图最大匹配的模板题,使用的是经典的匈牙利算法。 +我们将所有男生节点放在图的左边,将所有女生节点放在图的右边,部分男生女生之间有边相连。我们希望选取最多的边,但是每个男生或者女生最多只能与一条边相连。于是这题就是求无权二分图最大匹配的模板题,使用的是经典的匈牙利算法。 #### DFS 首先定义两个概念: From 1b750812a510dad18e86196f8be596d1f6616437 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Feb 2022 22:35:45 -0800 Subject: [PATCH 0460/2729] Update Readme.md --- Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md b/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md index 62c0bd5f5..a548a563a 100644 --- a/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md +++ b/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md @@ -4,7 +4,7 @@ #### DFS 首先定义两个概念: -1. 交替路:从一个未匹配点出发,依次经过非匹配边、匹配边、非匹配边……形成的路径叫交替路。 +1. 交替路:从一个未匹配点出发,依次经过非匹配边、匹配边、非匹配边……形成的路径叫交替路。所谓的匹配边,就是这条边被选中了;非匹配边,就是这条边未被选中。 2. 增广路:从一个未匹配点出发,走交替路,最终到达另一个未匹配点(一定是对面的节点),则这条交替路称为增广路(agumenting path)。增广路的特点就是,非匹配边的数目比匹配边的数目恰好多一个。 我们依次查看左图的节点。记当前的左图节点A尚未配对,那么我们用DFS找到一条以A为起点的增广路径(找一条即可),假设终点为B,这条增广路径上的匹配边个数是k,非匹配边的个数是k+1. 我们接下来做一个重要的操作:取消所有的匹配边,将非匹配边改为匹配边。这样操作的结果是:1. 不引入矛盾,即不会有任何一个点与对面的两个点相连。2. 配对的pair比原来多了1对。3. 保证了A被匹配。如果我们找不到这样的以A为起点的增广路径,那么就说明无法将A匹配的同时不影响匹配边的总量,也就是说我们要放弃对A的匹配。 From 3fb7ee6ffeedf5b3a47076358805bd9da4acc772 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Feb 2022 23:06:38 -0800 Subject: [PATCH 0461/2729] Update Readme.md --- Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md b/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md index a548a563a..6e8d4d7fc 100644 --- a/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md +++ b/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md @@ -1,6 +1,6 @@ ### 1820.Maximum-Number-of-Accepted-Invitations -我们将所有男生节点放在图的左边,将所有女生节点放在图的右边,部分男生女生之间有边相连。我们希望选取最多的边,但是每个男生或者女生最多只能与一条边相连。于是这题就是求无权二分图最大匹配的模板题,使用的是经典的匈牙利算法。 +我们将所有学生看做为节点,部分节点之间有边相连(本题里只是男生和女生之间)。我们希望选取最多的边,但是每个节点最多只能与一条边相连。于是这题就是求无权二分图最大匹配的模板题,使用的是经典的匈牙利算法。 #### DFS 首先定义两个概念: From 9b7d58e500050fa36f00131fd2248380a563292d Mon Sep 17 00:00:00 2001 From: Fenghe Xu Date: Wed, 9 Feb 2022 00:44:44 +0800 Subject: [PATCH 0462/2729] fix: 1774 brute-force TLE Remove duplicates of topping combinations to prevent TLE. --- .../1774.Closest-Dessert-Cost.cpp | 60 +++++++++++-------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp b/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp index b8590d089..5465273d4 100644 --- a/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp +++ b/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp @@ -1,30 +1,40 @@ class Solution { public: - int closestCost(vector& baseCosts, vector& toppingCosts, int target) - { - int cost; - int diff = INT_MAX; - int m = toppingCosts.size(); + int closestCost(vector& baseCosts, vector& toppingCosts, int target) { + set toppingsSet; + + int n = toppingCosts.size(); + + for(int state = 0; state < (1 << (2 * n)); ++state) { + int sum = 0; + for(int i = 0; i < n; ++i) { + int cur = (state >> (2 * i)) & 3; + if(!cur || cur == 3) continue; + sum += toppingCosts[i] * cur; + } + toppingsSet.insert(sum); + } - for (int baseCost: baseCosts) - { - for (int state = 0; state < (1<<(2*m)); state++) - { - int sum = baseCost; - for (int i=0; i>(i*2))&1) - sum += toppingCosts[i]; - if ((state>>(i*2+1))&1) - sum += toppingCosts[i]; - } - if (abs(sum-target) Date: Tue, 8 Feb 2022 14:36:42 -0800 Subject: [PATCH 0463/2729] Update Readme.md --- Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md b/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md index 6e8d4d7fc..bf59bdd5d 100644 --- a/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md +++ b/Graph/1820.Maximum-Number-of-Accepted-Invitations/Readme.md @@ -1,6 +1,6 @@ ### 1820.Maximum-Number-of-Accepted-Invitations -我们将所有学生看做为节点,部分节点之间有边相连(本题里只是男生和女生之间)。我们希望选取最多的边,但是每个节点最多只能与一条边相连。于是这题就是求无权二分图最大匹配的模板题,使用的是经典的匈牙利算法。 +我们将所有学生看做为节点,部分节点之间有边相连(本题里只是男生和女生之间)。显然,这一定是个二分图。然后,我们希望选取最多的边且每个节点最多只能与一条边相连。于是这就是求无权二分图最大匹配的模板题,使用的是经典的匈牙利算法。 #### DFS 首先定义两个概念: From 5bf0f5d8d4acb7cc325d1115ced18a3f100c276c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 15:28:47 -0800 Subject: [PATCH 0464/2729] Create 2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix.cpp --- ...ions-to-Remove-Adjacent-Ones-in-Matrix.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix.cpp diff --git a/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix.cpp b/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix.cpp new file mode 100644 index 000000000..8336b4767 --- /dev/null +++ b/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix.cpp @@ -0,0 +1,60 @@ +class Solution { + vector next[90000]; + int match[90000]; +public: + int minimumOperations(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + int t = m*n; + + vector>dir({{1,0},{-1,0},{0,1},{0,-1}}); + + for (int i=0; i=m||y<0||y>=n) continue; + if (grid[x][y]!=1) continue; + next[i*n+j].push_back(x*n+y); + } + } + + for (int i=0; ivisited(t); + + int count = 0; + for (int i=0; i&visited) + { + for (int j: next[i]) + { + if (visited[j]) continue; + visited[j] = true; + if (match[j]==-1 || dfs(match[j], visited)) + { + match[i] = j; + match[j] = i; + return true; + } + } + return false; + } +}; From 436a76f6f707b2bb6cface33de1ae8cad568cd50 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 15:29:49 -0800 Subject: [PATCH 0465/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 351aa8dcb..7d732dd22 100644 --- a/Readme.md +++ b/Readme.md @@ -910,7 +910,9 @@ [1719.Number-Of-Ways-To-Reconstruct-A-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1719.Number-Of-Ways-To-Reconstruct-A-Tree) (H+) [1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph) (M+) [1782.Count-Pairs-Of-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1782.Count-Pairs-Of-Nodes) (H) +* ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) +[2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) #### [Math](https://github.com/wisdompeak/LeetCode/tree/master/Math) [089.Gray-Code](https://github.com/wisdompeak/LeetCode/tree/master/Math/089.Gray-Code) (M+) (aka. 1238. Circular Permutation in Binary Representation) From 02c9fe54572a58ae27a2fe9627e9d885e229a9c8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 15:54:58 -0800 Subject: [PATCH 0466/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/Readme.md diff --git a/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/Readme.md b/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/Readme.md new file mode 100644 index 000000000..11b900276 --- /dev/null +++ b/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/Readme.md @@ -0,0 +1,11 @@ +### 2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix + +本题的难点在于如何看出这是一个二分图最大匹配问题。 + +我们只考虑图中为1的点,每两个相邻的1之间看做存在一条边。我们发现这个图中肯定不会出现“含有奇数个节点的环”,故此图肯定可以被分割为[二分图](https://www.renfei.org/blog/bipartite-matching.html)。在本题的语境就是,我们可以将所有为1的节点分为AB两组,每组内部没有边连接,所有的边都跨越这AB两组之间。 + +很显然,如果我们将B组里的节点都翻转为0,那么原图就会变得满足条件(原先的边现在跨接的两端是1和0)。于是根据题意,我们希望二分图的划分策略是让A里的元素越多越好,B里的元素越少越好。 + +那么B集合少到极致意味着什么呢?意味着B里的每一个元素都会有至少一条边通向A(否则我们就可以把它放入A而不影响二分图);但是反之不一定,A里的某些元素可能没有边通向B(当然也不可能通向A的其他元素,否则违反了二分图的定义)。此时,我们回顾一下二分图的最大匹配的定义:指的是选取最多的跨接AB的边,但是所选取的边都不能有公共顶点。于是我们可以推理:因为B一定有边指向A,那么二分图的最大匹配边的数目一定就是B的个数。 + +于是本题就只需要套用匈牙利算法的模板,代码和```1820.Maximum-Number-of-Accepted-Invitations ```非常相似。 From 6bab7d268c6a2ccafa2f23dc5b190c62832337a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 15:55:32 -0800 Subject: [PATCH 0467/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/Readme.md b/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/Readme.md index 11b900276..37094fb58 100644 --- a/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/Readme.md +++ b/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix/Readme.md @@ -6,6 +6,6 @@ 很显然,如果我们将B组里的节点都翻转为0,那么原图就会变得满足条件(原先的边现在跨接的两端是1和0)。于是根据题意,我们希望二分图的划分策略是让A里的元素越多越好,B里的元素越少越好。 -那么B集合少到极致意味着什么呢?意味着B里的每一个元素都会有至少一条边通向A(否则我们就可以把它放入A而不影响二分图);但是反之不一定,A里的某些元素可能没有边通向B(当然也不可能通向A的其他元素,否则违反了二分图的定义)。此时,我们回顾一下二分图的最大匹配的定义:指的是选取最多的跨接AB的边,但是所选取的边都不能有公共顶点。于是我们可以推理:因为B一定有边指向A,那么二分图的最大匹配边的数目一定就是B的个数。 +那么B集合少到极致意味着什么呢?意味着B里的每一个元素都会有至少一条边通向A(否则我们就可以把它放入A而不影响二分图);但是反之不一定,A里的某些元素可能没有边通向B(当然也不可能通向A的其他元素,否则违反了二分图的定义)。此时,我们回顾一下二分图的最大匹配的定义:指的是选取最多的跨接AB的边,但是所选取的边都不能有公共顶点。于是我们可以推理:因为B一定有一条边指向A,那么二分图的最大匹配边的数目一定就是B的个数。 于是本题就只需要套用匈牙利算法的模板,代码和```1820.Maximum-Number-of-Accepted-Invitations ```非常相似。 From ba703eb299b5e54b4e3e056aef831a16d7219fc2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 17:04:09 -0800 Subject: [PATCH 0468/2729] Update 1774.Closest-Dessert-Cost.cpp --- .../1774.Closest-Dessert-Cost.cpp | 43 ++++++++++++------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp b/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp index 5465273d4..c8c42513f 100644 --- a/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp +++ b/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp @@ -1,7 +1,7 @@ class Solution { public: int closestCost(vector& baseCosts, vector& toppingCosts, int target) { - set toppingsSet; + unordered_set toppingsSet; int n = toppingCosts.size(); @@ -14,27 +14,40 @@ class Solution { } toppingsSet.insert(sum); } + vectortoppings(toppingsSet.begin(), toppingsSet.end()); + sort(toppings.begin(), toppings.end()); int ret = INT_MAX; + int ret_diff = INT_MAX; for(int base: baseCosts) { int targetTopping = target - base; - auto it1 = toppingsSet.upper_bound(targetTopping); - auto it2 = it1; - if(it2 != toppingsSet.begin()) --it2; - if(it1 == toppingsSet.end()) --it1; - int cur; - int curDiff1 = abs(*it1 + base - target); - int curDiff2 = abs(*it2 + base - target); - if(curDiff1 < curDiff2) { - cur = *it1 + base; - } else { - cur = *it2 + base; + auto iter = lower_bound(toppings.begin(), toppings.end(), targetTopping); + if (iter!=toppings.end()) + { + int cand = *iter; + if (abs(base+cand-target) < ret_diff) + { + ret = base+cand; + ret_diff = abs(base+cand-target); + } + else if (abs(base+cand-target) == ret_diff && base+cand < ret) + ret = base+cand; } - int retDiff = abs(ret - target); - int curDiff = abs(cur - target); - if(curDiff < retDiff || (curDiff == retDiff && cur < ret)) ret = cur; + + if (iter!=toppings.begin()) + { + int cand = *prev(iter); + if (abs(base+cand-target) < ret_diff) + { + ret = base+cand; + ret_diff = abs(base+cand-target); + } + else if (abs(base+cand-target) == ret_diff && base+cand < ret) + ret = base+cand; + } } + return ret; } }; From f2f7c664b6806460e27563e6b95341b7511236c6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 17:05:20 -0800 Subject: [PATCH 0469/2729] Update Readme.md --- Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md b/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md index 0220ef217..83148fea5 100644 --- a/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md +++ b/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md @@ -3,3 +3,5 @@ 本题需要暴力枚举所有toppings的选配方案。这样的枚举对每种topping都在0,1,2中选择,并没有任何优化、剪支的空间,所以相比于DFS的递归做法(需要递归十次),用bit mask来说更为方便。 我们注意要toppings只有十种,如果用每两个bit位来表示一种topping的方案(00,01,10,11),那么总共需要20个bit位。注意到01和10都可以用来表示该topping选择一份。尽管有些状态的数目上有些浪费,但即使如此,考虑2^20是1e6量级,这样的暴力是可以接收的。 + +我们将所有的toppings的选配方案去重后按照从小到大排序。当我们遍历base时,我们希望找与target-base最接近的topping,这里就可以用二分搜索。 From ffa88460a8b25f0270bb5f5c6264859c76e35161 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 20:16:02 -0800 Subject: [PATCH 0470/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7d732dd22..c0ae7f860 100644 --- a/Readme.md +++ b/Readme.md @@ -80,6 +80,7 @@ 1201.Ugly-Number-III (TBD) [1533.Find-the-Index-of-the-Large-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1533.Find-the-Index-of-the-Large-Integer) (M) [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) +[1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) @@ -765,7 +766,6 @@ [1601.Maximum-Number-of-Achievable-Transfer-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1601.Maximum-Number-of-Achievable-Transfer-Requests) (H-) [1755.Closest-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1755.Closest-Subsequence-Sum) (H) [2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) -[1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) (M) [2151.Maximum-Good-People-Based-on-Statements](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements) (M+) From 2b968b5fa14124d1a102248aed8fc4faf96cc2ab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 21:03:32 -0800 Subject: [PATCH 0471/2729] Update Readme.md --- Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md b/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md index 63305b037..b684263de 100644 --- a/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md +++ b/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md @@ -6,7 +6,7 @@ **引理2:** 给定K个点{xi,yi},曼哈顿距离最远的两个点AB之间的距离L,可以计算如下:令 ```a = x + y, b = x - y```. 则 ```L = max(max{|ai-aj|}, max{|bi-bj|}) for all i,j``` -本题是希望找到K个点集,使得它们的最大曼哈顿距离L满足 ```(L+1)<=K``` +本题是希望找到某K个点组成的集合,记其最大曼哈顿距离L满足,如果```D = (L+1)/2 <= K```,那么说明D天后他们的“中心”肯定会被这K个病毒爆发点传染到。我们求所有D中最小的那个。 我们首先将所有的点按照a值排序(前面提到了a=x+y)。我们用两个循环枚举全部的a值区间[i:j],其中i和j是a值序列的index。对于这个固定的a值区间,前面公式里的“最大a值差”(即```max{|ai-aj|}```),已经是已知的了,就是```aj-ai```。我们此时需思考的是这个区间上的点集的b值范围(前面提到了b=x-y)。我们希望找到K个点,使得他们的最大b值差尽量小。 From 8cf53f5c45982640195301e77868f0c1a4066569 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 21:03:50 -0800 Subject: [PATCH 0472/2729] Update Readme.md --- Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md b/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md index b684263de..421c33383 100644 --- a/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md +++ b/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md @@ -6,7 +6,7 @@ **引理2:** 给定K个点{xi,yi},曼哈顿距离最远的两个点AB之间的距离L,可以计算如下:令 ```a = x + y, b = x - y```. 则 ```L = max(max{|ai-aj|}, max{|bi-bj|}) for all i,j``` -本题是希望找到某K个点组成的集合,记其最大曼哈顿距离L满足,如果```D = (L+1)/2 <= K```,那么说明D天后他们的“中心”肯定会被这K个病毒爆发点传染到。我们求所有D中最小的那个。 +本题是希望找到某K个点组成的集合,记其中最大的曼哈顿距离L,如果```D = (L+1)/2 <= K```,那么说明D天后他们的“中心”肯定会被这K个病毒爆发点传染到。我们求所有D中最小的那个。 我们首先将所有的点按照a值排序(前面提到了a=x+y)。我们用两个循环枚举全部的a值区间[i:j],其中i和j是a值序列的index。对于这个固定的a值区间,前面公式里的“最大a值差”(即```max{|ai-aj|}```),已经是已知的了,就是```aj-ai```。我们此时需思考的是这个区间上的点集的b值范围(前面提到了b=x-y)。我们希望找到K个点,使得他们的最大b值差尽量小。 From 824462d1d0d2c6e7ab8b8ccd8cc760754e6baee8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 22:06:49 -0800 Subject: [PATCH 0473/2729] Update Readme.md --- .../Readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md b/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md index 421c33383..08048ee2a 100644 --- a/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md +++ b/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread/Readme.md @@ -13,3 +13,7 @@ 显然我们只要将这些点再按照b值排个序后,找一段长度为K的滑窗,使得滑窗两端点的b值差最小即可。但是需要注意的是,我们需要保证所选的K个点集的“a值差”仍然是我们之前想要的固定的那个,这意味着我们需要找到i、j这两个点在新建的按照b值排序后的序列里的位置pLeft, pRight。我们用双指针遍历滑动窗口的时候,要求窗口必须包含[pLeft,pRight]这一段。综上,我们在这个b值序列里,遍历所有长度为k、包含[pLeft,pRight]的滑窗,记录最小的“最大b值差”(也就是窗口两端点的b值差)。 总的时间复杂度是 ```o(N^2*NlogN)``` + +============================= + +Update: 以上解法有bug,无法通过新的test case。最大曼哈顿距离是L的点集,并不意味着存在一个中点M,使得M到所有点的距离D不超过(L+1)/2。反例就是[(1,1),(1,2),(2,1),(2,2)]. From 3a37256542e2aa3301486fb82f7f2c8512a05f4e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 22:11:43 -0800 Subject: [PATCH 0474/2729] Update Hungarian.cpp --- Template/Graph/Hungarian.cpp | 134 ++++++++++------------------------- 1 file changed, 38 insertions(+), 96 deletions(-) diff --git a/Template/Graph/Hungarian.cpp b/Template/Graph/Hungarian.cpp index 8097961d1..e2a4d8939 100644 --- a/Template/Graph/Hungarian.cpp +++ b/Template/Graph/Hungarian.cpp @@ -1,100 +1,42 @@ -// https://www.renfei.org/blog/bipartite-matching.html -// 顶点、边的编号均从 0 开始 -// 邻接表储存 - -struct Edge -{ - int from; - int to; - int weight; - - Edge(int f, int t, int w):from(f), to(t), weight(w) {} -}; - -vector G[__maxNodes]; /* G[i] 存储顶点 i 出发的边的编号 */ -vector edges; -typedef vector::iterator iterator_t; -int num_nodes; -int num_left; -int num_right; -int num_edges; -int matching[__maxNodes]; /* 存储求解结果 */ -int check[__maxNodes]; - -/********* DFS ******************************/ - -bool dfs(int u) -{ - for (iterator_t i = G[u].begin(); i != G[u].end(); ++i) { // 对 u 的每个邻接点 - int v = edges[*i].to; - if (!check[v]) { // 要求不在交替路中 - check[v] = true; // 放入交替路 - if (matching[v] == -1 || dfs(matching[v])) { - // 如果是未盖点,说明交替路为增广路,则交换路径,并返回成功 - matching[v] = u; - matching[u] = v; - return true; - } - } - } - return false; // 不存在增广路,返回失败 -} - -int hungarian() -{ - int ans = 0; - memset(matching, -1, sizeof(matching)); - for (int u=0; u < num_left; ++u) { - if (matching[u] == -1) { - memset(check, 0, sizeof(check)); - if (dfs(u)) - ++ans; +int num_nodes = 100000; +class Solution { + vector next[num_nodes]; + int match[num_nodes]; +public: + int minimumOperations(vector>& grid) + { + // construct next[] + + for (int i=0; ivisited(num_nodes); + + int count = 0; + for (int i=0; i Q; -int prev[__maxNodes]; -int Hungarian() -{ - int ans = 0; - memset(matching, -1, sizeof(matching)); - memset(check, -1, sizeof(check)); - for (int i=0; i= 0) { // 此点为匹配点 - prev[matching[v]] = u; - } else { // 找到未匹配点,交替路变为增广路 - flag = true; - int d=u, e=v; - while (d != -1) { - int t = matching[d]; - matching[d] = e; - matching[e] = d; - d = prev[d]; - e = t; - } - } - } - } - Q.pop(); + + bool dfs(int i, vector&visited) + { + for (int j: next[i]) + { + if (visited[j]) continue; + visited[j] = true; + if (match[j]==-1 || dfs(match[j], visited)) + { + match[i] = j; + match[j] = i; + return true; } - if (matching[i] != -1) ++ans; } - } - return ans; -} + return false; + } +}; From 30c5e2b7c2de55c1b5261263da305cba93d3b67b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 23:56:09 -0800 Subject: [PATCH 0475/2729] Update 631.Design Excel Sum Formula.cpp --- .../631.Design Excel Sum Formula.cpp | 92 ++++++++----------- 1 file changed, 37 insertions(+), 55 deletions(-) diff --git a/Design/631.Design-Excel-Sum-Formula/631.Design Excel Sum Formula.cpp b/Design/631.Design-Excel-Sum-Formula/631.Design Excel Sum Formula.cpp index a53bba47f..c2d80eccc 100644 --- a/Design/631.Design-Excel-Sum-Formula/631.Design Excel Sum Formula.cpp +++ b/Design/631.Design-Excel-Sum-Formula/631.Design Excel Sum Formula.cpp @@ -1,80 +1,62 @@ -class Excel { - vector>Table; - unordered_map>Map; - +class Excel { + int Table[27][26]; + vector Exp[27][26]; public: Excel(int H, char W) - { - Table = vector>(H+1,vector(W-'A'+1,0)); + { + for (int i=0; i<27; i++) + for (int j=0; j<26; j++) + Table[i][j] = 0; } void set(int r, char c, int v) - { - if (Map.find(to_string(r)+c)!=Map.end()) - Map.erase(to_string(r)+c); + { Table[r][c-'A']=v; + Exp[r][c-'A'].clear(); } int get(int r, char c) { - if (Map.find(to_string(r)+c)==Map.end()) + if (Exp[r][c-'A'].empty()) return Table[r][c-'A']; else { - Table[r][c-'A'] = sum(r,c,Map[to_string(r)+c]); - return Table[r][c-'A']; + int ret = 0; + for (auto s: Exp[r][c-'A']) + { + int p = s.find(":"); + if (p==-1) + { + auto [x, y] = parse(s); + ret += get(x, y); + } + else + { + auto [x0, y0] = parse(s.substr(0, p)); + auto [x1, y1] = parse(s.substr(p+1)); + for (int i=x0; i<=x1; i++) + for (char j=y0; j<=y1; j++) + ret += get(i, j); + } + } + return ret; } } int sum(int r, char c, vector strs) { - Map[to_string(r)+c]=strs; - int sum=0; - for (int i=0; i parse(string s) + { + int num = stoi(s.substr(1)); + char ch = s[0]; + return {num, ch}; } + }; /** From 1c6db40fbe7620052243a1071feb00ed692e1eca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Feb 2022 23:56:28 -0800 Subject: [PATCH 0476/2729] Rename 631.Design Excel Sum Formula.cpp to 631.Design-Excel-Sum-Formula.cpp --- ...ign Excel Sum Formula.cpp => 631.Design-Excel-Sum-Formula.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Design/631.Design-Excel-Sum-Formula/{631.Design Excel Sum Formula.cpp => 631.Design-Excel-Sum-Formula.cpp} (100%) diff --git a/Design/631.Design-Excel-Sum-Formula/631.Design Excel Sum Formula.cpp b/Design/631.Design-Excel-Sum-Formula/631.Design-Excel-Sum-Formula.cpp similarity index 100% rename from Design/631.Design-Excel-Sum-Formula/631.Design Excel Sum Formula.cpp rename to Design/631.Design-Excel-Sum-Formula/631.Design-Excel-Sum-Formula.cpp From 88070b7c45e877266c9daa28f8ccad966c4c79b4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 9 Feb 2022 00:12:04 -0800 Subject: [PATCH 0477/2729] Update Readme.md --- Design/631.Design-Excel-Sum-Formula/Readme.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Design/631.Design-Excel-Sum-Formula/Readme.md b/Design/631.Design-Excel-Sum-Formula/Readme.md index 5d3e7d082..1e2a9b7ac 100644 --- a/Design/631.Design-Excel-Sum-Formula/Readme.md +++ b/Design/631.Design-Excel-Sum-Formula/Readme.md @@ -1,12 +1,17 @@ ### 631.Design-Excel-Sum-Formula -本题需要注意的是操作的完整性。 +我们定义两个数据结构: +``` + int Val[27][26]; + vector Exp[27][26]; +``` +前者存数值,后者存表达式。 -Set:如果该单元格已经有公式,则需要先把公式从Map里清除,再对该单元格赋值。 +Set:对Val的对应位置赋值。如果该位置已经有Exp,则需要将Exp清空。 -Get:不是简单地从table里读数据。如果该单元格已经有公式,则该单元格依赖于其他单元格且可能未被更新。所以需要先执行一遍公式,即sum(r,c,Map[to_string(r)+c])更新该单元格的内容,再返回。 +Get:如果该位置没有Exp,则从Val里读取。否则就需要解析表达式,对每个位置上递归调用Get,然后相加。 -Sum:在根据公式计算时,对于所需要的单元格数值,不能简单地从table里读取,而是要通过get操作来实现,因为那个单元格可能存在公式且未更新。 +Sum:对Exp的对应位置赋值,然后调用Get。 -[Leetcode Link](https://leetcode.com/problems/design-excel-sum-formula) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/design-excel-sum-formula) From 82155d1fa0dc8fda90ff68996a5f07dda76593d5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 9 Feb 2022 00:12:20 -0800 Subject: [PATCH 0478/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c0ae7f860..4bdeb1bae 100644 --- a/Readme.md +++ b/Readme.md @@ -290,7 +290,7 @@ [716.Max-Stack](https://github.com/wisdompeak/LeetCode/tree/master/Design/716.Max-Stack) (M+) [355.Design-Twitter](https://github.com/wisdompeak/LeetCode/tree/master/Design/355.Design-Twitter) (H) [535.Encode-and-Decode-TinyURL](https://github.com/wisdompeak/LeetCode/tree/master/Design/535.Encode-and-Decode-TinyURL) (M) -[631.Design-Excel-Sum-Formula](https://github.com/wisdompeak/LeetCode/tree/master/Design/631.Design-Excel-Sum-Formula) (H) +[631.Design-Excel-Sum-Formula](https://github.com/wisdompeak/LeetCode/tree/master/Design/631.Design-Excel-Sum-Formula) (H-) [642.Design-Search-Autocomplete-System](https://github.com/wisdompeak/LeetCode/tree/master/Design/642.Design-Search-Autocomplete-System) (M+) [895.Maximum-Frequency-Stack](https://github.com/wisdompeak/LeetCode/tree/master/Design/895.Maximum-Frequency-Stack) (H) [1146.Snapshot-Array](https://github.com/wisdompeak/LeetCode/tree/master/Design/1146.Snapshot-Array) (H) From 33c2d057b6e9c3ebc7fbdc50c2c59a50e0cce9b0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 9 Feb 2022 00:12:48 -0800 Subject: [PATCH 0479/2729] Update 631.Design-Excel-Sum-Formula.cpp --- .../631.Design-Excel-Sum-Formula.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Design/631.Design-Excel-Sum-Formula/631.Design-Excel-Sum-Formula.cpp b/Design/631.Design-Excel-Sum-Formula/631.Design-Excel-Sum-Formula.cpp index c2d80eccc..573969365 100644 --- a/Design/631.Design-Excel-Sum-Formula/631.Design-Excel-Sum-Formula.cpp +++ b/Design/631.Design-Excel-Sum-Formula/631.Design-Excel-Sum-Formula.cpp @@ -1,24 +1,24 @@ class Excel { - int Table[27][26]; + int Val[27][26]; vector Exp[27][26]; public: Excel(int H, char W) { for (int i=0; i<27; i++) for (int j=0; j<26; j++) - Table[i][j] = 0; + Val[i][j] = 0; } void set(int r, char c, int v) { - Table[r][c-'A']=v; + Val[r][c-'A']=v; Exp[r][c-'A'].clear(); } int get(int r, char c) { if (Exp[r][c-'A'].empty()) - return Table[r][c-'A']; + return Val[r][c-'A']; else { int ret = 0; From cd3f3fa3c6392ce8afacd652c209db0f537589e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 9 Feb 2022 00:30:27 -0800 Subject: [PATCH 0480/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 4bdeb1bae..75c847c00 100644 --- a/Readme.md +++ b/Readme.md @@ -290,7 +290,7 @@ [716.Max-Stack](https://github.com/wisdompeak/LeetCode/tree/master/Design/716.Max-Stack) (M+) [355.Design-Twitter](https://github.com/wisdompeak/LeetCode/tree/master/Design/355.Design-Twitter) (H) [535.Encode-and-Decode-TinyURL](https://github.com/wisdompeak/LeetCode/tree/master/Design/535.Encode-and-Decode-TinyURL) (M) -[631.Design-Excel-Sum-Formula](https://github.com/wisdompeak/LeetCode/tree/master/Design/631.Design-Excel-Sum-Formula) (H-) +[631.Design-Excel-Sum-Formula](https://github.com/wisdompeak/LeetCode/tree/master/Design/631.Design-Excel-Sum-Formula) (M+) [642.Design-Search-Autocomplete-System](https://github.com/wisdompeak/LeetCode/tree/master/Design/642.Design-Search-Autocomplete-System) (M+) [895.Maximum-Frequency-Stack](https://github.com/wisdompeak/LeetCode/tree/master/Design/895.Maximum-Frequency-Stack) (H) [1146.Snapshot-Array](https://github.com/wisdompeak/LeetCode/tree/master/Design/1146.Snapshot-Array) (H) From abc080f20f5408251842b9e2038cd086c12aba04 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 9 Feb 2022 23:30:51 -0800 Subject: [PATCH 0481/2729] Create 2152.Minimum-Number-of-Lines-to-Cover-Points.cpp --- ...inimum-Number-of-Lines-to-Cover-Points.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/2152.Minimum-Number-of-Lines-to-Cover-Points.cpp diff --git a/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/2152.Minimum-Number-of-Lines-to-Cover-Points.cpp b/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/2152.Minimum-Number-of-Lines-to-Cover-Points.cpp new file mode 100644 index 000000000..99246b1ee --- /dev/null +++ b/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/2152.Minimum-Number-of-Lines-to-Cover-Points.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + int minimumLines(vector>& points) + { + int n = points.size(); + vectordp(1<0; subset=(subset-1)&state) + { + dp[state] = min(dp[state], dp[subset] + dp[state-subset]); + } + } + + return dp[(1<>& points, int state) + { + vectortemp; + for (int i=0; i Date: Wed, 9 Feb 2022 23:41:42 -0800 Subject: [PATCH 0482/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 75c847c00..cac8e609d 100644 --- a/Readme.md +++ b/Readme.md @@ -727,6 +727,7 @@ [1494.Parallel-Courses-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1494.Parallel-Courses-II) (H) [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) [1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks) (M+) + [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) * ``带权二分图`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From 962e98a7a066e7ce86b12478f9b64c04f3a56046 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 9 Feb 2022 23:53:26 -0800 Subject: [PATCH 0483/2729] Update Readme.md --- Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index cac8e609d..4c30758ce 100644 --- a/Readme.md +++ b/Readme.md @@ -765,11 +765,11 @@ [1284.Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1284.Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix) (M+) [1452.People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1452.People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List) (H-) [1601.Maximum-Number-of-Achievable-Transfer-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1601.Maximum-Number-of-Achievable-Transfer-Requests) (H-) -[1755.Closest-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1755.Closest-Subsequence-Sum) (H) -[2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) [2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) (M) [2151.Maximum-Good-People-Based-on-Statements](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements) (M+) - + * ``Meet in the Middle`` + [1755.Closest-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1755.Closest-Subsequence-Sum) (H) + [2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) #### [Divide and Conquer](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer) [315.Count-of-Smaller-Numbers-After-Self](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self) (H-) From 75ec05d00bef77ed2b73cc72738beb22b1054cf1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 10 Feb 2022 00:35:46 -0800 Subject: [PATCH 0484/2729] Create Readme.md --- .../2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md diff --git a/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md b/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md new file mode 100644 index 000000000..a393f89c7 --- /dev/null +++ b/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md @@ -0,0 +1,7 @@ +### 2152.Minimum-Number-of-Lines-to-Cover-Points + +从本题的数据规模n<=10来看,用bit mask暴力穷举是正解。我们用一个二进制数state来表示一组点的集合,dp[state]表示这些点最少能用多少条直线覆盖。 + +如果state的所有点都在一条直线上,那么必然是```dp[state]=1```. 否则的话,这个点集的最优解是需要两条或者更多的直线来覆盖,我们必然可以将这些直线和对应的点归并出两组。这意味着必然有一种方法可以将state分为A子集和B子集,使得```dp[state]=dp[A]+dp[B]```,所以我们只需要枚举state的子集subset,那么```dp[state] = min{dp[subste] + dp[state-subset]}```. + +所以本题的解法是:从小到大遍历所有的状态state,对于每个状态dp[state],考察它的子集subset和补集(注意dp[subset]必然已经是已知的)。dp[state]要么是1,要么就是两个子集状态之和。 From 732c60732b926004a19bf614386b8c649d7297fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 10 Feb 2022 00:36:15 -0800 Subject: [PATCH 0485/2729] Update Readme.md --- .../2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md b/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md index a393f89c7..456deb4b9 100644 --- a/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md +++ b/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points/Readme.md @@ -4,4 +4,4 @@ 如果state的所有点都在一条直线上,那么必然是```dp[state]=1```. 否则的话,这个点集的最优解是需要两条或者更多的直线来覆盖,我们必然可以将这些直线和对应的点归并出两组。这意味着必然有一种方法可以将state分为A子集和B子集,使得```dp[state]=dp[A]+dp[B]```,所以我们只需要枚举state的子集subset,那么```dp[state] = min{dp[subste] + dp[state-subset]}```. -所以本题的解法是:从小到大遍历所有的状态state,对于每个状态dp[state],考察它的子集subset和补集(注意dp[subset]必然已经是已知的)。dp[state]要么是1,要么就是两个子集状态之和。 +所以本题的解法是:从小到大遍历所有的状态state,对于每个状态dp[state],考察它的子集subset和补集(注意dp[subset]必然已经是已知的)。dp[state]要么是1,要么就是两个子集状态之和(取最小值)。 From 10a5112eddfab5d099b9c602328bea21c1599510 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 10 Feb 2022 10:27:31 -0800 Subject: [PATCH 0486/2729] Create 416.Partition-Equal-Subset-Sum_dfs_v1.cpp --- .../416.Partition-Equal-Subset-Sum_dfs_v1.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v1.cpp diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v1.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v1.cpp new file mode 100644 index 000000000..5c59cc416 --- /dev/null +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v1.cpp @@ -0,0 +1,29 @@ +class Solution { + unordered_setvisited; +public: + bool canPartition(vector& nums) + { + int sum = accumulate(nums.begin(), nums.end(), 0); + sort(nums.rbegin(), nums.rend()); + if (sum%2!=0) return false; + return dfs(nums, 0, 0, sum/2); + } + + bool dfs(vector& nums, int cur, int curSum, int targetSum) + { + if (curSum == targetSum) return true; + if (curSum > targetSum) return false; + int hash = curSum * 20005 + cur; + if (visited.find(hash)!=visited.end()) + return false; + + for (int i=cur; icur && nums[i]==nums[i-1]) continue; + if (dfs(nums, i+1, curSum+nums[i], targetSum)) + return true; + } + visited.insert(hash); + return false; + } +}; From 6e3ba1cf30262fd20274564e5fd1e80d687fb5e5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 10 Feb 2022 10:32:50 -0800 Subject: [PATCH 0487/2729] Create 416.Partition-Equal-Subset-Sum_dfs_v2.cpp --- .../416.Partition-Equal-Subset-Sum_dfs_v2.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp new file mode 100644 index 000000000..0329802fe --- /dev/null +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp @@ -0,0 +1,32 @@ +class Solution { + unordered_setvisited; +public: + bool canPartition(vector& nums) + { + int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum%2!=0) return false; + return dfs(nums, sum/2, 0, 0); + } + + bool dfs(vector& nums, int targetSum, int i, int sum) + { + int hash = sum * 20005 + i; + if (visited.find(hash)!=visited.end()) + return false; + + if (sum== targetSum) + return true; + + if (sum> targetSum) + return false; + + if (i == nums.size()) + return false; + + if (dfs(nums, targetSum, i + 1, sum+ nums[i]) || dfs(nums, targetSum, i + 1, sum)) + return true; + + visited.insert(hash); + return false; + } +}; From efa9557191bedb486482d0c1d1d1b5870d8205fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 10 Feb 2022 10:44:04 -0800 Subject: [PATCH 0488/2729] Update 416.Partition-Equal-Subset-Sum_dfs_v1.cpp --- .../416.Partition-Equal-Subset-Sum_dfs_v1.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v1.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v1.cpp index 5c59cc416..f111f0e1f 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v1.cpp +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v1.cpp @@ -4,22 +4,28 @@ class Solution { bool canPartition(vector& nums) { int sum = accumulate(nums.begin(), nums.end(), 0); - sort(nums.rbegin(), nums.rend()); + sort(nums.begin(), nums.end()); if (sum%2!=0) return false; return dfs(nums, 0, 0, sum/2); } bool dfs(vector& nums, int cur, int curSum, int targetSum) { - if (curSum == targetSum) return true; - if (curSum > targetSum) return false; - int hash = curSum * 20005 + cur; + int hash = curSum * 1000 + cur; if (visited.find(hash)!=visited.end()) return false; + if (curSum == targetSum) return true; + if (curSum > targetSum) return false; + if (cur==nums.size()) return false; + for (int i=cur; icur && nums[i]==nums[i-1]) continue; + if (i>cur && nums[i]==nums[i-1]) + { + visited.insert((curSum+nums[i])*1000 + i); + continue; + } if (dfs(nums, i+1, curSum+nums[i], targetSum)) return true; } From ef729c1249ead3ead47f1a94b5eeb5958a69e152 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 10 Feb 2022 10:44:15 -0800 Subject: [PATCH 0489/2729] Update 416.Partition-Equal-Subset-Sum_dfs_v2.cpp --- .../416.Partition-Equal-Subset-Sum_dfs_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp index 0329802fe..e55b27165 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp @@ -10,7 +10,7 @@ class Solution { bool dfs(vector& nums, int targetSum, int i, int sum) { - int hash = sum * 20005 + i; + int hash = sum * 1000 + i; if (visited.find(hash)!=visited.end()) return false; From 066ddae084f530d36db4d40eceab235943771665 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 11 Feb 2022 04:41:34 -0800 Subject: [PATCH 0490/2729] Update 956.Tallest-Billboard.cpp --- .../956.Tallest-Billboard/956.Tallest-Billboard.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/956.Tallest-Billboard/956.Tallest-Billboard.cpp b/Dynamic_Programming/956.Tallest-Billboard/956.Tallest-Billboard.cpp index e28cc18b2..201993fdd 100644 --- a/Dynamic_Programming/956.Tallest-Billboard/956.Tallest-Billboard.cpp +++ b/Dynamic_Programming/956.Tallest-Billboard/956.Tallest-Billboard.cpp @@ -15,7 +15,7 @@ class Solution { int j = diff+B; if (dp_temp[j]==-1) continue; - if (diff+x=-B) dp[j-x] = max(dp[j-x],dp_temp[j]); } } From f0f7b89c3cacca9c1d0e1ce6e85a0e94fa18cb2c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 11 Feb 2022 23:48:47 -0800 Subject: [PATCH 0491/2729] Create 2168.Unique-Substrings-With-Equal-Digit-Frequency.cpp --- ...-Substrings-With-Equal-Digit-Frequency.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 String/2168.Unique-Substrings-With-Equal-Digit-Frequency/2168.Unique-Substrings-With-Equal-Digit-Frequency.cpp diff --git a/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/2168.Unique-Substrings-With-Equal-Digit-Frequency.cpp b/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/2168.Unique-Substrings-With-Equal-Digit-Frequency.cpp new file mode 100644 index 000000000..6a3edd856 --- /dev/null +++ b/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/2168.Unique-Substrings-With-Equal-Digit-Frequency.cpp @@ -0,0 +1,42 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int equalDigitFrequency(string s) + { + vectorcount(10); + unordered_setSet; + + int n = s.size(); + for (int i=0; i Date: Fri, 11 Feb 2022 23:49:19 -0800 Subject: [PATCH 0492/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4c30758ce..29b45e8c6 100644 --- a/Readme.md +++ b/Readme.md @@ -808,6 +808,7 @@ [1698.Number-of-Distinct-Substrings-in-a-String](https://github.com/wisdompeak/LeetCode/tree/master/String/1698.Number-of-Distinct-Substrings-in-a-String) (H-) [1923.Longest-Common-Subpath](https://github.com/wisdompeak/LeetCode/tree/master/String/1923.Longest-Common-Subpath) (H) [2156.Find-Substring-With-Given-Hash-Value](https://github.com/wisdompeak/LeetCode/tree/master/String/2156.Find-Substring-With-Given-Hash-Value) (M) +[2168.Unique-Substrings-With-Equal-Digit-Frequency](https://github.com/wisdompeak/LeetCode/tree/master/String/2168.Unique-Substrings-With-Equal-Digit-Frequency) (M+) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) From 37c3890c48e23ac86862dd7b823bc8ff759c9f14 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 12 Feb 2022 00:04:05 -0800 Subject: [PATCH 0493/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 String/2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md diff --git a/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md b/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md new file mode 100644 index 000000000..e44e063d4 --- /dev/null +++ b/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md @@ -0,0 +1,9 @@ +### 2168.Unique-Substrings-With-Equal-Digit-Frequency + +从此题的数目局规模上来看,用N^2的时间来遍历所有的substring、并且判断是否符合要求是可行的。但比较难办的是如何判断这些子串是否是unique。因为N^2个字符串会占用N^3的空间,我们无法直接存下所有字符串再去重。 + +对于判定字符串重复,我们有固定的套路,那就是rolling hash,可以将任意长度的字符串编码为一个整数来存储。本题中需要注意的是,为了避免将"012"和"12"都哈希成同一个编码,我们可以将十进制的编码规则改为十一进制,这样字符0也会被编码。即 +```cpp +for (int j=i; j Date: Sun, 13 Feb 2022 13:50:49 -0800 Subject: [PATCH 0494/2729] Create 2172.Maximum-AND-Sum-of-Array_v1.cpp --- .../2172.Maximum-AND-Sum-of-Array_v1.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v1.cpp diff --git a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v1.cpp b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v1.cpp new file mode 100644 index 000000000..dc3dde47e --- /dev/null +++ b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v1.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int maximumANDSum(vector& nums, int numSlots) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + int m = pow(3, numSlots); + vector>dp(n+1, vector(m, INT_MIN/2)); + dp[0][0] = 0; + + int ret = 0; + for (int i=1; i<=n; i++) + for (int state = 0; state < m; state++) + { + for (int j=0; j=1) + dp[i][state] = max(dp[i][state], dp[i-1][state - pow(3,j)] + (nums[i]&(j+1))); + } + if (i==n) + ret = max(ret, dp[i][state]); + } + + return ret; + } + + bool filled(int state, int k) + { + for (int i=0; i Date: Sun, 13 Feb 2022 14:16:35 -0800 Subject: [PATCH 0495/2729] Create 2172.Maximum-AND-Sum-of-Array_v2.cpp --- .../2172.Maximum-AND-Sum-of-Array_v2.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v2.cpp diff --git a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v2.cpp b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v2.cpp new file mode 100644 index 000000000..e8c48460f --- /dev/null +++ b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v2.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int maximumANDSum(vector& nums, int numSlots) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + int m = pow(3, numSlots); + vector>dp(n+1, vector(m, INT_MIN/2)); + dp[0][0] = 0; + + int ret = 0; + + for (int state = 1; state < m; state++) + { + int i = 0; + int temp = state; + while (temp>0) + { + i+=temp%3; + temp/=3; + } + if (i>n) continue; + + for (int j=0; j=1) + { + dp[i][state] = max(dp[i][state], dp[i-1][state - pow(3,j)] + (nums[i]&(j+1))); + } + + } + if (i==n) + ret = max(ret, dp[i][state]); + } + + return ret; + } + + bool filled(int state, int k) + { + for (int i=0; i Date: Sun, 13 Feb 2022 14:17:08 -0800 Subject: [PATCH 0496/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 29b45e8c6..da5edc2a9 100644 --- a/Readme.md +++ b/Readme.md @@ -732,6 +732,7 @@ [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) [1947.Maximum-Compatibility-Score-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1947.Maximum-Compatibility-Score-Sum) (H) +[2172.Maximum-AND-Sum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array) (H) * ``Catalan`` [096.Unique-Binary-Search-Trees](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/096.Unique-Binary-Search-Trees) (M+) [1259.Handshakes-That-Don't-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1259.Handshakes-That-Don't-Cross) (M+) From 2553ffab3bd224c0328edb7fb1ed8c45203c3070 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Feb 2022 15:19:12 -0800 Subject: [PATCH 0497/2729] Create Readme.md --- .../2172.Maximum-AND-Sum-of-Array/Readme.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md diff --git a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md new file mode 100644 index 000000000..80d237a68 --- /dev/null +++ b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md @@ -0,0 +1,27 @@ +### 2172.Maximum-AND-Sum-of-Array + +本题看上像二分图匹配问题。左边是一堆数字,右边是一对slots,要求匹配的边权之和最大。但是标准的二分图匹配要求每条边不能有公共边,本题则是允许最多两条边共享一个slot节点。 + +同以往一样,我们不用KM算法来解决带权最大二分图匹配,我们也不考虑最小费用最大流的做法,这里依然用状态压缩DP。 + +一般我们有两种方案:1. 遍历slot,用状态来表示nums。2. 遍历nums,用状态来表示slot。 + +对于第一种方法,我们用二进制数state来表示那些数字已经被配对,于是dp[i][state]表达的是:用完第i个slot、配对了state所表示的数字集时,所得的最大价值。所以核心代码大致会是: +``` + for (int i=0; i Date: Sun, 13 Feb 2022 15:20:34 -0800 Subject: [PATCH 0498/2729] Update Readme.md --- Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md index 80d237a68..6688609f3 100644 --- a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md +++ b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md @@ -15,7 +15,7 @@ ``` 其中上式里的available plans比较复杂。因为slot里面可以放0个或者1个或者2个数字,所以需要在state所代表的数字集合里面任意挑选0个、1个、2个数字的组合,这个组合的大小可能会有C(18,2)的级别。综上三层循环的总复杂度会是:```9*(2^18)*C(18,2)```,这是1e8数量级的数字,会TLE。 -第二种方法,我们用三进制数state来表示所有slots的状态(三进制数的每个bit表示该slot里面已经装了0个、1个或2个数字)。于是dp[i][state]表达的是:用完第i个数字、配对了state所表示的slots时,所得的最大价值。所以核心代码大致会是: +第二种方法,我们用三进制数state来表示所有slots的匹配状态(三进制数的每个bit表示该slot里面已经装了0个、1个或2个数字)。于是dp[i][state]表达的是:用完第i个数字、配对了state所表示的slots时,所得的最大价值。所以核心代码大致会是: ``` for (int i=0; i Date: Sun, 13 Feb 2022 22:52:45 -0800 Subject: [PATCH 0499/2729] Create 2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp --- ...erations-to-Make-the-Array-Alternating.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp diff --git a/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp b/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp new file mode 100644 index 000000000..9a16afe30 --- /dev/null +++ b/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp @@ -0,0 +1,45 @@ +class Solution { + static bool cmp(pair&a,pair&b) + { + return a.second > b.second; + } +public: + int minimumOperations(vector& nums) + { + int n = nums.size(); + if (n==1) return 0; + + unordered_mapMap1; + unordered_mapMap2; + int count1 = 0, count2 = 0; + for (int i=0; i>temp2(Map2.begin(), Map2.end()); + sort(temp2.begin(), temp2.end(), cmp); + + int ret = n; + for (auto& x: Map1) + { + int key = x.first, freq = x.second; + int ans = count1-freq; + + if (temp2[0].first == key) + ans += count2 - (temp2.size()==1?0:temp2[1].second); + else + ans += count2 - temp2[0].second; + + ret = min(ret, ans); + } + + return ret; + } +}; From 344ea58d5cc335dc9eff1b4ed129bffd8384a331 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Feb 2022 23:07:42 -0800 Subject: [PATCH 0500/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/Readme.md diff --git a/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/Readme.md b/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/Readme.md new file mode 100644 index 000000000..6933cd07c --- /dev/null +++ b/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/Readme.md @@ -0,0 +1,7 @@ +### 2170.Minimum-Operations-to-Make-the-Array-Alternating + +我们将所有偶数位的数字和所有奇数位的数字分别进行频率统计,保存至数组Map1和Map2,并且按照频率从大到小排序。 + +如果Map1和Map2分别词频最高的数字不相同,那么意味着最优方案就是保留这两种数字。如果Map1和Map2分别词频最高的数字相同,那么要么保留Map1最高频的数字+Map2次高频的数字,或者保留Map1次高频的数字+Map2最高频的数字。 + +特别注意,Map1和Map2保存的数字种类可能只有1种,需要特别处理。 From b515962aaa14c5691778fc6d6a786efa7d24d5fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Feb 2022 23:08:19 -0800 Subject: [PATCH 0501/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index da5edc2a9..e666fd94e 100644 --- a/Readme.md +++ b/Readme.md @@ -1046,6 +1046,7 @@ [1911.Maximum-Alternating-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1911.Maximum-Alternating-Subsequence-Sum) (M+) [2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses) (M+) [2136.Earliest-Possible-Day-of-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom) (M+) +[2170.Minimum-Operations-to-Make-the-Array-Alternating](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From a473bb6d127fa916e65b34669feefd61adb811fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Feb 2022 23:09:26 -0800 Subject: [PATCH 0502/2729] Update 2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp --- ...erations-to-Make-the-Array-Alternating.cpp | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp b/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp index 9a16afe30..e5dcded84 100644 --- a/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp +++ b/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170.Minimum-Operations-to-Make-the-Array-Alternating.cpp @@ -23,23 +23,21 @@ class Solution { count2++; } + vector>temp1(Map1.begin(), Map1.end()); vector>temp2(Map2.begin(), Map2.end()); + sort(temp1.begin(), temp1.end(), cmp); sort(temp2.begin(), temp2.end(), cmp); - int ret = n; - for (auto& x: Map1) - { - int key = x.first, freq = x.second; - int ans = count1-freq; - - if (temp2[0].first == key) - ans += count2 - (temp2.size()==1?0:temp2[1].second); - else - ans += count2 - temp2[0].second; - - ret = min(ret, ans); + if (temp1.size()==1) temp1.push_back({0,0}); + if (temp2.size()==1) temp2.push_back({0,0}); + + if (temp1[0].first!=temp2[0].first) + return n - temp1[0].second - temp2[0].second; + else + { + int x = count1 - temp1[0].second + count2 - temp2[1].second; + int y = count1 - temp1[1].second + count2 - temp2[0].second; + return min(x,y); } - - return ret; } }; From 0218b15850d8915b3a419388b75c6f4df204df0f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Feb 2022 23:28:28 -0800 Subject: [PATCH 0503/2729] Create 2171.Removing-Minimum-Number-of-Magic-Beans.cpp --- ...Removing-Minimum-Number-of-Magic-Beans.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/2171.Removing-Minimum-Number-of-Magic-Beans.cpp diff --git a/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/2171.Removing-Minimum-Number-of-Magic-Beans.cpp b/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/2171.Removing-Minimum-Number-of-Magic-Beans.cpp new file mode 100644 index 000000000..74aac8c5b --- /dev/null +++ b/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/2171.Removing-Minimum-Number-of-Magic-Beans.cpp @@ -0,0 +1,29 @@ +using LL = long long; +class Solution { +public: + long long minimumRemoval(vector& beans) + { + sort(beans.rbegin(), beans.rend()); + int n = beans.size(); + + vectorpre(n); + pre[0] = beans[0]; + for (int i=1; isuf(n); + suf[n-1] = beans[n-1]; + for (int i=n-2; i>=0; i--) + suf[i] = suf[i+1]+(LL)beans[i]; + + LL ret = LLONG_MAX; + for (int i=0; i Date: Sun, 13 Feb 2022 23:29:01 -0800 Subject: [PATCH 0504/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e666fd94e..2f04353f2 100644 --- a/Readme.md +++ b/Readme.md @@ -1047,6 +1047,7 @@ [2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2086.Minimum-Number-of-Buckets-Required-to-Collect-Rainwater-from-Houses) (M+) [2136.Earliest-Possible-Day-of-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom) (M+) [2170.Minimum-Operations-to-Make-the-Array-Alternating](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating) (M+) +[2171.Removing-Minimum-Number-of-Magic-Beans](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans) (M) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 341d37e628c850e64045fdf0c456358ca9b358ab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Feb 2022 23:40:59 -0800 Subject: [PATCH 0505/2729] Create Readme.md --- .../2171.Removing-Minimum-Number-of-Magic-Beans/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/Readme.md diff --git a/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/Readme.md b/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/Readme.md new file mode 100644 index 000000000..4094fee2b --- /dev/null +++ b/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/Readme.md @@ -0,0 +1,6 @@ +### 2171.Removing-Minimum-Number-of-Magic-Beans + +本题的关键是我们要有直觉,最终所有袋子的统一的豆子数目,一定等于原始袋子里某一袋的数目。这可以用反证法说明。我们将所有的豆子按照从大到小的顺序排列,假设最优解对应的最终每袋豆子数是k,介于beans[i]和beans[i+1]之间,那么我们必然要把第i+1袋到最后一袋的豆子都拿走,同时将前i袋里每袋豆子都降至数目k。显然,这不会是最优解,因为我们如果将答案k上调为为beans[i],依然把第i+1袋到最后一袋的豆子都拿走,但前i袋豆子需要拿走的数目会变少。所以最终的k一定是某个beans[i]。 + +我们将beans从大到小排列之后,可以遍历一遍每个beans[i]查验如果它是最终解,那么需要移动的豆子总数包括两部分:前i袋需要移走```sum[0:i] - beans[i]*(i+1)```,后i袋需要全部拿走```sum[i+1:n-1]```。因此本题就是寻找```sum[0:n-1] - beans[i]*(i+1)```全局最小值所对应的i。 + From 3060bed42893612adf31ba344a51f9cd977b2c7f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Feb 2022 23:41:06 -0800 Subject: [PATCH 0506/2729] Update 2171.Removing-Minimum-Number-of-Magic-Beans.cpp --- ...Removing-Minimum-Number-of-Magic-Beans.cpp | 23 ++++--------------- 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/2171.Removing-Minimum-Number-of-Magic-Beans.cpp b/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/2171.Removing-Minimum-Number-of-Magic-Beans.cpp index 74aac8c5b..520ca7849 100644 --- a/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/2171.Removing-Minimum-Number-of-Magic-Beans.cpp +++ b/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans/2171.Removing-Minimum-Number-of-Magic-Beans.cpp @@ -4,25 +4,12 @@ class Solution { long long minimumRemoval(vector& beans) { sort(beans.rbegin(), beans.rend()); - int n = beans.size(); - - vectorpre(n); - pre[0] = beans[0]; - for (int i=1; isuf(n); - suf[n-1] = beans[n-1]; - for (int i=n-2; i>=0; i--) - suf[i] = suf[i+1]+(LL)beans[i]; - + LL total = accumulate(beans.begin(), beans.end(), 0LL); + LL ret = LLONG_MAX; - for (int i=0; i Date: Thu, 17 Feb 2022 17:42:31 -0800 Subject: [PATCH 0507/2729] Update 1774.Closest-Dessert-Cost.cpp --- .../1774.Closest-Dessert-Cost.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp b/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp index c8c42513f..9c31a6b97 100644 --- a/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp +++ b/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp @@ -1,16 +1,18 @@ class Solution { public: int closestCost(vector& baseCosts, vector& toppingCosts, int target) { - unordered_set toppingsSet; - - int n = toppingCosts.size(); - - for(int state = 0; state < (1 << (2 * n)); ++state) { + int m = toppingCosts.size(); + + unordered_set toppingsSet; + for(int state = 0; state < pow(3,m); ++state) + { + int s = state; int sum = 0; - for(int i = 0; i < n; ++i) { - int cur = (state >> (2 * i)) & 3; - if(!cur || cur == 3) continue; + for(int i = 0; i < m; ++i) + { + int cur = s%3; sum += toppingCosts[i] * cur; + s/=3; } toppingsSet.insert(sum); } From f55a70371cc12f9009c58d854cb5146257269dd3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 17 Feb 2022 17:45:35 -0800 Subject: [PATCH 0508/2729] Update Readme.md --- Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md b/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md index 83148fea5..9e6166530 100644 --- a/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md +++ b/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md @@ -1,7 +1,5 @@ ### 1774.Closest-Dessert-Cost -本题需要暴力枚举所有toppings的选配方案。这样的枚举对每种topping都在0,1,2中选择,并没有任何优化、剪支的空间,所以相比于DFS的递归做法(需要递归十次),用bit mask来说更为方便。 +本题需要暴力枚举所有toppings的选配方案。枚举时对每种topping的数量都在0,1,2中选择,所以可以将topping的组合用一个含有m个bit的三进制数表示。我们对0到3^m进行循环,查看每个三进制数所对应的topping组合方案需要的cost,记录在toppingsSet里去重,并对按照从小到大排序。 -我们注意要toppings只有十种,如果用每两个bit位来表示一种topping的方案(00,01,10,11),那么总共需要20个bit位。注意到01和10都可以用来表示该topping选择一份。尽管有些状态的数目上有些浪费,但即使如此,考虑2^20是1e6量级,这样的暴力是可以接收的。 - -我们将所有的toppings的选配方案去重后按照从小到大排序。当我们遍历base时,我们希望找与target-base最接近的topping,这里就可以用二分搜索。 +然后我们遍历base,显然我们在toppingsSet里希望找与target-base最接近的topping,这里就可以用二分搜索。 From 65565ad07b05d8b34afde25654a28ce505530702 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 17 Feb 2022 20:39:24 -0800 Subject: [PATCH 0509/2729] Update Readme.md --- .../1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md b/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md index 6bcc44dfb..cbca3c02d 100644 --- a/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md +++ b/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md @@ -19,7 +19,6 @@ for (int i=0; i Date: Thu, 17 Feb 2022 20:44:58 -0800 Subject: [PATCH 0510/2729] Update Readme.md --- .../Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md b/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md index cbca3c02d..86f8b7784 100644 --- a/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md +++ b/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md @@ -18,7 +18,8 @@ for (int i=0; i Date: Thu, 17 Feb 2022 20:45:27 -0800 Subject: [PATCH 0511/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2f04353f2..9c8eedaf3 100644 --- a/Readme.md +++ b/Readme.md @@ -716,7 +716,6 @@ [1349.Maximum-Students-Taking-Exam](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1349.Maximum-Students-Taking-Exam) (H) [1411.Number-of-Ways-to-Paint-N×3-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1411.Number-of-Ways-to-Paint-N%C3%973-Grid) (M) [1434.Number-of-Ways-to-Wear-Different-Hats-to-Each-Other](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1434.Number-of-Ways-to-Wear-Different-Hats-to-Each-Other) (H-) -[1595.Minimum-Cost-to-Connect-Two-Groups-of-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points) (H) [1659.Maximize-Grid-Happiness](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1659.Maximize-Grid-Happiness) (H) [1681.Minimum-Incompatibility](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1681.Minimum-Incompatibility) (H) [1723.Find-Minimum-Time-to-Finish-All-Jobs](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1723.Find-Minimum-Time-to-Finish-All-Jobs) (H-) @@ -730,6 +729,7 @@ [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) * ``带权二分图`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) +[1595.Minimum-Cost-to-Connect-Two-Groups-of-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points) (H) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) [1947.Maximum-Compatibility-Score-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1947.Maximum-Compatibility-Score-Sum) (H) [2172.Maximum-AND-Sum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array) (H) From 974201c2fbe21d71205cbc424f340949724b8afb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 17 Feb 2022 21:59:14 -0800 Subject: [PATCH 0512/2729] Update 1595.Minimum-Cost-to-Connect-Two-Groups-of-Points.cpp --- ...m-Cost-to-Connect-Two-Groups-of-Points.cpp | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points.cpp b/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points.cpp index 63bc8eb72..f3bb3218a 100644 --- a/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points.cpp +++ b/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points.cpp @@ -1,24 +1,28 @@ class Solution { - int dp[12][1<<12]; public: int connectTwoGroups(vector>& cost) { int m = cost.size(); int n = cost[0].size(); - - dp[0][0] = INT_MAX/2; - for (int state = 1; state < (1<>dp(m+1, vector(1<>cost2(m+1, vector(1<>j)&1)==1) - sum += cost[0][j]; + int sum = 0; + for (int j=0; j>j)&1)==1) + sum += cost[i][j]; + } + cost2[i][state] = sum; } - dp[0][state] = sum; - } - - for (int i=1; i0; subset=(subset-1)&state) { - int sum = 0; - for (int j=0; j>j)&1)==1) - sum += cost[i][j]; - } - dp[i][state] = min(dp[i][state], dp[i-1][state-subset]+sum); + dp[i][state] = min(dp[i][state], dp[i-1][state-subset] + cost2[i][subset]); } - + int minPath = INT_MAX; for (int j=0; j Date: Thu, 17 Feb 2022 22:01:07 -0800 Subject: [PATCH 0513/2729] Update Readme.md --- .../1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md b/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md index 86f8b7784..a1e1c4430 100644 --- a/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md +++ b/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points/Readme.md @@ -24,7 +24,7 @@ for (int i=0; i Date: Thu, 17 Feb 2022 23:07:41 -0800 Subject: [PATCH 0514/2729] Update 1774.Closest-Dessert-Cost.cpp --- .../1774.Closest-Dessert-Cost.cpp | 57 ++++++------------- 1 file changed, 17 insertions(+), 40 deletions(-) diff --git a/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp b/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp index 9c31a6b97..9747dd2af 100644 --- a/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp +++ b/Bit_Manipulation/1774.Closest-Dessert-Cost/1774.Closest-Dessert-Cost.cpp @@ -3,52 +3,29 @@ class Solution { int closestCost(vector& baseCosts, vector& toppingCosts, int target) { int m = toppingCosts.size(); - unordered_set toppingsSet; - for(int state = 0; state < pow(3,m); ++state) - { - int s = state; - int sum = 0; - for(int i = 0; i < m; ++i) - { - int cur = s%3; - sum += toppingCosts[i] * cur; - s/=3; - } - toppingsSet.insert(sum); - } - vectortoppings(toppingsSet.begin(), toppingsSet.end()); - sort(toppings.begin(), toppings.end()); - int ret = INT_MAX; int ret_diff = INT_MAX; - for(int base: baseCosts) { - int targetTopping = target - base; - - auto iter = lower_bound(toppings.begin(), toppings.end(), targetTopping); - if (iter!=toppings.end()) + + for (int base: baseCosts) + for(int state = 0; state < pow(3,m); ++state) { - int cand = *iter; - if (abs(base+cand-target) < ret_diff) + int s = state; + int topping = 0; + for(int i = 0; i < m; ++i) { - ret = base+cand; - ret_diff = abs(base+cand-target); - } - else if (abs(base+cand-target) == ret_diff && base+cand < ret) - ret = base+cand; - } - - if (iter!=toppings.begin()) - { - int cand = *prev(iter); - if (abs(base+cand-target) < ret_diff) + int cur = s%3; + topping += toppingCosts[i] * cur; + s/=3; + } + + if (abs(base+topping-target) < ret_diff) { - ret = base+cand; - ret_diff = abs(base+cand-target); + ret = base+topping; + ret_diff = abs(base+topping-target); } - else if (abs(base+cand-target) == ret_diff && base+cand < ret) - ret = base+cand; - } - } + else if (abs(base+topping-target) == ret_diff && base+topping < ret) + ret = base+topping; + } return ret; } From 6ee773e64599238c8cd5aa34fe25faac41a5c1b4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 17 Feb 2022 23:08:42 -0800 Subject: [PATCH 0515/2729] Update Readme.md --- Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md b/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md index 9e6166530..81ea71452 100644 --- a/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md +++ b/Bit_Manipulation/1774.Closest-Dessert-Cost/Readme.md @@ -2,4 +2,4 @@ 本题需要暴力枚举所有toppings的选配方案。枚举时对每种topping的数量都在0,1,2中选择,所以可以将topping的组合用一个含有m个bit的三进制数表示。我们对0到3^m进行循环,查看每个三进制数所对应的topping组合方案需要的cost,记录在toppingsSet里去重,并对按照从小到大排序。 -然后我们遍历base,显然我们在toppingsSet里希望找与target-base最接近的topping,这里就可以用二分搜索。 +记得我们仍然需要遍历base. 总的时间复杂度是```o(m*3^n)```,大概是6e5,是可以接受的。 From 01e4896ddeeeefee24ee7bb9e7c484058b84e9f7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 17 Feb 2022 23:09:27 -0800 Subject: [PATCH 0516/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9c8eedaf3..6b514cd8a 100644 --- a/Readme.md +++ b/Readme.md @@ -80,7 +80,6 @@ 1201.Ugly-Number-III (TBD) [1533.Find-the-Index-of-the-Large-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1533.Find-the-Index-of-the-Large-Integer) (M) [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) -[1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) @@ -766,6 +765,7 @@ [1284.Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1284.Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix) (M+) [1452.People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1452.People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List) (H-) [1601.Maximum-Number-of-Achievable-Transfer-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1601.Maximum-Number-of-Achievable-Transfer-Requests) (H-) +[1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) (M) [2151.Maximum-Good-People-Based-on-Statements](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements) (M+) * ``Meet in the Middle`` From 1d246d1c207b5143c876d658b5358c0c81092953 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Feb 2022 15:59:47 -0800 Subject: [PATCH 0517/2729] Create 2179.Count-Good-Triplets-in-an-Array.cpp --- .../2179.Count-Good-Triplets-in-an-Array.cpp | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Segment_Tree/2179.Count-Good-Triplets-in-an-Array/2179.Count-Good-Triplets-in-an-Array.cpp diff --git a/Segment_Tree/2179.Count-Good-Triplets-in-an-Array/2179.Count-Good-Triplets-in-an-Array.cpp b/Segment_Tree/2179.Count-Good-Triplets-in-an-Array/2179.Count-Good-Triplets-in-an-Array.cpp new file mode 100644 index 000000000..ff8182c6a --- /dev/null +++ b/Segment_Tree/2179.Count-Good-Triplets-in-an-Array/2179.Count-Good-Triplets-in-an-Array.cpp @@ -0,0 +1,76 @@ +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; + long long M = 1e9+7; + + BIT(int N) + { + this->N = N; + bitArr.resize(N+1); + nums.resize(N+1); + } + + // increase nums[i] by delta + void updateDelta(int i, long long delta) { + int idx = i; + while (idx <= N) + { + bitArr[idx]+=delta; + bitArr[idx] %= M; + idx+=idx&(-idx); + } + } + + // sum of a range nums[1:j] inclusively + long long queryPreSum(int idx){ + long long result = 0; + while (idx){ + result += bitArr[idx]; + result %= M; + idx-=idx&(-idx); + } + return result; + } + + // sum of a range nums[i:j] inclusively + long long sumRange(int i, int j) { + return queryPreSum(j)-queryPreSum(i-1); + } +}; + +class Solution { +public: + long long goodTriplets(vector& nums1, vector& nums2) + { + int n = nums1.size(); + unordered_mapMap; + for (int i=0; ismallerBefore(n,0); + BIT bit1(100005); + for (int i=0; ilargerAfter(n,0); + BIT bit2(100005); + for (int i=n-1; i>=0; i--) + { + largerAfter[i] = bit2.sumRange(nums2[i], 100000); + bit2.updateDelta(nums2[i], 1); + } + + long long ret = 0; + for (int i=0; i Date: Sat, 19 Feb 2022 16:00:13 -0800 Subject: [PATCH 0518/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6b514cd8a..637aa3cf7 100644 --- a/Readme.md +++ b/Readme.md @@ -279,6 +279,7 @@ [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) [1649.Create-Sorted-Array-through-Instructions](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions) (H) [2031.Count-Subarrays-With-More-Ones-Than-Zeros](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros) (H) +[2179.Count-Good-Triplets-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2179.Count-Good-Triplets-in-an-Array) (H) #### [Design](https://github.com/wisdompeak/LeetCode/tree/master/Design) [146.LRU-Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/146.LRU-Cache) (H-) From a6b1dee719ab3292daa40c11160870f898d968ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Feb 2022 16:03:41 -0800 Subject: [PATCH 0519/2729] Update BIT.cpp --- Template/Binary_Index_Tree/BIT.cpp | 39 ++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/Template/Binary_Index_Tree/BIT.cpp b/Template/Binary_Index_Tree/BIT.cpp index e79ada3b0..98f5421a0 100644 --- a/Template/Binary_Index_Tree/BIT.cpp +++ b/Template/Binary_Index_Tree/BIT.cpp @@ -1,15 +1,21 @@ -const int MAX_N = 100000; - -class Solution { -public: - long long bitArr[MAX_N+1]; - long long nums[MAX_N+1]; // Note: nums is 1-index +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; long long M = 1e9+7; + + BIT(int N) + { + this->N = N; + bitArr.resize(N+1); + nums.resize(N+1); + } - // increase nums[i] by delta (1-index) + // increase nums[i] by delta void updateDelta(int i, long long delta) { int idx = i; - while (idx <= MAX_N) + while (idx <= N) { bitArr[idx]+=delta; bitArr[idx] %= M; @@ -17,7 +23,7 @@ class Solution { } } - // sum of a range nums[1:j] inclusively, 1-index + // sum of a range nums[1:j] inclusively long long queryPreSum(int idx){ long long result = 0; while (idx){ @@ -31,5 +37,18 @@ class Solution { // sum of a range nums[i:j] inclusively long long sumRange(int i, int j) { return queryPreSum(j)-queryPreSum(i-1); - } + } }; + +int main() +{ + int N = 100000; + BIT bit(N); + vectornums(N); + // cin>> nums .... + + for (int i=1; i Date: Sat, 19 Feb 2022 16:35:38 -0800 Subject: [PATCH 0520/2729] Create Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Segment_Tree/2179.Count-Good-Triplets-in-an-Array/Readme.md diff --git a/Segment_Tree/2179.Count-Good-Triplets-in-an-Array/Readme.md b/Segment_Tree/2179.Count-Good-Triplets-in-an-Array/Readme.md new file mode 100644 index 000000000..43f73e085 --- /dev/null +++ b/Segment_Tree/2179.Count-Good-Triplets-in-an-Array/Readme.md @@ -0,0 +1,18 @@ +### 2179.Count-Good-Triplets-in-an-Array + +本题的入手思路如下。我们容易确定相同数字在两个数组中的位置,类似nums1[i]==nums2[j] +``` +X X X i X X X X X X X +X X X X X X j X X X X +``` +自然地,我们希望知道有多少```x>i```和```y>j```,使得nums1[x]==nums2[y]. 比较暴力的方法是遍历大于i的所有位置x,查看nums[j+1:n-1]区间内是否有与nums1[x]相同的数。但从这个算法来看并没有优化的空间,因为能有多少配对完全是随机事件。如何更高效地去做呢? + +考虑到所有的元素都互不相同,这里有一个技巧:因为我们对nums1里面的元素大小并不关心,我们其实可以只看编号不看数值,这样nums1在我们眼里可以就只是```0,1,2,3...,```,这样就构建了一个映射。将nums1所做的映射也应用在nums2里面,则nums2重新变换成了一个新的乱序排列。这里就发现了规律,变换后nums1里面在i后面的元素,意味着在nums2里面必然都比nums[j]的数值大。反过来说,nums2里那些比nums2[j]大的数,意味着在nums1里时一定排在i后面。所以我们需要根据nums2[j]计算一个新数组largerAfterSelf[j],表示nums2[j]后面有多少元素比自己大,那么这些元素必然也存在于nums1[i]的后面。 + +同理,我们可以构造smallerBeforeSelf[j],表示nums2[j]前面有多少元素比自己小,那么这些元素必然也存在于nums1[i]的后面。 + +最终的答案就是```sum{smallerBeforeSelf[j] * largerAfterSelf[j]}, for i=0,1,2,..,n-1```. 这个思路在```1713.Minimum-Operations-to-Make-a-Subsequence```里也有应用。 + +计算largerAfterSelf的方法同```315.Count-of-Smaller-Numbers-After-Self```,可以用分治+归并排序,也可以套用树状数组。 + +对于BIT的解法,我们注意到所有数值的大小不超过1e5,所以开辟长度为1e5的树状数组作为篮子,每考察nums[i],就需要在树状数组的[nums[i]+1: INT_MAX]区间内累加所有的数据之和,这个就是largerAfterSelf[i]. 之后记得在idex = nums[i]的位置自增1. From ccb314e38c590cf747badd8bac4dddee38237dea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 20 Feb 2022 22:56:43 -0800 Subject: [PATCH 0521/2729] Create 2183.Count-Array-Pairs-Divisible-by-K.cpp --- .../2183.Count-Array-Pairs-Divisible-by-K.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Math/2183.Count-Array-Pairs-Divisible-by-K/2183.Count-Array-Pairs-Divisible-by-K.cpp diff --git a/Math/2183.Count-Array-Pairs-Divisible-by-K/2183.Count-Array-Pairs-Divisible-by-K.cpp b/Math/2183.Count-Array-Pairs-Divisible-by-K/2183.Count-Array-Pairs-Divisible-by-K.cpp new file mode 100644 index 000000000..610da6394 --- /dev/null +++ b/Math/2183.Count-Array-Pairs-Divisible-by-K/2183.Count-Array-Pairs-Divisible-by-K.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + long long countPairs(vector& nums, int k) + { + unordered_setyueshu; + for (int i=1; i*i<=k; i++) + { + if (k%i!=0) continue; + yueshu.insert(i); + if (i*i!=k) + yueshu.insert(k/i); + } + + unordered_map>Map; + for (int i=0; i Date: Sun, 20 Feb 2022 23:00:29 -0800 Subject: [PATCH 0522/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 637aa3cf7..7e49e0915 100644 --- a/Readme.md +++ b/Readme.md @@ -949,6 +949,7 @@ [1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Math/1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation) (H) [1969.Minimum-Non-Zero-Product-of-the-Array-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/1969.Minimum-Non-Zero-Product-of-the-Array-Elements) (M+) [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) +[2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) From f7a7738dbf33dbb053159ae43e53879cc3b8c277 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 20 Feb 2022 23:41:17 -0800 Subject: [PATCH 0523/2729] Create Readme.md --- Math/2183.Count-Array-Pairs-Divisible-by-K/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Math/2183.Count-Array-Pairs-Divisible-by-K/Readme.md diff --git a/Math/2183.Count-Array-Pairs-Divisible-by-K/Readme.md b/Math/2183.Count-Array-Pairs-Divisible-by-K/Readme.md new file mode 100644 index 000000000..cd48274dc --- /dev/null +++ b/Math/2183.Count-Array-Pairs-Divisible-by-K/Readme.md @@ -0,0 +1,7 @@ +### 2183.Count-Array-Pairs-Divisible-by-K + +一个比较常见的思想就是遍历nums[i],高效查找那些nums[j]可以与之相乘能被k整除。 + +要使得两数相乘能够被k整除,关键在于两个数字里包含了多少k的约数,其他的约数对于我们没有意义。所以对于nums[i]而言,我们只关注nums[i]与k的最大公约数,令```a = gcd(nums[i],k)```,则nums[j]只要(且必须)含有约数```b=k/a```,那么就可以与nums[i]配对乘积能被k整除。假设我们将nums里所有含有约数b的index都存下来,那么就可以通过二分查找,找到位置i之后有多少nums[j]满足条件。所以整个时间复杂度就是NlogN,第一个N是遍历i,第二个logN是在含有约数b的元素数组里做二分定位。 + +在上述的主框架之外,我们需要如下预处理:首先计算k的所有约数,放入集合yueshu。然后遍历所有元素nums[i]和yueshu集合的元素x,查看nums[i]是否能被x整除,是的话就将i加入Map[x]。Map的key是k的所有约数,val是有哪些nums包含了对应的约数。这里需要注意的是,1e5以内含有约数最多的自然数是83160,只有128个因子。所以预处理的时间复杂度是o(128N). From cdc02cd093dce58eabf38e645b5d29b04039fe05 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 21 Feb 2022 10:43:05 -0800 Subject: [PATCH 0524/2729] Create 2182.Construct-String-With-Repeat-Limit.cpp --- ...182.Construct-String-With-Repeat-Limit.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Greedy/2182.Construct-String-With-Repeat-Limit/2182.Construct-String-With-Repeat-Limit.cpp diff --git a/Greedy/2182.Construct-String-With-Repeat-Limit/2182.Construct-String-With-Repeat-Limit.cpp b/Greedy/2182.Construct-String-With-Repeat-Limit/2182.Construct-String-With-Repeat-Limit.cpp new file mode 100644 index 000000000..493ad5322 --- /dev/null +++ b/Greedy/2182.Construct-String-With-Repeat-Limit/2182.Construct-String-With-Repeat-Limit.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + string repeatLimitedString(string s, int repeatLimit) + { + unordered_mapMap; + for (auto ch: s) + Map[ch]++; + + priority_queue>pq; + + for (auto x:Map) + pq.push(x); + + string ret; + while (!pq.empty()) + { + auto x = pq.top(); + pq.pop(); + int k = min(x.second, repeatLimit); + for (int i=0; i Date: Mon, 21 Feb 2022 10:43:41 -0800 Subject: [PATCH 0525/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7e49e0915..d1ba45485 100644 --- a/Readme.md +++ b/Readme.md @@ -1050,6 +1050,7 @@ [2136.Earliest-Possible-Day-of-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2136.Earliest-Possible-Day-of-Full-Bloom) (M+) [2170.Minimum-Operations-to-Make-the-Array-Alternating](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating) (M+) [2171.Removing-Minimum-Number-of-Magic-Beans](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans) (M) +[2182.Construct-String-With-Repeat-Limit](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2182.Construct-String-With-Repeat-Limit) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 948b6d094b489d241d7561fa5f8fb05c12499d74 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 21 Feb 2022 10:50:34 -0800 Subject: [PATCH 0526/2729] Create Readme.md --- Greedy/2182.Construct-String-With-Repeat-Limit/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 Greedy/2182.Construct-String-With-Repeat-Limit/Readme.md diff --git a/Greedy/2182.Construct-String-With-Repeat-Limit/Readme.md b/Greedy/2182.Construct-String-With-Repeat-Limit/Readme.md new file mode 100644 index 000000000..fe32e44e6 --- /dev/null +++ b/Greedy/2182.Construct-String-With-Repeat-Limit/Readme.md @@ -0,0 +1,6 @@ +### 2182.Construct-String-With-Repeat-Limit + +非常直观的贪心策略。所有的字母统计频次之后,按照字典序从大到小放入pq里。有这么几种情况: +1. 最大的字母少于或者等于repeatLimit个,那么就将其全部取出。 +2. 最大的字母有多于repeatLimit个,那么就取出repeatLimit个,同时再取次大的字母一个。将最大和次大字母再塞入pq中(如果还有的话)。 +3. 最大的字母有多于repeatLimit个,那么就取出repeatLimit个,此时pq里没有次大的字母,就直接返回。 From 69b113a06c16d9fca9577d10d8d17784290ef9c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 21 Feb 2022 10:50:57 -0800 Subject: [PATCH 0527/2729] Update 2182.Construct-String-With-Repeat-Limit.cpp --- .../2182.Construct-String-With-Repeat-Limit.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Greedy/2182.Construct-String-With-Repeat-Limit/2182.Construct-String-With-Repeat-Limit.cpp b/Greedy/2182.Construct-String-With-Repeat-Limit/2182.Construct-String-With-Repeat-Limit.cpp index 493ad5322..a7d0bdec9 100644 --- a/Greedy/2182.Construct-String-With-Repeat-Limit/2182.Construct-String-With-Repeat-Limit.cpp +++ b/Greedy/2182.Construct-String-With-Repeat-Limit/2182.Construct-String-With-Repeat-Limit.cpp @@ -16,12 +16,19 @@ class Solution { { auto x = pq.top(); pq.pop(); + + if (x.second <= repeatLimit) + { + for (int i=0; i Date: Thu, 24 Feb 2022 15:05:44 -0800 Subject: [PATCH 0528/2729] Create 2183.Count-Array-Pairs-Divisible-by-K_v2.cpp --- ...83.Count-Array-Pairs-Divisible-by-K_v2.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Math/2183.Count-Array-Pairs-Divisible-by-K/2183.Count-Array-Pairs-Divisible-by-K_v2.cpp diff --git a/Math/2183.Count-Array-Pairs-Divisible-by-K/2183.Count-Array-Pairs-Divisible-by-K_v2.cpp b/Math/2183.Count-Array-Pairs-Divisible-by-K/2183.Count-Array-Pairs-Divisible-by-K_v2.cpp new file mode 100644 index 000000000..f3af7ac16 --- /dev/null +++ b/Math/2183.Count-Array-Pairs-Divisible-by-K/2183.Count-Array-Pairs-Divisible-by-K_v2.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + long long countPairs(vector& nums, int k) + { + unordered_setyueshu; + for (int i=1; i*i<=k; i++) + { + if (k%i!=0) continue; + yueshu.insert(i); + yueshu.insert(k/i); + } + + long long ret = 0; + unordered_mapcount; + for (int i=nums.size()-1; i>=0; i--) + { + int a = gcd(nums[i],k); + int b = k/a; + if (count.find(b)!=count.end()) + ret += count[b]; + + for (int x: yueshu) + { + if (nums[i]%x==0) + count[x]++; + } + } + + return ret; + } +}; From 4c4e548a2b030d1b5397a210418d329c3de5f2b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Feb 2022 22:03:03 -0800 Subject: [PATCH 0529/2729] Update Readme.md --- Dynamic_Programming/376.Wiggle-Subsequence/Readme.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/376.Wiggle-Subsequence/Readme.md b/Dynamic_Programming/376.Wiggle-Subsequence/Readme.md index b3819fd15..b7ee4695e 100644 --- a/Dynamic_Programming/376.Wiggle-Subsequence/Readme.md +++ b/Dynamic_Programming/376.Wiggle-Subsequence/Readme.md @@ -26,11 +26,15 @@ #### 解法2:DP -设计两个状态变量:p表示截止目前为止,最后一个元素是上升趋势的最长wiggle子序列;q表示截止目前为止,最后一个元素时下降趋势的最长wiggle子序列。 +设计两个状态变量:p表示截止目前为止,最后一个元素是上升趋势的最长wiggle子序列;q表示截止目前为止,最后一个元素是下降趋势的最长wiggle子序列。 -每查看一个数字,尝试更新两个变量p和q。当nums[i]比nums[i-1]大时,意味着q对应的序列之后又出现了一个上升段,说明可以更新p,即p=q+1。当nums[i]比nums[i-1]小时,意味着p对应的序列之后又出现了一个下降段,说明可以更新q,即p=q+1 +首先我们要有这样一个概念。无论当前元素x是什么,p序列的最后一个元素要么是x,要么只能是在x前面、但是比x大的元素。反证:如果存在一个元素y在x前面、且比x要小,那么这个将y从p序列的结尾里去掉、改成x加入p序列的结尾,同样不影响p序列的性质和长度。同理,无论当前元素x是什么,q序列的最后一个元素要么是x,要么只能是在x前面、但是比x小的元素。 + +回到我们的问题。我们每查看一个数字,尝试更新两个变量p和q。当nums[i]>nums[i-1]大时,由前面可知,原先q序列的结尾元素一定比nums[i]小,于是再接上nums[i]的话q序列一定不会变的更长。同时,原先q序列的结尾一定比nums[i]小,接上nums[i]之后,就可以得到一个新的p的序列。故有```q不变,p=q+1```. + +类似地,当nums[i] Date: Fri, 25 Feb 2022 10:58:17 -0800 Subject: [PATCH 0530/2729] Update Readme.md --- Template/Diff_Array_2D/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/Diff_Array_2D/Readme.md b/Template/Diff_Array_2D/Readme.md index e2ae5aeeb..5fcc7fc51 100644 --- a/Template/Diff_Array_2D/Readme.md +++ b/Template/Diff_Array_2D/Readme.md @@ -5,7 +5,7 @@ diff[x0][y1+1]-=1; diff[x1+1][y0]-=1; diff[x1+1][y1+1]+=1; ``` -其中diff[i][j]的物理意义是,以(i,j)为左上角、延伸至大矩阵的右下角,这样的区域我们整体赋值. +其中diff[i][j]的物理意义是,以(i,j)为左上角、延伸至大矩阵(即整个空间)的右下角,这样的区域我们整体赋值. 这样的操作可以进行多次。如果我们想重构更新后的f的值,需要做如下操作: ``` From 99c62d147f30f85e2f0d0cb963b3bd9d8c354347 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 28 Feb 2022 19:24:43 -0800 Subject: [PATCH 0531/2729] Create 2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall.cpp --- ...ber-of-Ways-to-Build-Sturdy-Brick-Wall.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall.cpp diff --git a/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall.cpp b/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall.cpp new file mode 100644 index 000000000..27ab14158 --- /dev/null +++ b/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + int buildWall(int height, int width, vector& bricks) + { + unordered_setSet(bricks.begin(), bricks.end()); + vectorplans; + int m = width-1; + for (int state=0; state<(1<temp({-1}); + for (int i=0; i>i)&1) + temp.push_back(i); + } + temp.push_back(width-1); + + int flag = 1; + for (int i=1; i>dp(height, vector(plans.size())); + int M = 1e9+7; + for (int j=0; j Date: Mon, 28 Feb 2022 19:25:22 -0800 Subject: [PATCH 0532/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d1ba45485..57344dfe7 100644 --- a/Readme.md +++ b/Readme.md @@ -722,6 +722,7 @@ [1799.Maximize-Score-After-N-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1799.Maximize-Score-After-N-Operations) (H-) [1931.Painting-a-Grid-With-Three-Different-Colors](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1931.Painting-a-Grid-With-Three-Different-Colors) (M+) [1994.The-Number-of-Good-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1994.The-Number-of-Good-Subsets) (H) +[2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall) (H-) * ``枚举集合的子集`` [1494.Parallel-Courses-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1494.Parallel-Courses-II) (H) [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) From 44e1eb68a9232b045e33b8fad47b8918e4afa907 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 28 Feb 2022 19:31:42 -0800 Subject: [PATCH 0533/2729] Create Readme.md --- .../2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md diff --git a/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md b/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md new file mode 100644 index 000000000..386ae48cf --- /dev/null +++ b/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md @@ -0,0 +1,3 @@ +### 2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall + +本题的突破口在于width<=10,这暗示我们可以用一个10bit的01二进制数来表示“这一层砌的是什么样子”。那么如何用一串01既来表示用了哪些砖、又可以描述这些砖是怎么排列的呢?方法就是用1来表示“砖与砖之间的缝隙”。例如长度为w的平面,相当于有w-1个潜在的切缝位置,我们用1表示这确实是个两块砖之间的缝,0则表示这个位置属于一块完整的砖无法切割。比如10010,这说明有三块长度分别是1、3、2的砖拼接起来。 From 0f5fb2be00a269bb24da6e9e7e77878675d4132e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 1 Mar 2022 05:09:35 -0800 Subject: [PATCH 0534/2729] Update Readme.md --- .../Readme.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md b/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md index 386ae48cf..f5cdd5e7d 100644 --- a/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md +++ b/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall/Readme.md @@ -1,3 +1,13 @@ ### 2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall -本题的突破口在于width<=10,这暗示我们可以用一个10bit的01二进制数来表示“这一层砌的是什么样子”。那么如何用一串01既来表示用了哪些砖、又可以描述这些砖是怎么排列的呢?方法就是用1来表示“砖与砖之间的缝隙”。例如长度为w的平面,相当于有w-1个潜在的切缝位置,我们用1表示这确实是个两块砖之间的缝,0则表示这个位置属于一块完整的砖无法切割。比如10010,这说明有三块长度分别是1、3、2的砖拼接起来。 +本题的突破口在于width<=10,这暗示我们可以用一个10bit的01二进制数来表示“长度为w的线段可以如何切割为若干段”。那么如何用一串01既来表示“用了哪些长度的砖”、又可以描述“这些砖是怎么排列的”呢?方法就是着眼于那些可能是切缝的位置。 + +例如长度为w,就有w-1个潜在的切缝位置(编号是0到w-2),我们用1表示这确实是个两块砖之间的缝,0则表示这个位置属于一块完整的砖无法切割。特别注意,我们需要虚拟地添加上左边缘的位置(想象成第-1个切缝位置)和右边缘的位置(想象成第w-1个切缝位置)。 + +比如w=6,那么内部有五个切缝位置,假设是10010,表示切缝位置0、3是砖与砖的交界处。另外加上左边缘-1和右边缘5,所以总共有四个交界位置:-1,0,3,5,这说明有三块长度分别是1、3、2的砖拼接起来。也就是说,任意两个1之间的index之差,表示了中间有多少块砖。 + +考虑到w很小,我们穷举所有对w的切割方案,看看切割出来的每一小段是否存在于bricks里面。都存在的话就是一个合法的切割(拼接)方案。 + +我们得到所有合法的切割方案之后(用bitmask的形式表示),就是常规的状态压缩DP。我们用dp[i][state]表示第i层用state这种拼接方式的话可以有多少种方案。显然```dp[i][state]+=dp[i-1][state1]```其中state1和state不能在同一个切缝位置上都是拼接点,也就是说必须满足```(state & state1) == 0```。这个思想和paint house非常相似,在那道题里,任何相邻的房子不能是同一种颜色。 + +最终答案是 sum{dp[height-1][state]} for all states From a382db10b6d20ed1ce5f802900397e5dfb9a0090 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Mar 2022 03:36:21 -0800 Subject: [PATCH 0535/2729] Update Readme.md --- DFS/2014.Longest-Subsequence-Repeated-k-Times/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/2014.Longest-Subsequence-Repeated-k-Times/Readme.md b/DFS/2014.Longest-Subsequence-Repeated-k-Times/Readme.md index 4c2e91fb0..fd6dc09c0 100644 --- a/DFS/2014.Longest-Subsequence-Repeated-k-Times/Readme.md +++ b/DFS/2014.Longest-Subsequence-Repeated-k-Times/Readme.md @@ -2,6 +2,6 @@ 本题其实并没有特别高明的算法,就是“暴力”枚举可能的repeated subsequence,然后检验该子序列能否在s中重复k次。显然对于“检验”的操作,复杂度就是o(n)=16000,那么枚举repeated subsequence的复杂度是多少呢? -注意到本题的约束条件```n < k*8```. 这说明了两点:首先,repeated subsequence的长度不超过7,否则重复k次之后会有```n>=len(subsequenc)*k>=8*k```推出矛盾。其次,s里面频次大于等于k的字符种类不会超过7,否则也会有```n>=k*8```推出矛盾。这两个推论告诉我们,repeated subsequence的构造并没有那么复杂,它最长只有7位,并且字符的种类不会超过7种。所以repeated subsequence的可能性最多就是7^7+7^6+7^5...= 7^8 = 5e6。 +注意到本题的约束条件```n < k*8```. 这说明了两点:首先,repeated subsequence的长度不超过7,否则重复k次之后会有```n>=len(subsequence)*k>=8*k```推出矛盾。其次,s里面频次大于等于k的字符种类不应该超过7,否则也会有```n>=k*8```推出矛盾。这两个推论告诉我们,repeated subsequence的构造并没有那么复杂,它最长只有7位,并且字符的种类不会超过7种。所以repeated subsequence的可能性最多就是7^7+7^6+7^5...= 7^8 = 5e6。 按照上面的分析,共有5e6种可能的subsequence,每次检验需要1.6e4,总的时间复杂度依然达到了1e10数量级。我们只能寄希望于剪枝,降低subsequence的种类数目。其中一种方法就是,如果我们发现一个较短的subsequence不符合条件(即无法重复k次依然是s的子序列),那么任何在此基础上append任何字符也都不会符合条件。所以这就提醒我们“暴力”枚举repeated subsequence可以采用从短的序列逐渐生成更长序列的方法,一旦检验发现不合条件,就可以终止这个支路。 From 5e00a58f8e2fccbdaa186ecb39e75f0b8c752a69 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Mar 2022 08:24:19 -0800 Subject: [PATCH 0536/2729] Create 2188.Minimum-Time-to-Finish-the-Race.cpp --- .../2188.Minimum-Time-to-Finish-the-Race.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/2188.Minimum-Time-to-Finish-the-Race.cpp diff --git a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/2188.Minimum-Time-to-Finish-the-Race.cpp b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/2188.Minimum-Time-to-Finish-the-Race.cpp new file mode 100644 index 000000000..9726c1311 --- /dev/null +++ b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/2188.Minimum-Time-to-Finish-the-Race.cpp @@ -0,0 +1,48 @@ +using LL = long long; +class Solution { + static bool cmp(vector&a, vector&b) + { + if (a[1]!=b[1]) + return a[1] < b[1]; + else + return a[0] > b[0]; + } +public: + int minimumFinishTime(vector>& tires, int changeTime, int numLaps) + { + sort(tires.begin(), tires.end(), cmp); + vector>newTires; + for (int i=0; iminTime(min(20, numLaps+1), DBL_MAX); + for (int x=1; xdp(numLaps+1, DBL_MAX); + dp[0] = 0; + for (int i=1; i<=numLaps; i++) + for (int j=i-1; i-j<20 && j>=0; j--) + { + dp[i] = min(dp[i], dp[j]+minTime[i-j] + (j==0?0:changeTime)); + } + + return dp[numLaps]; + } + + double cal(vectortire, int x) + { + double f= tire[0], r = tire[1]; + double ret = f*(pow(r, x)-1)/(r-1); + return ret; + + } +}; From e9559ffce62726ecb23b370148929807c38fe55f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Mar 2022 08:24:59 -0800 Subject: [PATCH 0537/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 57344dfe7..e32d25487 100644 --- a/Readme.md +++ b/Readme.md @@ -633,6 +633,7 @@ [1546.Maximum-Number-of-Non-Overlapping-Subarrays-With-Sum-Equals-Target](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1546.Maximum-Number-of-Non-Overlapping-Subarrays-With-Sum-Equals-Target) (M+) [1626.Best-Team-With-No-Conflicts](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1626.Best-Team-With-No-Conflicts) (M) [1691.Maximum-Height-by-Stacking-Cuboids](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1691.Maximum-Height-by-Stacking-Cuboids) (H) +[2188.Minimum-Time-to-Finish-the-Race](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race) (H-) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) From 313e774bd97a6463ecc11ebd543d0dd4c73c1601 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Mar 2022 09:20:48 -0800 Subject: [PATCH 0538/2729] Create Readme.md --- .../2188.Minimum-Time-to-Finish-the-Race/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md diff --git a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md new file mode 100644 index 000000000..e3d16e643 --- /dev/null +++ b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md @@ -0,0 +1,6 @@ +### 2188.Minimum-Time-to-Finish-the-Race + +整体思想显然是DP。令dp[i]表示跑i圈的最小代价,那么它取决于最后一次换胎的选择。假设最后一次换胎跑了j圈,那么就有```dp[i] = dp[i-j] + changTime + minTime[j]```,其中j表示minTime[j]是在所有轮胎类型中跑j圈最快的时间。所以求解DP的过程大致是o(numLaps^2) = 1e6 的复杂度,可以接受。 + +那么预处理minTime需要多少时间呢?在有m种轮胎,如果把所有的minTime[t], t=1,2,3,...numLaps的情况下,我们需要花```o(m*numLaps)```的时间,那就是1e8数量级,必然TLE。该如何改进呢? + From 7cfb86066807cd464ac1b2dc626a2bd48b9aa073 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Mar 2022 15:10:06 -0800 Subject: [PATCH 0539/2729] Update Readme.md --- .../2188.Minimum-Time-to-Finish-the-Race/Readme.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md index e3d16e643..58485cb9a 100644 --- a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md +++ b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md @@ -2,5 +2,10 @@ 整体思想显然是DP。令dp[i]表示跑i圈的最小代价,那么它取决于最后一次换胎的选择。假设最后一次换胎跑了j圈,那么就有```dp[i] = dp[i-j] + changTime + minTime[j]```,其中j表示minTime[j]是在所有轮胎类型中跑j圈最快的时间。所以求解DP的过程大致是o(numLaps^2) = 1e6 的复杂度,可以接受。 -那么预处理minTime需要多少时间呢?在有m种轮胎,如果把所有的minTime[t], t=1,2,3,...numLaps的情况下,我们需要花```o(m*numLaps)```的时间,那就是1e8数量级,必然TLE。该如何改进呢? +那么预处理minTime需要多少时间呢?在有m种轮胎,如果把所有的minTime[j], j=1,2,3,...numLaps都计算的话,我们需要花```o(m*numLaps)```的时间,那就是1e8数量级,必然TLE。该如何改进呢? +事实上我们根据跑一圈的公式```t = f*r^(x-1)```,在不换胎的条件下,当x很大时,跑一圈的时间会指数级地增长。显然,当不换胎多跑一圈的时间大于换胎本身的时间时,无论对于任何轮胎,继续跑下去都是不合算的。通过尝试发现,我们在最极端的条件下,即f=1,r=2时,当x是第20圈的时候,跑一圈所花的时间就有2^19=5e5已经大于了changeTime的上限。所以无论对于什么轮胎,一次性跑20圈都是不划算的。因此在dp的转移方程里,我们对于minTime的下标不会超过20圈。 + +所以本题的DP计算是```o(20*numLaps)```,此外我们提前需要预处理minTime[20]需要```o(20m)=2e6```的时间。 + +以上的操作还会有TLE。进一步改进的方法是减少轮胎的种类。显然如果轮胎A的f参数和r参数都比轮胎B的大,那么轮胎A完全就可以忽略。所以我们可以将所有轮胎按照r参数递增排列,顺次检查这些轮胎时,如果发现任何一个轮胎的f值大于前面的轮胎,那么该轮胎就可以忽略。 From 00fb8f62ebd364c75afb977e354501c761aabedf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Mar 2022 15:14:17 -0800 Subject: [PATCH 0540/2729] Update Readme.md --- .../2188.Minimum-Time-to-Finish-the-Race/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md index 58485cb9a..dac593f24 100644 --- a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md +++ b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md @@ -8,4 +8,4 @@ 所以本题的DP计算是```o(20*numLaps)```,此外我们提前需要预处理minTime[20]需要```o(20m)=2e6```的时间。 -以上的操作还会有TLE。进一步改进的方法是减少轮胎的种类。显然如果轮胎A的f参数和r参数都比轮胎B的大,那么轮胎A完全就可以忽略。所以我们可以将所有轮胎按照r参数递增排列,顺次检查这些轮胎时,如果发现任何一个轮胎的f值大于前面的轮胎,那么该轮胎就可以忽略。 +以上的操作还会有TLE。进一步改进的方法是减少轮胎的种类。显然如果轮胎A的f参数和r参数都比轮胎B的大,那么轮胎A完全就可以忽略。所以我们可以将所有轮胎按照r参数递增排列,顺次检查这些轮胎时,如果发现任何一个轮胎的f值大于等于前面的轮胎,那么该轮胎就可以忽略。 From 90ab3ee0a2b7bffd7c5cf483c88bc35e85291caa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Mar 2022 15:14:41 -0800 Subject: [PATCH 0541/2729] Update Readme.md --- .../2188.Minimum-Time-to-Finish-the-Race/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md index dac593f24..e4d80b949 100644 --- a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md +++ b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/Readme.md @@ -8,4 +8,4 @@ 所以本题的DP计算是```o(20*numLaps)```,此外我们提前需要预处理minTime[20]需要```o(20m)=2e6```的时间。 -以上的操作还会有TLE。进一步改进的方法是减少轮胎的种类。显然如果轮胎A的f参数和r参数都比轮胎B的大,那么轮胎A完全就可以忽略。所以我们可以将所有轮胎按照r参数递增排列,顺次检查这些轮胎时,如果发现任何一个轮胎的f值大于等于前面的轮胎,那么该轮胎就可以忽略。 +以上的操作还会有TLE。进一步改进的方法是减少轮胎的种类。显然如果轮胎A的f参数和r参数都比轮胎B的大,那么轮胎A完全就可以忽略。所以我们可以将所有轮胎按照r参数递增排列,顺次检查这些轮胎时,如果发现任何一个轮胎的f值大于等于前面的轮胎,那么该轮胎就可以忽略。这样我们就可以大幅度地减少轮胎的种类。 From e237aa1758352d4b30cf0ca87560ce8e2561f244 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Mar 2022 15:34:47 -0800 Subject: [PATCH 0542/2729] Update 2188.Minimum-Time-to-Finish-the-Race.cpp --- .../2188.Minimum-Time-to-Finish-the-Race.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/2188.Minimum-Time-to-Finish-the-Race.cpp b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/2188.Minimum-Time-to-Finish-the-Race.cpp index 9726c1311..ea6cc7d52 100644 --- a/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/2188.Minimum-Time-to-Finish-the-Race.cpp +++ b/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race/2188.Minimum-Time-to-Finish-the-Race.cpp @@ -5,7 +5,7 @@ class Solution { if (a[1]!=b[1]) return a[1] < b[1]; else - return a[0] > b[0]; + return a[0] < b[0]; } public: int minimumFinishTime(vector>& tires, int changeTime, int numLaps) @@ -13,8 +13,7 @@ class Solution { sort(tires.begin(), tires.end(), cmp); vector>newTires; for (int i=0; i Date: Sun, 6 Mar 2022 17:48:47 -0800 Subject: [PATCH 0543/2729] Create 2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp --- ...-Number-of-Moves-to-Make-Palindrome_v1.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp new file mode 100644 index 000000000..2d386867a --- /dev/null +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int minMovesToMakePalindrome(string s) + { + int n = s.size(); + int ret = 0; + int c = 0; + + for (int i=0; i Date: Sun, 6 Mar 2022 18:22:03 -0800 Subject: [PATCH 0544/2729] Create Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md new file mode 100644 index 000000000..ab5ecfb14 --- /dev/null +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md @@ -0,0 +1,18 @@ +### 2193.Minimum-Number-of-Moves-to-Make-Palindrome + +这道题存在着一个非常直观的贪心策略,我们从左往右遍历每个字符s[i],找到与它能够组成回文对称的那个s[j],那么将其从j移动到与s[i]回文对称的位置(在总长度是偶数的条件下就是n-1-i)即可。如果暴力地用swap来模拟这个过程,那么就是o(N^2)的复杂度:遍历i是o(N),对于每个i,用o(N)找到j,并且将j移动到n-1-i。 + +那么这个贪心策略如何证明呢?也就是说,如果当前字符串最左边是x,那么为什么我们贪心地就把一对x调整到最外层,而不是把其他的一对y调整到最外层呢?我们不失一般性地描述出x和y可能的位置位置关系: +1. ```x ... y... y ... x .....``` 很明显,我们必然先搬动这对x到外侧,再搬动这对y到x的内侧 +2. ```x ..(a).. y..(b).. x ..(c).. y ..(d)..``` 我们用abcde表示每段区间的长度。 + (1) 策略1是将x搬动到外侧,那么需要 0 + (c+d+1),再搬动y到x的内侧,需要(a) + (d) + (2) 策略2是将y搬动到外侧,那么需要 (a+1) + (d),再搬动x到y的内侧,需要 0 + (c+d) + 我们惊奇地发现上面两种策略的总和都是 2d+a+d+1 +3. ```x ..(a).. x..(b).. y ..(c).. y ..(d)..``` + (1) 策略1是将x搬动到外侧,那么需要 (0) + (b+c+d+2),再搬动y到x的内侧,需要 (a+b+1) + (d) + (2) 策略2是将y搬动到外侧,那么需要 (a+b+2) + (d),再搬动x到y的内侧,需要(0) + (b+c+d+1) + 我们惊奇地发现上面两种策略的总和都是 2d+a+b+c+3 + +所以我们得出结论,无论什么情况下,我们只需要把最左边的x固定,将另一个对称的x放到左右边,就是当前的最佳策略。处理完之后就可以剥除最外面一对,递归处理剩下的字符串即可。 + +OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长度是奇数,那么这个需要放在中心位置的字符,一定是唯一频次是奇数的字符里最靠中间那个,这个是不难找出来的。那么我们要对其做什么处理呢?注意,我们在调整配对完其他字符前,不应该调整它的位置。 From f7a2d9087fcec22d10014747e548213c009d9fcb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Mar 2022 19:11:26 -0800 Subject: [PATCH 0545/2729] Update Readme.md --- .../Readme.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md index ab5ecfb14..dbdf2c936 100644 --- a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md @@ -1,5 +1,6 @@ ### 2193.Minimum-Number-of-Moves-to-Make-Palindrome +#### 贪心加暴力模拟 这道题存在着一个非常直观的贪心策略,我们从左往右遍历每个字符s[i],找到与它能够组成回文对称的那个s[j],那么将其从j移动到与s[i]回文对称的位置(在总长度是偶数的条件下就是n-1-i)即可。如果暴力地用swap来模拟这个过程,那么就是o(N^2)的复杂度:遍历i是o(N),对于每个i,用o(N)找到j,并且将j移动到n-1-i。 那么这个贪心策略如何证明呢?也就是说,如果当前字符串最左边是x,那么为什么我们贪心地就把一对x调整到最外层,而不是把其他的一对y调整到最外层呢?我们不失一般性地描述出x和y可能的位置位置关系: @@ -15,4 +16,6 @@ 所以我们得出结论,无论什么情况下,我们只需要把最左边的x固定,将另一个对称的x放到左右边,就是当前的最佳策略。处理完之后就可以剥除最外面一对,递归处理剩下的字符串即可。 -OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长度是奇数,那么这个需要放在中心位置的字符,一定是唯一频次是奇数的字符里最靠中间那个,这个是不难找出来的。那么我们要对其做什么处理呢?注意,我们在调整配对完其他字符前,不应该调整它的位置。 +OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长度是奇数,那么这个需要放在中心位置的字符,一定是唯一频次是奇数的字符里最靠中间那个,这个位置mid是不难找出来的。那么我们要对其做什么处理呢?注意,我们如果在从左到右遍历字符的过程中遇到了mid,那么就直接忽略处理下一个。也就是说,在人工调整完其他字符对之前,不应该调整mid的位置,否则可能反而会增加其他字符在调整过程中需要交换的次数(比如说waabb,先调整a再调整w的话是2+2,先调整w再调整a的话是2+3)。所以我们只需要基于之前算出的答案,加上这个字符的位置mid与n/2之差即可。 + + From 38d21150aba4fbd060902c3b3d30ff228fa1b2da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Mar 2022 19:11:56 -0800 Subject: [PATCH 0546/2729] Update Readme.md --- .../2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md index dbdf2c936..dab747650 100644 --- a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md @@ -16,6 +16,6 @@ 所以我们得出结论,无论什么情况下,我们只需要把最左边的x固定,将另一个对称的x放到左右边,就是当前的最佳策略。处理完之后就可以剥除最外面一对,递归处理剩下的字符串即可。 -OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长度是奇数,那么这个需要放在中心位置的字符,一定是唯一频次是奇数的字符里最靠中间那个,这个位置mid是不难找出来的。那么我们要对其做什么处理呢?注意,我们如果在从左到右遍历字符的过程中遇到了mid,那么就直接忽略处理下一个。也就是说,在人工调整完其他字符对之前,不应该调整mid的位置,否则可能反而会增加其他字符在调整过程中需要交换的次数(比如说waabb,先调整a再调整w的话是2+2,先调整w再调整a的话是2+3)。所以我们只需要基于之前算出的答案,加上这个字符的位置mid与n/2之差即可。 +OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长度是奇数,那么这个需要放在中心位置的字符,一定是唯一频次是奇数的字符里最靠中间那个,这个位置是不难找出来的,我们记做mid。那么我们要对mid做什么处理呢?注意,我们如果在从左到右遍历字符的过程中遇到了mid,那么就直接忽略处理下一个。也就是说,在人工调整完其他字符对之前,不应该调整mid的位置,否则可能反而会增加其他字符在调整过程中需要交换的次数(比如说waabb,先调整a再调整w的话是2+2,先调整w再调整a的话是2+3)。所以我们只需要基于之前算出的答案,加上这个字符的位置mid与n/2之差即可。 From 22bcb25a379d4f54902a744a710cad0df5411f6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Mar 2022 23:06:23 -0800 Subject: [PATCH 0547/2729] Create 2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp --- ...-Number-of-Moves-to-Make-Palindrome_v2.cpp | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp new file mode 100644 index 000000000..33c6ee054 --- /dev/null +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp @@ -0,0 +1,70 @@ +class Solution { +public: + int minMovesToMakePalindrome(string s) + { + int n = s.size(); + int ret = 0; + + unordered_map>dq; + for (int i=0; iarr; + int count = 0; // how many left-pair characters have been processed + + for (int i=0; i temp = countSmaller(arr); + ret += accumulate(temp.begin(), temp.end(), 0); + + return ret; + } + + vector countSmaller(vector nums) + { + int N = nums.size(); + if (N==0) return {}; + + vectorsortedNums = nums; + vectorcounts(N,0); + DivideConque(nums,sortedNums, counts, 0, nums.size()-1); // 0表示起点,N-1表示终点 + return counts; + } + + void DivideConque(vector&nums, vector&sortedNums, vector&counts, int start, int end) + { + if (start==end) return; + + int mid = start+(end-start)/2; + DivideConque(nums, sortedNums, counts, start,mid); + DivideConque(nums, sortedNums, counts, mid+1, end); + + for (int i=start; i<=mid; i++) + { + int val = nums[i]; + auto pos = lower_bound(sortedNums.begin()+mid+1, sortedNums.begin()+end+1,val); + counts[i] += pos-(sortedNums.begin()+mid+1); + } + + sort(sortedNums.begin()+start,sortedNums.begin()+end+1); + } +}; From 0be24bfb1e6281f441812f5519f3ab3c61483cd8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Mar 2022 23:08:33 -0800 Subject: [PATCH 0548/2729] Update 2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp --- ...2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp index 2d386867a..10aaa1779 100644 --- a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v1.cpp @@ -4,11 +4,11 @@ class Solution { { int n = s.size(); int ret = 0; - int c = 0; + int count = 0; // how many left-pair characters have been processed for (int i=0; i Date: Sun, 6 Mar 2022 23:30:08 -0800 Subject: [PATCH 0549/2729] Update Readme.md --- .../Readme.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md index dab747650..047c299cf 100644 --- a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md @@ -1,6 +1,6 @@ ### 2193.Minimum-Number-of-Moves-to-Make-Palindrome -#### 贪心加暴力模拟 +#### 解法1:贪心加暴力模拟 这道题存在着一个非常直观的贪心策略,我们从左往右遍历每个字符s[i],找到与它能够组成回文对称的那个s[j],那么将其从j移动到与s[i]回文对称的位置(在总长度是偶数的条件下就是n-1-i)即可。如果暴力地用swap来模拟这个过程,那么就是o(N^2)的复杂度:遍历i是o(N),对于每个i,用o(N)找到j,并且将j移动到n-1-i。 那么这个贪心策略如何证明呢?也就是说,如果当前字符串最左边是x,那么为什么我们贪心地就把一对x调整到最外层,而不是把其他的一对y调整到最外层呢?我们不失一般性地描述出x和y可能的位置位置关系: @@ -16,6 +16,13 @@ 所以我们得出结论,无论什么情况下,我们只需要把最左边的x固定,将另一个对称的x放到左右边,就是当前的最佳策略。处理完之后就可以剥除最外面一对,递归处理剩下的字符串即可。 -OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长度是奇数,那么这个需要放在中心位置的字符,一定是唯一频次是奇数的字符里最靠中间那个,这个位置是不难找出来的,我们记做mid。那么我们要对mid做什么处理呢?注意,我们如果在从左到右遍历字符的过程中遇到了mid,那么就直接忽略处理下一个。也就是说,在人工调整完其他字符对之前,不应该调整mid的位置,否则可能反而会增加其他字符在调整过程中需要交换的次数(比如说waabb,先调整a再调整w的话是2+2,先调整w再调整a的话是2+3)。所以我们只需要基于之前算出的答案,加上这个字符的位置mid与n/2之差即可。 +OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长度是奇数,那么在上述“递归处理”的过程中,我们会遇到这样一种情况:此时字符串的最左边是一个仅出现一次的字符(记做w)。那么我们要对w做什么处理呢?答案是我们应该直接忽略掉它,先处理下一个。也就是说,只有在处理完剩下的所有配对之后,再去考察w需要位移几次(就是n/2与w所在index之差)。比如说waabb,正解是忽略w,先调整得到wabba,再将w插入abba的中央,总的交换次数是4. 如果我们试图先将w放入中央得到aawbb,那么再使得aabb对称的话,总的交换次数就需要2+3。 +#### 解法2:贪心加统计逆序对 +上面的贪心解法配合的是暴力移动。事实上我们有“虚拟移动”的方法来提高效率。 +根据前面的分析,最优的做法其实分三步:1. 将所有配对字符的左半边,按照其出场顺序移动到字符串的左侧。2. 如果总长度是奇数,那么将落单的字符移动到n/2的位置。3. 此时剩余的字符(即所有配对字符的右半边)仍然是按照出场顺序排列的,但是都已经挪到了字符串的右侧,此时我们只需要将这个乱序的substring进行操作,使得顺序变得和左侧(更确切地说是与左侧的倒序)一致即可。 + +举个例子,假设在第1步里第一个遇到的是字符a,与之配对的另一个a的位置是7;第二个遇到的是字符b,与之配对的另一个b的位置是5;第三个遇到的是字符c,与之配对的另一个c的位置是9. 那么说明在原始串579这些位置的字符,我们希望通过adjacent swap的操作最终变为957的顺序。因为最右侧的7对应着与a配对,中间的5对应着与b配对,左边的9对应着与c配对。 + +那么需要多少次adjacent swap使得579变成957呢?这个问题等价于将一个乱序957变成顺序579. 这是一个经典题,答案是统计所有逆序对的个数。在这里(9,5)和(9,7)是逆序对(即前者大于后者),所以我们只需要两次交换就可以将957->579. 而求逆序对,就是LC.493的原题。 From ddf130569f44d335d6927a72c03726ef88c8249b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Mar 2022 23:35:36 -0800 Subject: [PATCH 0550/2729] Update 493.Reverse-Pairs_v1.cpp --- .../493.Reverse-Pairs_v1.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/Divide_Conquer/493.Reverse-Pairs/493.Reverse-Pairs_v1.cpp b/Divide_Conquer/493.Reverse-Pairs/493.Reverse-Pairs_v1.cpp index fefcbcf80..0131dfb07 100644 --- a/Divide_Conquer/493.Reverse-Pairs/493.Reverse-Pairs_v1.cpp +++ b/Divide_Conquer/493.Reverse-Pairs/493.Reverse-Pairs_v1.cpp @@ -1,21 +1,20 @@ -class Solution { - int ret = 0; +class Solution { int temp[50001]; public: int reversePairs(vector& nums) { int n = nums.size(); - vectorsorted = nums; - helper(nums, sorted, 0, n-1); - return ret; + vectorsorted = nums; + return helper(nums, sorted, 0, n-1); } - void helper(vector& nums, vector& sorted, int a, int b) + int helper(vector& nums, vector& sorted, int a, int b) { - if (a>=b) return; + if (a>=b) return 0; + int ret = 0; int mid = a+(b-a)/2; - helper(nums, sorted, a, mid); - helper(nums, sorted, mid+1, b); + ret += helper(nums, sorted, a, mid); + ret += helper(nums, sorted, mid+1, b); for (int j=mid+1; j<=b; j++) { @@ -52,5 +51,7 @@ class Solution { } for (int i=0; i Date: Sun, 6 Mar 2022 23:42:32 -0800 Subject: [PATCH 0551/2729] Update Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md index 047c299cf..20f01b730 100644 --- a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md @@ -26,3 +26,8 @@ OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长 举个例子,假设在第1步里第一个遇到的是字符a,与之配对的另一个a的位置是7;第二个遇到的是字符b,与之配对的另一个b的位置是5;第三个遇到的是字符c,与之配对的另一个c的位置是9. 那么说明在原始串579这些位置的字符,我们希望通过adjacent swap的操作最终变为957的顺序。因为最右侧的7对应着与a配对,中间的5对应着与b配对,左边的9对应着与c配对。 那么需要多少次adjacent swap使得579变成957呢?这个问题等价于将一个乱序957变成顺序579. 这是一个经典题,答案是统计所有逆序对的个数。在这里(9,5)和(9,7)是逆序对(即前者大于后者),所以我们只需要两次交换就可以将957->579. 而求逆序对,就是LC.493的原题。 + +别忘了第1步和第2步我们也需要统计交换的次数。我们需要用count来统计在第一步的过程中已经处理了多少个left-pair的字符,那么我们在遇到一个新的left-pair字符时(记当前位置是i),那么意味着我们要将它从位置i移动到位置count,所以需要i-count次操作。 + +如果我们在位置i遇到了前述的落单字符w,那么它需要移动多少次呢?注意,我们本质上是需要把所有left-pair都处理完(即第一步)之后再计算w的移动次数。第一步处理完之后,意味着会有n/2-count个left-pair字符会移动到w前面,这意味着它的位置其实是被挤到后面去了,实际是i+(n/2-count)。然后我们需要将w放置在w/2的地方,所以移动步数是```i+(n/2-count) - n/2 = i-count```. + From 49bae1fec65cc7d9fe8514d4d8499dc0aa88cbaa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Mar 2022 01:23:45 -0800 Subject: [PATCH 0552/2729] Update 2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp --- ...-Number-of-Moves-to-Make-Palindrome_v2.cpp | 65 ++++++++----------- 1 file changed, 28 insertions(+), 37 deletions(-) diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp index 33c6ee054..fe19bfde4 100644 --- a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/2193.Minimum-Number-of-Moves-to-Make-Palindrome_v2.cpp @@ -1,70 +1,61 @@ class Solution { + int temp[50001]; public: int minMovesToMakePalindrome(string s) { int n = s.size(); + int count = 0; // how many left-pair characters have been processed int ret = 0; unordered_map>dq; - for (int i=0; iarr; - int count = 0; // how many left-pair characters have been processed - for (int i=0; i temp = countSmaller(arr); - ret += accumulate(temp.begin(), temp.end(), 0); - - return ret; + return ret + reversePairs(arr); } - vector countSmaller(vector nums) - { - int N = nums.size(); - if (N==0) return {}; - - vectorsortedNums = nums; - vectorcounts(N,0); - DivideConque(nums,sortedNums, counts, 0, nums.size()-1); // 0表示起点,N-1表示终点 - return counts; + int reversePairs(vector& nums) + { + int n = nums.size(); + vectorsorted = nums; + return helper(nums, sorted, 0, n-1); } - - void DivideConque(vector&nums, vector&sortedNums, vector&counts, int start, int end) + + int helper(vector& nums, vector& sorted, int a, int b) { - if (start==end) return; - - int mid = start+(end-start)/2; - DivideConque(nums, sortedNums, counts, start,mid); - DivideConque(nums, sortedNums, counts, mid+1, end); - - for (int i=start; i<=mid; i++) + if (a>=b) return 0; + int ret = 0; + int mid = a+(b-a)/2; + ret += helper(nums, sorted, a, mid); + ret += helper(nums, sorted, mid+1, b); + + for (int j=mid+1; j<=b; j++) { - int val = nums[i]; - auto pos = lower_bound(sortedNums.begin()+mid+1, sortedNums.begin()+end+1,val); - counts[i] += pos-(sortedNums.begin()+mid+1); + auto iter = upper_bound(sorted.begin()+a, sorted.begin()+mid+1, (long)nums[j]); + ret += sorted.begin()+mid+1 - iter; } - - sort(sortedNums.begin()+start,sortedNums.begin()+end+1); + sort(sorted.begin()+a, sorted.begin()+b+1); + return ret; } }; From f7753ca9c2720d56f657167d649caeec6588f7d1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 11 Mar 2022 22:41:05 -0800 Subject: [PATCH 0553/2729] Update Readme.md --- .../Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md index 20f01b730..4ab7facc0 100644 --- a/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md +++ b/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome/Readme.md @@ -10,12 +10,14 @@ (2) 策略2是将y搬动到外侧,那么需要 (a+1) + (d),再搬动x到y的内侧,需要 0 + (c+d) 我们惊奇地发现上面两种策略的总和都是 2d+a+d+1 3. ```x ..(a).. x..(b).. y ..(c).. y ..(d)..``` - (1) 策略1是将x搬动到外侧,那么需要 (0) + (b+c+d+2),再搬动y到x的内侧,需要 (a+b+1) + (d) - (2) 策略2是将y搬动到外侧,那么需要 (a+b+2) + (d),再搬动x到y的内侧,需要(0) + (b+c+d+1) - 我们惊奇地发现上面两种策略的总和都是 2d+a+b+c+3 + (1) 策略1是将x搬动到外侧,那么需要 (0) + (b+c+d+2),再搬动y到x的内侧,需要 (a+b) + (d) + (2) 策略2是将y搬动到外侧,那么需要 (a+b+2) + (d),再搬动x到y的内侧,需要(0) + (b+c+d) + 我们惊奇地发现上面两种策略的总和都是 2d+a+b+c+2 所以我们得出结论,无论什么情况下,我们只需要把最左边的x固定,将另一个对称的x放到左右边,就是当前的最佳策略。处理完之后就可以剥除最外面一对,递归处理剩下的字符串即可。 +补充:为什么我们要关注次外层?这里的逻辑是,我们如果想证明“把x放在最外层”比“把y放在最外层”的操作更优,我们除了要计算x和y的移动次数之外,还必须保证两种操作结束之后剩下的字符串状态是一样的,这样才是公平的比较。单纯地把x移到最外层、或单纯地把y移到最外层,遗留的字符串状态大概率还是不一样,我们也就无法得知后续操作谁更有优势。在视频的分析中,无论我们选哪个y,x都更比y更适合作为最外层,那么显然x就是做为最外层的最优解。 + OK,以上我们只是考虑了总长度是偶数的情况。如果回文串长度是奇数,那么在上述“递归处理”的过程中,我们会遇到这样一种情况:此时字符串的最左边是一个仅出现一次的字符(记做w)。那么我们要对w做什么处理呢?答案是我们应该直接忽略掉它,先处理下一个。也就是说,只有在处理完剩下的所有配对之后,再去考察w需要位移几次(就是n/2与w所在index之差)。比如说waabb,正解是忽略w,先调整得到wabba,再将w插入abba的中央,总的交换次数是4. 如果我们试图先将w放入中央得到aawbb,那么再使得aabb对称的话,总的交换次数就需要2+3。 #### 解法2:贪心加统计逆序对 From ead81c9cdba11a73b9f006e95acb1306d8b8a532 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 11 Mar 2022 22:41:43 -0800 Subject: [PATCH 0554/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e32d25487..46ac1aa50 100644 --- a/Readme.md +++ b/Readme.md @@ -1053,6 +1053,7 @@ [2170.Minimum-Operations-to-Make-the-Array-Alternating](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2170.Minimum-Operations-to-Make-the-Array-Alternating) (M+) [2171.Removing-Minimum-Number-of-Magic-Beans](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans) (M) [2182.Construct-String-With-Repeat-Limit](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2182.Construct-String-With-Repeat-Limit) (M+) +[2193.Minimum-Number-of-Moves-to-Make-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome) (H+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From a203120c4eb62b9547537782ae98ed7effc03ee7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 00:57:49 -0800 Subject: [PATCH 0555/2729] Create 2197.Replace-Non-Coprime-Numbers-in-Array.cpp --- ...7.Replace-Non-Coprime-Numbers-in-Array.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Stack/2197.Replace-Non-Coprime-Numbers-in-Array/2197.Replace-Non-Coprime-Numbers-in-Array.cpp diff --git a/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/2197.Replace-Non-Coprime-Numbers-in-Array.cpp b/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/2197.Replace-Non-Coprime-Numbers-in-Array.cpp new file mode 100644 index 000000000..a06b7d8d1 --- /dev/null +++ b/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/2197.Replace-Non-Coprime-Numbers-in-Array.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector replaceNonCoprimes(vector& nums) + { + vectorrets; + for (int i=0; i1) + { + x = lcm(rets.back(), x); + rets.pop_back(); + } + rets.push_back(x); + } + return rets; + } + + long long lcm(long long a, long long b) + { + return (long long)a*(long long)b/gcd(a,b); + } +}; From 9ce2d9bfd26513c618340a9dd68e0a686200a27e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 01:29:41 -0800 Subject: [PATCH 0556/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 46ac1aa50..e023c840d 100644 --- a/Readme.md +++ b/Readme.md @@ -317,6 +317,7 @@ [1190.Reverse-Substrings-Between-Each-Pair-of-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1190.Reverse-Substrings-Between-Each-Pair-of-Parentheses) (H-) [1209.Remove-All-Adjacent-Duplicates-in-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1209.Remove-All-Adjacent-Duplicates-in-String-II) (M+) [1586.Binary-Search-Tree-Iterator-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1586.Binary-Search-Tree-Iterator-II) (H) +[2197.Replace-Non-Coprime-Numbers-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2197.Replace-Non-Coprime-Numbers-in-Array) (H-) * ``monotonic stack`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) From 93958d4375e597ed7a408566a6e4345838ebb91a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 01:45:19 -0800 Subject: [PATCH 0557/2729] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index e023c840d..050d44597 100644 --- a/Readme.md +++ b/Readme.md @@ -501,15 +501,16 @@ [505.The-Maze-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/505.The-Maze-II) (H) [787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H-) [882.Reachable-Nodes-In-Subdivided-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/882.Reachable-Nodes-In-Subdivided-Graph ) (H) -[1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) -[1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) -[1947.Maximum-Compatibility-Score-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1947.Maximum-Compatibility-Score-Sum) (H) [1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid) (H) [1514.Path-with-Maximum-Probability](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1514.Path-with-Maximum-Probability) (H) [1786.Number-of-Restricted-Paths-From-First-to-Last-Node](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1786.Number-of-Restricted-Paths-From-First-to-Last-Node) (H-) [1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (H-) [2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) +* ``Dijkstra (for Bipatite Graph)`` +[1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) +[1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) +[1947.Maximum-Compatibility-Score-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1947.Maximum-Compatibility-Score-Sum) (H) #### [Trie](https://github.com/wisdompeak/LeetCode/tree/master/Trie) [208.Implement-Trie--Prefix-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Trie/208.Implement-Trie--Prefix-Tree) (M+) From 703f813bbeec2f818f39a3e766b1869a8a66e05c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 17:44:11 -0700 Subject: [PATCH 0558/2729] Create Readme.md --- Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md diff --git a/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md b/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md new file mode 100644 index 000000000..e3d8cb1a9 --- /dev/null +++ b/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md @@ -0,0 +1,7 @@ +### 2197.Replace-Non-Coprime-Numbers-in-Array + +这道题出得很精彩。通常的套路是,如果想合并若干个相邻的元素,可以考虑栈。如果想合并不相邻的元素(归为一类),那么可以考虑并查集。 + +在本题中,每加入一个新元素,我们自然会考虑是否与数组前一个元素互质。如果新元素与前一个元素互质,那么就只能保留。如果不是那么就可以马上合并成为他们的最大公约数(LCM),因为越大的数(即因数越多的数)越容易与其他数字合并。特别注意,合并之后我们还可以持续考察它是否能与再之前的元素合并,比如这个例子```3,2,6```,第二个数2是与第一个数3互质的,但是当第三个数字6出现后,第二个数和第三个数合并成6之后,就可以往前再合并3. 用这个方法就可以把所有相邻的、可以合并的元素都汇聚成一个。 + +事实上,本题上述的贪心策略就对应了栈的基本操作。 From f165397b8f01161a4ee2af32a8281d835d4ee25a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 17:44:48 -0700 Subject: [PATCH 0559/2729] Update Readme.md --- Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md b/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md index e3d8cb1a9..96aff79f8 100644 --- a/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md +++ b/Stack/2197.Replace-Non-Coprime-Numbers-in-Array/Readme.md @@ -4,4 +4,4 @@ 在本题中,每加入一个新元素,我们自然会考虑是否与数组前一个元素互质。如果新元素与前一个元素互质,那么就只能保留。如果不是那么就可以马上合并成为他们的最大公约数(LCM),因为越大的数(即因数越多的数)越容易与其他数字合并。特别注意,合并之后我们还可以持续考察它是否能与再之前的元素合并,比如这个例子```3,2,6```,第二个数2是与第一个数3互质的,但是当第三个数字6出现后,第二个数和第三个数合并成6之后,就可以往前再合并3. 用这个方法就可以把所有相邻的、可以合并的元素都汇聚成一个。 -事实上,本题上述的贪心策略就对应了栈的基本操作。 +事实上,本题上述的贪心策略就模拟了栈的基本操作。 From a3af56d734d38fa75310d361bf362ded90d38429 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 22:18:58 -0700 Subject: [PATCH 0560/2729] Create 2203.Minimum-Weighted-Subgraph-With-the-Required-Paths.cpp --- ...ghted-Subgraph-With-the-Required-Paths.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths.cpp diff --git a/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths.cpp b/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths.cpp new file mode 100644 index 000000000..ec38c9b2f --- /dev/null +++ b/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths.cpp @@ -0,0 +1,56 @@ +using LL = long long; +using PII = pair; + +class Solution { + int n; +public: + long long minimumWeight(int n, vector>& edges, int src1, int src2, int dest) + { + this->n = n; + vector>next(n); + vector>prev(n); + for (auto edge: edges) + { + int a = edge[0], b = edge[1], w = edge[2]; + next[a].push_back({b,w}); + prev[b].push_back({a,w}); + } + + vectorAtoOthers = dijkstra(src1, next); + vectorBtoOthers = dijkstra(src2, next); + vectorCtoOthers = dijkstra(dest, prev); + + LL ret = LLONG_MAX/3; + for (int i=0; idijkstra(int start, vector>&adj) + { + vectordist(n, LLONG_MAX/3); + priority_queue, greater<>>pq; + pq.push({0,start}); + + while (!pq.empty()) + { + auto [d, c] = pq.top(); + pq.pop(); + if (dist[c] < LLONG_MAX/3) + continue; + dist[c] = d; + + for (auto x: adj[c]) + { + LL nxt = x.first, len = x.second; + if (dist[nxt] < LLONG_MAX/3) continue; + pq.push({d+len, nxt}); + } + } + return dist; + } +}; From 61559725f5cdfed189db9bd621990bd9b16c85e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 22:19:36 -0700 Subject: [PATCH 0561/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 050d44597..b352a4d1c 100644 --- a/Readme.md +++ b/Readme.md @@ -507,6 +507,7 @@ [1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (H-) [2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) +[2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From 393c99db96f58ce799df41614c14cf2cbb08dc7b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 22:36:38 -0700 Subject: [PATCH 0562/2729] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths/Readme.md diff --git a/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths/Readme.md b/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths/Readme.md new file mode 100644 index 000000000..7a8322306 --- /dev/null +++ b/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths/Readme.md @@ -0,0 +1,3 @@ +### 2203.Minimum-Weighted-Subgraph-With-the-Required-Paths + +本题的路径模式抽象起来其实就只有一种:就是分别从src1和src2出发的两条路径在某个位置交汇(记做M),然后再从M连通到target。所以本题就是找一个M点,使得M到三个位置(src1,src2,target)的最短路径之和最小。很显然,调用三次Dijkstra算法即可,每次调用求得全局任何位置到指定起点的最短路径,并将其记录下来。 From d0c38d9a8a38387c1fe9a82d40c8a525f25b01c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Mar 2022 23:34:08 -0700 Subject: [PATCH 0563/2729] Update 1514.Path-with-Maximum-Probability_dijkstra.cpp --- ...Path-with-Maximum-Probability_dijkstra.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/Graph/1514.Path-with-Maximum-Probability/1514.Path-with-Maximum-Probability_dijkstra.cpp b/Graph/1514.Path-with-Maximum-Probability/1514.Path-with-Maximum-Probability_dijkstra.cpp index a85bc57c7..7cc8b9d27 100644 --- a/Graph/1514.Path-with-Maximum-Probability/1514.Path-with-Maximum-Probability_dijkstra.cpp +++ b/Graph/1514.Path-with-Maximum-Probability/1514.Path-with-Maximum-Probability_dijkstra.cpp @@ -1,4 +1,4 @@ - +using PDI = pair; class Solution { public: double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) @@ -10,15 +10,14 @@ class Solution { Next[edges[i][1]].push_back({edges[i][0], -log(succProb[i])}); } - set>Set; // {dist, node} - Set.insert({0, start}); vectorprob(n,-1); - - while (!Set.empty()) + priority_queue, greater<>> pq; + pq.push({0, start}); + + while (!pq.empty()) { - double dist = get<0>(*Set.begin()); - int curNode = get<1>(*Set.begin()); - Set.erase(Set.begin()); + auto [dist, curNode] = pq.top(); + pq.pop(); if (prob[curNode]!=-1) continue; prob[curNode] = dist; @@ -30,10 +29,10 @@ class Solution { int nextNode = next.first; double edge = next.second; if (prob[nextNode]!=-1) continue; - Set.insert({dist + edge, nextNode}); + pq.push({dist + edge, nextNode}); } } - + return 0; } }; From ff75067016acf8a07c46ae6fe0996780ce81be6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Mar 2022 13:38:48 -0700 Subject: [PATCH 0564/2729] Create 499.The-Maze-III.cpp --- BFS/499.The-Maze-III/499.The-Maze-III.cpp | 72 +++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 BFS/499.The-Maze-III/499.The-Maze-III.cpp diff --git a/BFS/499.The-Maze-III/499.The-Maze-III.cpp b/BFS/499.The-Maze-III/499.The-Maze-III.cpp new file mode 100644 index 000000000..6bd3383dc --- /dev/null +++ b/BFS/499.The-Maze-III/499.The-Maze-III.cpp @@ -0,0 +1,72 @@ +using TP = tuple; +class Solution { +private: + int m,n; + vector> dir={{1,0},{0,-1},{0,1},{-1,0}}; + +public: + int Next(int i, int j, vector>& maze, int k, vector& hole) + { + int steps=0; + while (i+dir[k].first>=0 && i+dir[k].first=0 && j+dir[k].second>& maze, vector& ball, vector& hole) + { + m = maze.size(); + n = maze[0].size(); + + vector>dist(m, vector(n, INT_MAX)); + vector>inst(m, vector(n, "z")); + + priority_queue, greater<>> pq; + pq.push({0, "", ball[0], ball[1]}); + + while (!pq.empty()) + { + auto [d, s, x, y] = pq.top(); + pq.pop(); + + if (d > dist[x][y]) continue; + dist[x][y] = d; + inst[x][y] = min(inst[x][y], s); + + if (x==hole[0] && y==hole[1]) continue; + + for (int k=0; k<4; k++) + { + int step = Next(x,y,maze,k,hole); + int i = x+dir[k].first*step; + int j = y+dir[k].second*step; + + char ch='0'+k; + if (d+step > dist[i][j]) continue; + if (d+step == dist[i][j] && (s+ch) >= inst[i][j]) continue; + pq.push({d+step, s+ch, i, j}); + } + } + + if (dist[hole[0]][hole[1]]==INT_MAX) + return "impossible"; + + string ret = inst[hole[0]][hole[1]]; + for (int i=0; i Date: Mon, 14 Mar 2022 13:39:53 -0700 Subject: [PATCH 0565/2729] Update Readme.md --- Readme.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index b352a4d1c..2c1f6cfb2 100644 --- a/Readme.md +++ b/Readme.md @@ -498,14 +498,15 @@ [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) [778.Swim-in-Rising-Water](https://github.com/wisdompeak/LeetCode/tree/master/BFS/778.Swim-in-Rising-Water) (H) -[505.The-Maze-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/505.The-Maze-II) (H) -[787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H-) +[505.The-Maze-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/505.The-Maze-II) (H-) +[499.The-Maze-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/499.The-Maze-III) (H) +[787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) [882.Reachable-Nodes-In-Subdivided-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/882.Reachable-Nodes-In-Subdivided-Graph ) (H) [1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid) (H) [1514.Path-with-Maximum-Probability](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1514.Path-with-Maximum-Probability) (H) -[1786.Number-of-Restricted-Paths-From-First-to-Last-Node](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1786.Number-of-Restricted-Paths-From-First-to-Last-Node) (H-) +[1786.Number-of-Restricted-Paths-From-First-to-Last-Node](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1786.Number-of-Restricted-Paths-From-First-to-Last-Node) (M+) [1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) -[1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (H-) +[1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (M+) [2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) * ``Dijkstra (for Bipatite Graph)`` From d21e0ea04720f5f3c99e11a98621254b4b2a4380 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Mar 2022 13:47:55 -0700 Subject: [PATCH 0566/2729] Create Readme.md --- BFS/499.The-Maze-III/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 BFS/499.The-Maze-III/Readme.md diff --git a/BFS/499.The-Maze-III/Readme.md b/BFS/499.The-Maze-III/Readme.md new file mode 100644 index 000000000..bac76a9da --- /dev/null +++ b/BFS/499.The-Maze-III/Readme.md @@ -0,0 +1,7 @@ +### 499.The-Maze-III + +此题在505.The-Maze-II的基础上增加了一个条件:在最短距离相同的情况下,要更新为字典序最小的instruction。 + +LC 505是单纯地求最短路径,所以无脑使用Dijkstra算法:任何一个节点(记做X)第一次被弹出PQ时,所对应的dist就是该点X到原点的最短距离。当X在第二次或之后被弹出PQ时可以直接忽视。就算不直接忽视,你校验一下路径距离,肯定也不会更优。所以Dijkstra算法的最大好处就是有机会提前终止(如果只考察目标点target)。 + +但是本题则略微不同。当X第二次被弹出PQ时,有可能路径与之前登记的相同、但是instruction的字典序更优。在这种情况下,我们就不能直接忽视这个X,而是需要主动检验,如果满足“路径相等并且instruction更优”,就要更新关于X点的记录,并且必须将从X出发的邻接节点再次放入PQ里面。所以在本题里,我们必须让整个PQ主动跑完(变成空),而不能遇到target时就终止程序。 From 563399b6c89515998537b7c27f1448dfca1ae0cb Mon Sep 17 00:00:00 2001 From: dzf0023 Date: Mon, 14 Mar 2022 21:41:50 -0500 Subject: [PATCH 0567/2729] Create basic_calculator.java --- .../basic_calculator.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Stack/224.Basic-Calculator/basic_calculator.java diff --git a/Stack/224.Basic-Calculator/basic_calculator.java b/Stack/224.Basic-Calculator/basic_calculator.java new file mode 100644 index 000000000..0d3c461e3 --- /dev/null +++ b/Stack/224.Basic-Calculator/basic_calculator.java @@ -0,0 +1,43 @@ +class Solution { + public int calculate(String s) { + + StringBuilder sb = new StringBuilder(); + sb.append("+"); + for(char c: s.toCharArray()){ + if(c == ' ') continue; + sb.append(c); + if(c == '('){ + sb.append("+"); + } + } + Deque nums = new ArrayDeque<>(); + Deque signs = new ArrayDeque<>(); + int sum = 0; + int sign = 0; + + for(int i = 0; i < sb.length(); i++){ + if(sb.charAt(i) == '+' || sb.charAt(i) == '-' ){ + sign = sb.charAt(i) == '+' ? 1 : -1; + }else if(Character.isDigit(sb.charAt(i))){ + int cur = 0; + int j = i; + while(j < sb.length() && Character.isDigit(sb.charAt(j))){ + cur = cur * 10 + (sb.charAt(j) - '0'); + + j+=1; + } + i = j-1; + sum += cur * sign; + }else if(sb.charAt(i) == '('){ + nums.addFirst(sum); + signs.addFirst(sign); + sum = 0; + }else if(sb.charAt(i) == ')'){ + sum = nums.pollFirst() + signs.pollFirst() * sum; + + } + } + + return sum; + } +} From 5518ba1f41b8deb8708bff110f54cb957dace29a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Mar 2022 22:58:57 -0700 Subject: [PATCH 0568/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 2c1f6cfb2..84dd28e0b 100644 --- a/Readme.md +++ b/Readme.md @@ -442,6 +442,7 @@ [638.Shopping-Offers](https://github.com/wisdompeak/LeetCode/tree/master/DFS/638.Shopping-Offers) (M+) [403.Frog-Jump](https://github.com/wisdompeak/LeetCode/tree/master/DFS/403.Frog-Jump) (M+) [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) +[1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) [1340.Jump-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1340.Jump-Game-V) (M+) [1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) From 7a2413a88720cbdfe1b4febd74b9a942b2d51901 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Mar 2022 23:22:49 -0700 Subject: [PATCH 0569/2729] Update 1810.Minimum-Path-Cost-in-a-Hidden-Grid.cpp --- ...810.Minimum-Path-Cost-in-a-Hidden-Grid.cpp | 72 +++++++++---------- 1 file changed, 35 insertions(+), 37 deletions(-) diff --git a/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid/1810.Minimum-Path-Cost-in-a-Hidden-Grid.cpp b/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid/1810.Minimum-Path-Cost-in-a-Hidden-Grid.cpp index c8fbb82ff..b064313d5 100644 --- a/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid/1810.Minimum-Path-Cost-in-a-Hidden-Grid.cpp +++ b/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid/1810.Minimum-Path-Cost-in-a-Hidden-Grid.cpp @@ -24,20 +24,46 @@ class Solution { for (int j=0; j<201; j++) cost[i][j] = -1; - visited[100][100] = 1; - dfs(master, 100, 100); + int x0 = 100, y0 = 100; + dfs(master, x0, y0); + return dijkstra(x0, y0); + } + + void dfs(GridMaster &master, int x, int y) + { + if(visited[x][y]==1) return; + visited[x][y] = 1; - for (int i=0; i<201; i++) - for (int j=0; j<201; j++) - visited[i][j] = 0; - + if (master.isTarget()) + { + targetX = x; + targetY = y; + } + + for (int k=0; k<4; k++) + { + if (master.canMove(d[k])) + { + int i = x+dir[k].first; + int j = y+dir[k].second; + cost[i][j] = master.move(d[k]); + dfs(master, i,j); + master.move(d[3-k]); + } + } + } + + int dijkstra(int x0, int y0) + { + vector>visited(201, vector(201)); priority_queue, greater<>>pq; - pq.push({0,100,100}); + pq.push({0,x0,y0}); while (!pq.empty()) { auto [c,x,y] = pq.top(); pq.pop(); + if (visited[x][y]==1) continue; visited[x][y] = 1; if (x==targetX && y==targetY) return c; @@ -46,43 +72,15 @@ class Solution { { int i = x+dir[k].first; int j = y+dir[k].second; - if (cost[i][j]==-1) continue; if (i<0 || i>=200 || j<0|| j>=200) continue; + if (cost[i][j]==-1) continue; if (visited[i][j]==1) continue; pq.push({c+cost[i][j], i, j}); } } - return -1; + return -1; } - void dfs(GridMaster &master, int x, int y) - { - - if (master.isTarget()) - { - targetX = x; - targetY = y; - } - for (int k=0; k<4; k++) - { - int i = x+dir[k].first; - int j = y+dir[k].second; - if(visited[i][j]==1) continue; - - if (master.canMove(d[k])) - { - int c = master.move(d[k]); - visited[i][j] = 1; - cost[i][j] = c; - dfs(master, i,j); - master.move(d[3-k]); - } - else - { - visited[i][j] = 1; - } - } - } }; From 683a7a18affe288bb3fff36ee64b784469a1f5e5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Mar 2022 23:32:58 -0700 Subject: [PATCH 0570/2729] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index 84dd28e0b..4328e7c36 100644 --- a/Readme.md +++ b/Readme.md @@ -423,7 +423,6 @@ [1718.Construct-the-Lexicographically-Largest-Valid-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1718.Construct-the-Lexicographically-Largest-Valid-Sequence) (H-) [1723.Find-Minimum-Time-to-Finish-All-Jobs](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1723.Find-Minimum-Time-to-Finish-All-Jobs) (H-) [1766.Tree-of-Coprimes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1766.Tree-of-Coprimes) (H-) -[1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) [2014.Longest-Subsequence-Repeated-k-Times](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2014.Longest-Subsequence-Repeated-k-Times) (H) [2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) [2065.Maximum-Path-Quality-of-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2065.Maximum-Path-Quality-of-a-Graph) (M) @@ -441,11 +440,13 @@ [329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix) (M) [638.Shopping-Offers](https://github.com/wisdompeak/LeetCode/tree/master/DFS/638.Shopping-Offers) (M+) [403.Frog-Jump](https://github.com/wisdompeak/LeetCode/tree/master/DFS/403.Frog-Jump) (M+) -[489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) -[1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) [1340.Jump-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1340.Jump-Game-V) (M+) [1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +* ``hidden matrix`` +[489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) +[1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) +[1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) #### [BFS](https://github.com/wisdompeak/LeetCode/tree/master/BFS) [127.Word-Ladder](https://github.com/wisdompeak/LeetCode/tree/master/BFS/127.Word-Ladder) (M+) From a256da0b298eb55978a5dc16cc5a66b9a41f9ccb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Mar 2022 23:48:00 -0700 Subject: [PATCH 0571/2729] Update 2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp --- ...nimum-Cost-to-Reach-City-With-Discounts.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp b/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp index ed2e5eaf3..e09121a60 100644 --- a/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp +++ b/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp @@ -11,27 +11,27 @@ class Solution { next[x[1]].push_back({x[0], x[2]}); } - vector>dist(n, vector(discounts+1, INT_MAX)); + vector>cost(n, vector(discounts+1, INT_MAX)); priority_queue, greater<>>pq; - pq.push({0,0,discounts}); // {dist, node, discounts} + pq.push({0,0,discounts}); // {cost, node, discounts} while (!pq.empty()) { - auto [d, curNode, times] = pq.top(); + auto [c, curNode, times] = pq.top(); pq.pop(); - if (d >= dist[curNode][times]) continue; - dist[curNode][times] = d; - if (curNode==n-1) return d; + if (c >= cost[curNode][times]) continue; + cost[curNode][times] = c; + if (curNode==n-1) return c; for (auto nxt: next[curNode]) { auto [nxtNode, len] = nxt; - if (dist[nxtNode][times]!=INT_MAX) continue; - pq.push({d+len, nxtNode, times}); + if (cost[nxtNode][times]!=INT_MAX) continue; + pq.push({c+len, nxtNode, times}); if (times>=1) - pq.push({d+len/2, nxtNode, times-1}); + pq.push({c+len/2, nxtNode, times-1}); } } From 756f5ec6c63df1b0c2975051f093470190f56634 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Mar 2022 23:24:00 -0700 Subject: [PATCH 0572/2729] Update Readme.md --- Graph/787.Cheapest-Flights-Within-K-Stops/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/787.Cheapest-Flights-Within-K-Stops/Readme.md b/Graph/787.Cheapest-Flights-Within-K-Stops/Readme.md index 7a44c6ed1..8ad4f1bb7 100644 --- a/Graph/787.Cheapest-Flights-Within-K-Stops/Readme.md +++ b/Graph/787.Cheapest-Flights-Within-K-Stops/Readme.md @@ -40,7 +40,7 @@ dp[b] = min(dp[k][b], dp[k-1][b], dp[k-1][a] + cost[a][b]), where there is a fli ### 解法3:BFS(Dijkstra) 利用Dijkstra求最短权重路径的算法思想,可以简单的理解为基于优先队列的BFS。从起点src开始不停地做BFS,但是队列里弹出的永远是权重最小的路径(所达到的点)。这样任何弹出的点,如果是第一次到达的话,那么它一定经历的是最短路径。所以,一旦BFS的过程中遇到了终点,就可以输出它的最短代价。 -但是本题不同之处在于,对于任何中转点(非终点),最短路径不一定就是最优方案,因为还有转机次数的考虑因素。举个例子,假设最多允许转机5次,一种方案是你转机3次花费10到达A地(非终点),另一种方案是转机4次花费8到达B地,对于后续的影响而言孰优孰劣我们是无法判断的。所以我们必须将它们都加入BFS的队列之中。当然,如果之前曾经以相同的转机次数到达过A,那么我们肯定只会保留最小代价的方案,所以我们需要一个visited[city][times]来记忆化之前所经历过的代价。 +但是本题不同之处在于,对于任何中转点(非终点),最短路径不一定就是最优方案,因为还有转机次数的考虑因素。举个例子,假设最多允许转机5次,一种方案是你转机3次花费10到达A地(非终点),另一种方案是转机4次花费8到达A,对于后续的影响而言孰优孰劣我们是无法判断的。所以我们必须将它们都加入BFS的队列之中。当然,如果之前曾经以相同的转机次数到达过A,那么我们肯定只会保留最小代价的方案,所以我们需要一个visited[city][times]来记忆化之前所经历过的代价。 From 3063b3c2dcc79502c3f97552293aa592f1344c67 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Mar 2022 23:44:02 -0700 Subject: [PATCH 0573/2729] Update and rename 787.Cheapest-Flights-Within-K-Stops_bfs.cpp to 787.Cheapest-Flights-Within-K-Stops_Dijkstra.cpp --- ...eapest-Flights-Within-K-Stops_Dijkstra.cpp | 37 +++++++++++++++++++ ...87.Cheapest-Flights-Within-K-Stops_bfs.cpp | 37 ------------------- 2 files changed, 37 insertions(+), 37 deletions(-) create mode 100644 Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_Dijkstra.cpp delete mode 100644 Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_bfs.cpp diff --git a/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_Dijkstra.cpp b/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_Dijkstra.cpp new file mode 100644 index 000000000..cd558a79b --- /dev/null +++ b/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_Dijkstra.cpp @@ -0,0 +1,37 @@ +using AI3 = array; +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int K) + { + vector>>next(n); + for (auto flight: flights) + { + int a = flight[0], b = flight[1], w = flight[2]; + next[a].push_back({b, w}); + } + + vector>cost(n, vector(K+2, INT_MAX/2)); + priority_queue, greater<>>pq; + pq.push({0, src, 0}); + + while (!pq.empty()) + { + auto [c, cur, stops] = pq.top(); + pq.pop(); + + if (cur == dst) return c; + if (stops == K+1) continue; + if (cost[cur][stops] < INT_MAX/2) continue; + cost[cur][stops] = c; + + for (auto ticket: next[cur]) + { + auto [nxt, price] = ticket; + if (cost[nxt][stops+1] < INT_MAX/2) continue; + pq.push({c+price, nxt, stops+1}); + } + } + + return -1; + } +}; diff --git a/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_bfs.cpp b/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_bfs.cpp deleted file mode 100644 index c9c5d44d6..000000000 --- a/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_bfs.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution { -public: - int findCheapestPrice(int n, vector>& flights, int src, int dst, int K) - { - vector>>graph(n); - for (auto flight: flights) - graph[flight[0]].push_back({flight[1], flight[2]}) ; - - auto visited = vector>(n, vector(K+2, INT_MAX/2)); - visited[src][0] = 0; - multiset>Set; - Set.insert({0, 0, src}); - - while (!Set.empty()) - { - int cost = (*Set.begin())[0]; - int step = (*Set.begin())[1]; - int cur = (*Set.begin())[2]; - Set.erase(Set.begin()); - - if (cur==dst) return cost; - if (step == K+1) continue; - - for (auto ticket: graph[cur]) - { - if (cost + ticket[1] < visited[ticket[0]][step+1]) - { - visited[ticket[0]][step+1] = cost + ticket[1]; - Set.insert({cost+ticket[1], step+1, ticket[0]}); - } - } - } - - return -1; - - } -}; From 2c19eaa359893bef1c6dc945bd128ed8449ab4ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 16 Mar 2022 00:16:28 -0700 Subject: [PATCH 0574/2729] Update 787.Cheapest-Flights-Within-K-Stops_DP.cpp --- ...787.Cheapest-Flights-Within-K-Stops_DP.cpp | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_DP.cpp b/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_DP.cpp index df4c8656d..d9877d2ca 100644 --- a/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_DP.cpp +++ b/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops_DP.cpp @@ -2,23 +2,18 @@ class Solution { public: int findCheapestPrice(int n, vector>& flights, int src, int dst, int K) { - auto dp = vector>(K+2, vector(n, INT_MAX/2)); - dp[0][src] = 0; - - for (int k=1; k<=K+1; k++) - { + vector>dp(n, vector(K+2, INT_MAX/2)); + dp[src][0] = 0; + int ret = INT_MAX/2; + + for (int j=1; j<=K+1; j++) for (auto flight: flights) { - int a = flight[0]; - int b = flight[1]; - int w = flight[2]; - dp[k][b] = min(dp[k][b], dp[k-1][b]); - dp[k][b] = min(dp[k][b], dp[k-1][a]+w); + int a = flight[0], b = flight[1], p = flight[2]; + dp[b][j] = min(dp[b][j], dp[a][j-1]+p); + if (b==dst) ret = min(ret, dp[b][j]); } - } - - int ret = dp[K+1][dst]; - - return (ret>=INT_MAX/2) ? -1 : ret; + + return ret >= INT_MAX/2 ? -1 : ret; } }; From 447bee460c6edb2d74cf140085047badb32648ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 16 Mar 2022 02:39:21 -0700 Subject: [PATCH 0575/2729] Update Readme.md --- .../1000.Minimum-Cost-to-Merge-Stones/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/1000.Minimum-Cost-to-Merge-Stones/Readme.md b/Dynamic_Programming/1000.Minimum-Cost-to-Merge-Stones/Readme.md index e67eb5b44..e9ef812bc 100644 --- a/Dynamic_Programming/1000.Minimum-Cost-to-Merge-Stones/Readme.md +++ b/Dynamic_Programming/1000.Minimum-Cost-to-Merge-Stones/Readme.md @@ -2,7 +2,7 @@ 这道题的最后一步是将已经merge成K堆的石子做最后一步简单的合并。所以,问题的关键就是变成如何最优化地将原本N堆石子合并成K堆石子,换句话说,需要将[0,N-1]分成K个区间。对于分成K个区间的DP题而言,我们显然会考虑如何先把第一个区间确定,那么其余的就是在剩下的元素里分成K-1个区间。这是比较常见的思路。 -所以本题的状态设计为dp[i][j][k],表示我们将从第i个到第j个元素,拆分成k个区间的最小cost是多少。根据上面的想法,我们需要遍历第一个区间可能的范围(即拆分位置m),寻找最优的拆分。也就是 +所以本题的状态设计为dp[i][j][k],表示我们将从第i个到第j个元素,归并成k个区间的最小cost是多少。根据上面的想法,我们需要遍历第一个区间可能的范围(即拆分位置m),寻找最优的拆分。也就是 ``` dp[i][j][k] = min(dp[i][m][1]+dp[m+1][j][k-1]) for i<=m Date: Mon, 21 Mar 2022 20:50:21 -0700 Subject: [PATCH 0576/2729] Update 2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp --- ...imum-Cost-to-Reach-City-With-Discounts.cpp | 42 +++++++++---------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp b/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp index e09121a60..21df69f74 100644 --- a/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp +++ b/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts/2093.Minimum-Cost-to-Reach-City-With-Discounts.cpp @@ -1,41 +1,39 @@ -using PII = pair; using AI3 = array; class Solution { public: int minimumCost(int n, vector>& highways, int discounts) { - vector>next(n); + vector>>next(n); for (auto x: highways) { - next[x[0]].push_back({x[1], x[2]}); - next[x[1]].push_back({x[0], x[2]}); + int a = x[0], b = x[1], w = x[2]; + next[a].push_back({b, w}); + next[b].push_back({a, w}); } - - vector>cost(n, vector(discounts+1, INT_MAX)); - priority_queue, greater<>>pq; - pq.push({0,0,discounts}); // {cost, node, discounts} - + vector>cost(n, vector(discounts+1, INT_MAX)); // cost[city][discounts] + priority_queue, greater<>> pq; // {cost, city, discounts} + pq.push({0,0,discounts}); + while (!pq.empty()) { - auto [c, curNode, times] = pq.top(); + auto [c, cur, times] = pq.top(); pq.pop(); - if (c >= cost[curNode][times]) continue; - cost[curNode][times] = c; - if (curNode==n-1) return c; + if (c >= cost[cur][times]) continue; + cost[cur][times] = c; + if (cur == n-1) return c; - for (auto nxt: next[curNode]) + for (auto x: next[cur]) { - auto [nxtNode, len] = nxt; - if (cost[nxtNode][times]!=INT_MAX) continue; - pq.push({c+len, nxtNode, times}); - if (times>=1) - pq.push({c+len/2, nxtNode, times-1}); - } + auto [nxt, toll] = x; + if (cost[nxt][times]==INT_MAX) + pq.push({c+toll, nxt, times}); + if (times >= 1 && cost[nxt][times-1]==INT_MAX) + pq.push({c+toll/2, nxt, times-1}); + } } - return -1; - + return -1; } }; From 612d115ddacd3ca0dc71709fde758a6402f167e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 22 Mar 2022 23:39:18 -0700 Subject: [PATCH 0577/2729] Create 2202.Maximize-the-Topmost-Element-After-K-Moves.cpp --- ...mize-the-Topmost-Element-After-K-Moves.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves/2202.Maximize-the-Topmost-Element-After-K-Moves.cpp diff --git a/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves/2202.Maximize-the-Topmost-Element-After-K-Moves.cpp b/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves/2202.Maximize-the-Topmost-Element-After-K-Moves.cpp new file mode 100644 index 000000000..a633b13c9 --- /dev/null +++ b/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves/2202.Maximize-the-Topmost-Element-After-K-Moves.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maximumTop(vector& nums, int K) + { + int n = nums.size(); + int ret = INT_MIN; + for (int i=1; i<=n; i++) + { + int k = K; + if (k1) + flag = 1; + + if (flag) ret = max(ret, nums[i-1]); + } + return ret==INT_MIN? -1:ret; + } +}; From e56393ea85a742a16ce6427b4f94041ec815d222 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 22 Mar 2022 23:39:43 -0700 Subject: [PATCH 0578/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4328e7c36..fbe045b8d 100644 --- a/Readme.md +++ b/Readme.md @@ -1139,6 +1139,7 @@ [2007.Find-Original-Array-From-Doubled-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2007.Find-Original-Array-From-Doubled-Array) (M) [2122.Recover-the-Original-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2122.Recover-the-Original-Array) (H-) [1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) +[2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From cefe4296eeb18989fffd1a1e06d9a378b53a958d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 23 Mar 2022 00:04:39 -0700 Subject: [PATCH 0579/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves/Readme.md diff --git a/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves/Readme.md b/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves/Readme.md new file mode 100644 index 000000000..533bde3bc --- /dev/null +++ b/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves/Readme.md @@ -0,0 +1,15 @@ +### 2202.Maximize-the-Topmost-Element-After-K-Moves + +我们逐个元素考虑,对于第i个元素(以1-index记),它能否被K次操作之后排在队列的首位? + +首先,我们为了将第i个元素放在首位,我们必须把前i-1个元素拿掉。这i-1次的remove操作是可以提前做而不影响最终结果的。注意,push的操作不能提前做,因为必须要先有removed的元素才能使得push操作有意义;反之,remove的操作不依赖于push,可以放心地提前。 + +将k自减i-1后,我们的目标元素就已经在队列首位了。此时假设我们还有k次操作要做,那么就分情况讨论。 + +1. k==0,那么无需操作,现状就是期待的效果 +2. k==1,那么此时我们无论是remove还是push,都无法再让第i个元素出现在队列首位了。 +3. 如果k是偶数,那么显然,我们可以通过反复remove和push队首元素,使得第i个元素始终保持在队列首位。 +4. 如果k是奇数,其实也有办法。那就是先remove当前的两个元素、再push回第i个元素。然后再反复remove和push第i个元素,消耗偶数次的操作。注意,这个方法的前提是存在第i+1个元素。 +5. 类似于4有一种容易被忽略的想法。那就是先remove第i个元素,再依次push会第i-1个元素和第i个元素。然后再反复remove和push第i元素,消耗偶数次的操作。注意这个方法不需要存在第i+1个元素,但需要存在第i-1个元素。 + +以上几种情况能保证第i个元素能通过操作后被放置在队列首位。我们在所有符合条件的元素里找最大值即可。 From b1bc3478e2e96dce42411613f1e2b9380abd1fb5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 23 Mar 2022 23:55:25 -0700 Subject: [PATCH 0580/2729] Create 2209.Minimum-White-Tiles-After-Covering-With-Carpets.cpp --- ...hite-Tiles-After-Covering-With-Carpets.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets/2209.Minimum-White-Tiles-After-Covering-With-Carpets.cpp diff --git a/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets/2209.Minimum-White-Tiles-After-Covering-With-Carpets.cpp b/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets/2209.Minimum-White-Tiles-After-Covering-With-Carpets.cpp new file mode 100644 index 000000000..c95b76519 --- /dev/null +++ b/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets/2209.Minimum-White-Tiles-After-Covering-With-Carpets.cpp @@ -0,0 +1,22 @@ +class Solution { + int dp[1001][1001]; +public: + int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) + { + int n = floor.size(); + floor = "#"+floor; + + dp[0][0] = 0; + for (int i=1; i<=n; i++) + for (int j=0; j<=numCarpets; j++) + { + dp[i][j] = INT_MAX/2; + dp[i][j] = min(dp[i][j], dp[i-1][j] + (floor[i]=='1')); + if (j>=1) + dp[i][j] = min(dp[i][j], i>=carpetLen ? dp[i-carpetLen][j-1]:0); + } + + return dp[n][numCarpets]; + + } +}; From 6354059871b5b1e1a34dece00d2d2d96a347c8a3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 23 Mar 2022 23:56:02 -0700 Subject: [PATCH 0581/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fbe045b8d..ef9fcfe6e 100644 --- a/Readme.md +++ b/Readme.md @@ -640,6 +640,7 @@ [1626.Best-Team-With-No-Conflicts](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1626.Best-Team-With-No-Conflicts) (M) [1691.Maximum-Height-by-Stacking-Cuboids](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1691.Maximum-Height-by-Stacking-Cuboids) (H) [2188.Minimum-Time-to-Finish-the-Race](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race) (H-) +[2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) From 80372c58a119bd101e0dd022bb7c248ef8c4791c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Mar 2022 22:17:57 -0700 Subject: [PATCH 0582/2729] Update 499.The-Maze-III.cpp --- BFS/499.The-Maze-III/499.The-Maze-III.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/BFS/499.The-Maze-III/499.The-Maze-III.cpp b/BFS/499.The-Maze-III/499.The-Maze-III.cpp index 6bd3383dc..95d876b49 100644 --- a/BFS/499.The-Maze-III/499.The-Maze-III.cpp +++ b/BFS/499.The-Maze-III/499.The-Maze-III.cpp @@ -25,7 +25,7 @@ class Solution { n = maze[0].size(); vector>dist(m, vector(n, INT_MAX)); - vector>inst(m, vector(n, "z")); + string ret; priority_queue, greater<>> pq; pq.push({0, "", ball[0], ball[1]}); @@ -36,10 +36,13 @@ class Solution { pq.pop(); if (d > dist[x][y]) continue; - dist[x][y] = d; - inst[x][y] = min(inst[x][y], s); + dist[x][y] = d; - if (x==hole[0] && y==hole[1]) continue; + if (x==hole[0] && y==hole[1]) + { + ret = s; + break; + } for (int k=0; k<4; k++) { @@ -48,8 +51,7 @@ class Solution { int j = y+dir[k].second*step; char ch='0'+k; - if (d+step > dist[i][j]) continue; - if (d+step == dist[i][j] && (s+ch) >= inst[i][j]) continue; + if (d+step >= dist[i][j]) continue; pq.push({d+step, s+ch, i, j}); } } @@ -57,7 +59,6 @@ class Solution { if (dist[hole[0]][hole[1]]==INT_MAX) return "impossible"; - string ret = inst[hole[0]][hole[1]]; for (int i=0; i Date: Thu, 24 Mar 2022 22:26:57 -0700 Subject: [PATCH 0583/2729] Update Readme.md --- BFS/499.The-Maze-III/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BFS/499.The-Maze-III/Readme.md b/BFS/499.The-Maze-III/Readme.md index bac76a9da..fd7c33027 100644 --- a/BFS/499.The-Maze-III/Readme.md +++ b/BFS/499.The-Maze-III/Readme.md @@ -1,7 +1,7 @@ ### 499.The-Maze-III -此题在505.The-Maze-II的基础上增加了一个条件:在最短距离相同的情况下,要更新为字典序最小的instruction。 +此题在505.The-Maze-II的基础上增加了一个条件:在最短距离相同的情况下,要更新为字典序最小的指令。 -LC 505是单纯地求最短路径,所以无脑使用Dijkstra算法:任何一个节点(记做X)第一次被弹出PQ时,所对应的dist就是该点X到原点的最短距离。当X在第二次或之后被弹出PQ时可以直接忽视。就算不直接忽视,你校验一下路径距离,肯定也不会更优。所以Dijkstra算法的最大好处就是有机会提前终止(如果只考察目标点target)。 +事实上本题与505并没有太大的区别,只不过优先队列的比较函数里增加一个条件:当(离源点)路径距离相等的时候,将路径指令的字典序更小的节点排在更前面。这样当终点第一次从优先队列里弹出的时候,不仅对应的距离最短,而且如果有多个相同距离的路径的话,指令也是最小的。 -但是本题则略微不同。当X第二次被弹出PQ时,有可能路径与之前登记的相同、但是instruction的字典序更优。在这种情况下,我们就不能直接忽视这个X,而是需要主动检验,如果满足“路径相等并且instruction更优”,就要更新关于X点的记录,并且必须将从X出发的邻接节点再次放入PQ里面。所以在本题里,我们必须让整个PQ主动跑完(变成空),而不能遇到target时就终止程序。 +有人会疑问,当终点第一次从队列里弹出的时候,固然对应着距离最短的路径,那么怎么保证所有该有着相同最短距离、但指令不同的路径都已经进入队列了呢?这是因为,假设终点第一次弹出队列所对应的路径长度是x,那么此时所有路径长度小于x的路径必然已经都弹出队列了,他们的后续路径必然包括了所有以距离x达到终点的路径。 From cd1de1d46d53d0f773f1ead4333aa03b8da591af Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Mar 2022 23:33:30 -0700 Subject: [PATCH 0584/2729] Update 499.The-Maze-III.cpp --- BFS/499.The-Maze-III/499.The-Maze-III.cpp | 76 +++++++++++------------ 1 file changed, 35 insertions(+), 41 deletions(-) diff --git a/BFS/499.The-Maze-III/499.The-Maze-III.cpp b/BFS/499.The-Maze-III/499.The-Maze-III.cpp index 95d876b49..ceba9d8cf 100644 --- a/BFS/499.The-Maze-III/499.The-Maze-III.cpp +++ b/BFS/499.The-Maze-III/499.The-Maze-III.cpp @@ -1,64 +1,44 @@ -using TP = tuple; +using TP = tuple; class Solution { -private: + vector>dir = {{1,0},{0,-1},{0,1},{-1,0}}; // d,l,r,u int m,n; - vector> dir={{1,0},{0,-1},{0,1},{-1,0}}; - public: - int Next(int i, int j, vector>& maze, int k, vector& hole) - { - int steps=0; - while (i+dir[k].first>=0 && i+dir[k].first=0 && j+dir[k].second>& maze, vector& ball, vector& hole) { - m = maze.size(); - n = maze[0].size(); - - vector>dist(m, vector(n, INT_MAX)); - string ret; + m = maze.size(), n = maze[0].size(); - priority_queue, greater<>> pq; + priority_queue, greater<>>pq; // {dist, string, node_x, node_y} pq.push({0, "", ball[0], ball[1]}); + vector>dist(m, vector(n,INT_MAX)); + string ret; + while (!pq.empty()) { auto [d, s, x, y] = pq.top(); pq.pop(); - if (d > dist[x][y]) continue; - dist[x][y] = d; - - if (x==hole[0] && y==hole[1]) + if (d > dist[x][y]) continue; + else dist[x][y] = d; + + if (x==hole[0] && y==hole[1]) { ret = s; break; } for (int k=0; k<4; k++) - { - int step = Next(x,y,maze,k,hole); - int i = x+dir[k].first*step; - int j = y+dir[k].second*step; - - char ch='0'+k; - if (d+step >= dist[i][j]) continue; + { + int step = Next(x,y,k,maze, hole); + int i = x + dir[k].first * step; + int j = y + dir[k].second * step; + + char ch = '0'+k; + if (d+step >= dist[i][j]) continue; pq.push({d+step, s+ch, i, j}); - } + } } - if (dist[hole[0]][hole[1]]==INT_MAX) - return "impossible"; - for (int i=0; i>& maze, vector& hole) + { + int step = 0; + while (x+dir[k].first >= 0 && x+dir[k].first < m && y+dir[k].second >= 0 && y+dir[k].second < n && maze[x+dir[k].first][y+dir[k].second]!=1) + { + step++; + x+=dir[k].first; + y+=dir[k].second; + if (x==hole[0] && y==hole[1]) + break; + } + return step; } }; From b8b1faf9715c9663caafefe6ea7282e1a6680196 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 25 Mar 2022 22:16:54 -0700 Subject: [PATCH 0585/2729] Update 291.Word-Pattern-II.cpp --- DFS/291.Word-Pattern-II/291.Word-Pattern-II.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/DFS/291.Word-Pattern-II/291.Word-Pattern-II.cpp b/DFS/291.Word-Pattern-II/291.Word-Pattern-II.cpp index 05213c83a..5110d5eb0 100644 --- a/DFS/291.Word-Pattern-II/291.Word-Pattern-II.cpp +++ b/DFS/291.Word-Pattern-II/291.Word-Pattern-II.cpp @@ -10,8 +10,7 @@ class Solution { bool dfs(int x, int y, string& pattern, string& s) { - if (x==pattern.size() && y==s.size()) - return true; + if (x==pattern.size()) return y==s.size(); char ch = pattern[x]; if (Map1.find(ch)!=Map1.end()) From 3b9db1be9743c6516c4742ce78b46bb8cb231820 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 25 Mar 2022 23:44:14 -0700 Subject: [PATCH 0586/2729] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets/Readme.md diff --git a/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets/Readme.md b/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets/Readme.md new file mode 100644 index 000000000..347b4064e --- /dev/null +++ b/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets/Readme.md @@ -0,0 +1,10 @@ +### 2209.Minimum-White-Tiles-After-Covering-With-Carpets + +令dp[i][j]表示前i个格子用j块地毯覆盖,留有的最小白色区域。显然我们分两种情况讨论。 + +1. 如果第i个格子我们不用第j块地毯,那么我们会关注前i-1个格子用j块地毯的覆盖情况,再加上第i个格子本身是否是白色。即```dp[i][j] = dp[i-1][j] + (s[i]=='1')``` +2. 如果第i个格子我们用了第j块地毯,那么这块地毯覆盖了carpetLen的区域。为了尽量节约使用地毯,我们必然希望这块地毯的效用最大化,也就是说,我们必然会把前j-1块地毯用来覆盖前i-carpetLen个格子。故```dp[i][j] = dp[i-carpetLen][j-1]```. + +我们在以上两种方案中取最大值。 + +需要注意的是在第二种情况里,如果```i-carpetLen<=0```怎么办?容易判断,在没有任何格子的情况下,所谓“留有的白色区域”自然也是0。 From c0f60742905a2fc8b538c225f0eba598c43f498b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Mar 2022 16:22:12 -0700 Subject: [PATCH 0587/2729] Create 2216.Minimum-Deletions-to-Make-Array-Beautiful.cpp --- ...imum-Deletions-to-Make-Array-Beautiful.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful/2216.Minimum-Deletions-to-Make-Array-Beautiful.cpp diff --git a/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful/2216.Minimum-Deletions-to-Make-Array-Beautiful.cpp b/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful/2216.Minimum-Deletions-to-Make-Array-Beautiful.cpp new file mode 100644 index 000000000..00eab6dba --- /dev/null +++ b/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful/2216.Minimum-Deletions-to-Make-Array-Beautiful.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int minDeletion(vector& nums) + { + int n = nums.size(); + int ret = 0; + + int i = 0; + + while (i Date: Sun, 27 Mar 2022 16:23:13 -0700 Subject: [PATCH 0588/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ef9fcfe6e..ff8dde018 100644 --- a/Readme.md +++ b/Readme.md @@ -1010,7 +1010,6 @@ [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) -[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H) [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [659.Split-Array-into-Consecutive-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/659.Split-Array-into-Consecutive-Subsequences) (H) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (H) @@ -1061,6 +1060,7 @@ [2171.Removing-Minimum-Number-of-Magic-Beans](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2171.Removing-Minimum-Number-of-Magic-Beans) (M) [2182.Construct-String-With-Repeat-Limit](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2182.Construct-String-With-Repeat-Limit) (M+) [2193.Minimum-Number-of-Moves-to-Make-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome) (H+) +[2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From ecb8afcb903a6d49c484a026dad414f0341afdd6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Mar 2022 16:36:54 -0700 Subject: [PATCH 0589/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful/Readme.md diff --git a/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful/Readme.md b/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful/Readme.md new file mode 100644 index 000000000..cc5395e38 --- /dev/null +++ b/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful/Readme.md @@ -0,0 +1,11 @@ +### 2216.Minimum-Deletions-to-Make-Array-Beautiful + +此题容易想到一种贪心策略,就是从左往右,每两个作为一个pair,依次尝试构建相邻的互异元素。如果发现有一对元素是相同的,那就删去(任意)其中一个,将剩下的一个尝试与右边的元素继续配对,以此构造一对相邻的互异元素。直至整个序列都被处理完。 + +那么这种贪心策略是否正确呢?事实上,当我们第一次遇到一对相邻的相同元素时,其实有两种策略。举个例子```... X Y | 2 2 | Z W ... ``` + +第一种方法,就是如上所说,我们删掉一个2,然后尝试将剩下的2与右边的Z配对,变成```... X Y | 2 Z W ... ``` + +第二种方法,就是如上所说,我们删掉前面的Y(或者其他任何在2之前的元素),这样会将这对2拆开,试图将第一个2与之前的元素X配对,第二个2与之后的元素配对,这样就变成了```... X 2 | 2 Z W ... ``` + +很显然,这两种方案产生的后半部分(即```2ZW...```)是完全一样的。而对于前半部分,第一种方法里X和Y已经是互异的了(因为我们约定这一对2是第一次遇到的一对相邻的相同元素);但第二种方法引入了一个不确定的因素,即X与2是否互异我们不得而知,有可能需要更多的操作来使得前半部分满足条件。所以总的来说第二种方法是不合算的。 From b2db9159b2ef9ce7631e6c08762477cf6eb45bf8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Mar 2022 17:12:37 -0700 Subject: [PATCH 0590/2729] Create 2218.Maximum-Value-of-K-Coins-From-Piles.cpp --- ...18.Maximum-Value-of-K-Coins-From-Piles.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles/2218.Maximum-Value-of-K-Coins-From-Piles.cpp diff --git a/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles/2218.Maximum-Value-of-K-Coins-From-Piles.cpp b/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles/2218.Maximum-Value-of-K-Coins-From-Piles.cpp new file mode 100644 index 000000000..95dc2dbf0 --- /dev/null +++ b/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles/2218.Maximum-Value-of-K-Coins-From-Piles.cpp @@ -0,0 +1,32 @@ +class Solution { + int dp[1002][2002]; +public: + int maxValueOfCoins(vector>& piles, int k) + { + int n = piles.size(); + vector>presum(n); + for (int i=0; i Date: Sun, 27 Mar 2022 17:32:06 -0700 Subject: [PATCH 0591/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ff8dde018..79b537cf8 100644 --- a/Readme.md +++ b/Readme.md @@ -598,6 +598,7 @@ [1955.Count-Number-of-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1955.Count-Number-of-Special-Subsequences) (H-) [2088.Count-Fertile-Pyramids-in-a-Land](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land) (H-) [2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H) +[2218.Maximum-Value-of-K-Coins-From-Piles](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 05692a7311eb873512b7846a29988c644b0b7242 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Mar 2022 17:45:55 -0700 Subject: [PATCH 0592/2729] Create Readme.md --- .../Readme.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles/Readme.md diff --git a/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles/Readme.md b/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles/Readme.md new file mode 100644 index 000000000..11c890751 --- /dev/null +++ b/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles/Readme.md @@ -0,0 +1,24 @@ +### 2218.Maximum-Value-of-K-Coins-From-Piles + +本题的动态规划算法本身不难想到,关键在于时间复杂度的分析。 + +因为我们对所有的pile依次处理,所以需要一个下标来表示pile的index。另外因为所能摘取coins总数目有限制,所以我们需要第二个下标来表示当前摘取的coins数目。即dp[i][j]表示截止到第i个pile,总共摘取j个coins的最大价值。 + +状态转移方程的着眼点自然就是第i根pile。我们能控制的就是该pile取几个coins。所以我们需要遍历对该pile的行动方案(即取0个,取1个,取2个,... ) + +所以本题的状态转移方程就是: +``` +dp[i][j] = max{dp[i-1][j-t] + pilesVal[i][t] } where t= 0,1,2,...,len(piles[i]) +``` +其中pilesVal[i][t]就是第i根pile取t个硬币的收益,这个是可以提前计算好的。 + +显然,这里似乎需要三层循环: +```cpp +for (int i=0; i Date: Sun, 27 Mar 2022 21:38:04 -0700 Subject: [PATCH 0593/2729] Create 2217.Find-Palindrome-With-Fixed-Length.cpp --- ...2217.Find-Palindrome-With-Fixed-Length.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp diff --git a/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp b/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp new file mode 100644 index 000000000..f5ab217b0 --- /dev/null +++ b/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp @@ -0,0 +1,67 @@ +using LL = long long; +class Solution { +public: + vector kthPalindrome(vector& queries, int intLength) + { + vectorrets; + for (int k: queries) + { + if (intLength==1) + { + if (k>9) + rets.push_back(-1); + else + rets.push_back(k); + continue; + } + + if (intLength%2==0) + { + int m = intLength/2; + if (k > 9*pow(10, m-1)) + { + rets.push_back(-1); + continue; + } + else + { + LL a = pow(10, m-1) + k - 1; + LL b = flip(a); + rets.push_back(a*pow(10,m)+b); + } + } + else + { + int m = intLength/2; + if (k > 9*pow(10, m-1)*10) + { + rets.push_back(-1); + continue; + } + else + { + LL k1 = (k-1)/10; + LL k2 = (k-1)%10; + + LL a = pow(10, m-1) + k1; + LL b = flip(a); + LL c = k2; + + rets.push_back(a*pow(10,m+1)+c*pow(10,m)+b); + } + } + } + return rets; + } + + LL flip(LL x) + { + LL ret = 0; + while (x>0) + { + ret = ret*10+(x%10); + x/=10; + } + return ret; + } +}; From 1e32579e7f35f29bb009315363ef196f5d90dda2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Mar 2022 21:43:42 -0700 Subject: [PATCH 0594/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 79b537cf8..d69523a7e 100644 --- a/Readme.md +++ b/Readme.md @@ -960,6 +960,7 @@ [1969.Minimum-Non-Zero-Product-of-the-Array-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/1969.Minimum-Non-Zero-Product-of-the-Array-Elements) (M+) [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) +[2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) From 2d39e5149b57ef2ad59f524ebd3dc287f85026c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Mar 2022 22:07:25 -0700 Subject: [PATCH 0595/2729] Update 2217.Find-Palindrome-With-Fixed-Length.cpp --- ...2217.Find-Palindrome-With-Fixed-Length.cpp | 40 +++++++++---------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp b/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp index f5ab217b0..63b54ecc6 100644 --- a/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp +++ b/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp @@ -15,44 +15,40 @@ class Solution { continue; } + int m = intLength/2; if (intLength%2==0) { - int m = intLength/2; - if (k > 9*pow(10, m-1)) + LL a = getKth(m, k); + if (a==-1) { rets.push_back(-1); continue; } - else - { - LL a = pow(10, m-1) + k - 1; - LL b = flip(a); - rets.push_back(a*pow(10,m)+b); - } + LL b = flip(a); + rets.push_back(a*pow(10, m) + b); } else { - int m = intLength/2; - if (k > 9*pow(10, m-1)*10) + LL a = getKth(m+1, k); + if (a==-1) { rets.push_back(-1); continue; } - else - { - LL k1 = (k-1)/10; - LL k2 = (k-1)%10; - - LL a = pow(10, m-1) + k1; - LL b = flip(a); - LL c = k2; - - rets.push_back(a*pow(10,m+1)+c*pow(10,m)+b); - } - } + LL c = a%10; + a = a/10; + LL b = flip(a); + rets.push_back(a*pow(10, m+1) + c*pow(10, m) + b); + } } return rets; } + + LL getKth(int m, int k) + { + if (k > 9*pow(10, m-1)) return -1; + else return pow(10, m-1) + k-1; + } LL flip(LL x) { From 8c9e1527ee97cba7455d23ada51321a19cf79556 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Mar 2022 22:11:32 -0700 Subject: [PATCH 0596/2729] Create Readme.md --- Math/2217.Find-Palindrome-With-Fixed-Length/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Math/2217.Find-Palindrome-With-Fixed-Length/Readme.md diff --git a/Math/2217.Find-Palindrome-With-Fixed-Length/Readme.md b/Math/2217.Find-Palindrome-With-Fixed-Length/Readme.md new file mode 100644 index 000000000..925cd860a --- /dev/null +++ b/Math/2217.Find-Palindrome-With-Fixed-Length/Readme.md @@ -0,0 +1,7 @@ +### 2217.Find-Palindrome-With-Fixed-Length + +因为回文数是镜像的。所以对于固定长度为L、第k大的回文数,其实只要求一半长度的第k个自然数即可。更具体地,我们要根据L的奇偶性分情况讨论。 + +如果L是偶数,那么本题就转换成了求长度为L/2的第k大的自然数。因为长度为L/2的最小自然数是1000...,即1e(L/2-1),所以回文数的左半边是```a = 1e(L/2-1) + (k-1)```。再将a镜像得到b,然后 ```a*1e(L/2)+b```就是最终的答案。 + +如果L是奇数,那么待求的回文数就是acb的形式。其中b是a的镜像,长度都是L/2;c是一个single digit。于是第k大的回文数,就等价于长度是L/2+1的第k大的自然数,即```a = 1e(L/2) + (k-1)```. 然后我们得到```c = a % 10```。将a去掉最后一位后,得到其镜像数字为b。最终的答案是```a*1e(L/2+1) + c*1e(L/2) + b```。 From 90a27c165c0f7f6cb8ec74f0591811e423416304 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Mar 2022 22:43:59 -0700 Subject: [PATCH 0597/2729] Update 2217.Find-Palindrome-With-Fixed-Length.cpp --- ...2217.Find-Palindrome-With-Fixed-Length.cpp | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp b/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp index 63b54ecc6..72dbb2400 100644 --- a/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp +++ b/Math/2217.Find-Palindrome-With-Fixed-Length/2217.Find-Palindrome-With-Fixed-Length.cpp @@ -6,18 +6,14 @@ class Solution { vectorrets; for (int k: queries) { - if (intLength==1) + if (intLength == 1) { - if (k>9) - rets.push_back(-1); - else - rets.push_back(k); - continue; + if (k>9) rets.push_back(-1); + else rets.push_back(k); } - - int m = intLength/2; - if (intLength%2==0) + else if (intLength%2==0) { + int m = intLength/2; LL a = getKth(m, k); if (a==-1) { @@ -25,39 +21,41 @@ class Solution { continue; } LL b = flip(a); - rets.push_back(a*pow(10, m) + b); + rets.push_back(a*pow(10, m) + b); } else { + int m = intLength/2; LL a = getKth(m+1, k); if (a==-1) { rets.push_back(-1); continue; } - LL c = a%10; + LL c = a % 10; a = a/10; LL b = flip(a); - rets.push_back(a*pow(10, m+1) + c*pow(10, m) + b); + rets.push_back(a*pow(10, m+1) + c*pow(10,m) + b); } - } + } return rets; } - + LL getKth(int m, int k) { if (k > 9*pow(10, m-1)) return -1; else return pow(10, m-1) + k-1; } - LL flip(LL x) + LL flip(LL a) { LL ret = 0; - while (x>0) + while (a>0) { - ret = ret*10+(x%10); - x/=10; + ret = ret*10+(a%10); + a/=10; } return ret; } + }; From 5cc119757cb1534a606fcd1d0b6acbaaa5c5b3dc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 28 Mar 2022 20:53:31 -0700 Subject: [PATCH 0598/2729] Create 2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph.cpp --- ...-of-a-Node-in-a-Directed-Acyclic-Graph.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph.cpp diff --git a/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph.cpp b/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph.cpp new file mode 100644 index 000000000..bbad94f68 --- /dev/null +++ b/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + vector> getAncestors(int n, vector>& edges) + { + vector>next(n); + vectorindegree(n); + for (auto edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + indegree[b]++; + } + + queueq; + for (int i=0; i>rets(n); + while (!q.empty()) + { + int cur = q.front(); + q.pop(); + for (auto x: next[cur]) + { + for (auto y: rets[cur]) + rets[x].insert(y); + rets[x].insert(cur); + indegree[x]--; + if (indegree[x]==0) + q.push(x); + } + } + + vector>ans(n); + for (int i=0; i Date: Mon, 28 Mar 2022 20:54:07 -0700 Subject: [PATCH 0599/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d69523a7e..5afbcf6b7 100644 --- a/Readme.md +++ b/Readme.md @@ -496,6 +496,7 @@ [2050.Parallel-Courses-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2050.Parallel-Courses-III) (M+) [2115.Find-All-Possible-Recipes-from-Given-Supplies](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies) (M) [2127.Maximum-Employees-to-Be-Invited-to-a-Meeting](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting) (H) +[2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph) (M) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From dffee810768f32ed5909efbec4987eefe00ef3b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 17:07:06 -0700 Subject: [PATCH 0600/2729] Create 2189.Number-of-Ways-to-Build-House-of-Cards.cpp --- ...Number-of-Ways-to-Build-House-of-Cards.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/2189.Number-of-Ways-to-Build-House-of-Cards.cpp diff --git a/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/2189.Number-of-Ways-to-Build-House-of-Cards.cpp b/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/2189.Number-of-Ways-to-Build-House-of-Cards.cpp new file mode 100644 index 000000000..8466d7b88 --- /dev/null +++ b/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/2189.Number-of-Ways-to-Build-House-of-Cards.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int houseOfCards(int n) + { + vectornums(501); + for (int i=1; i<=500; i++) + nums[i] = 2*i + (i-1); + + vector>dp(501, vector(501,0)); + dp[0][0] = 1; + for (int i=1; i<=n/2; i++) + for (int j=0; j<=n; j++) + { + dp[i][j] = dp[i-1][j] + (j>=nums[i]?dp[i-1][j-nums[i]]:0); + } + + return dp[n/2][n]; + } +}; From 06fb95a346d066662575b54cb14952ca71c6c368 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 17:07:50 -0700 Subject: [PATCH 0601/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5afbcf6b7..a8614b3de 100644 --- a/Readme.md +++ b/Readme.md @@ -599,6 +599,7 @@ [1955.Count-Number-of-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1955.Count-Number-of-Special-Subsequences) (H-) [2088.Count-Fertile-Pyramids-in-a-Land](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2088.Count-Fertile-Pyramids-in-a-Land) (H-) [2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H) +[2189.Number-of-Ways-to-Build-House-of-Cards](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards) (H-) [2218.Maximum-Value-of-K-Coins-From-Piles](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) From a25d70d2e79250094c38cfd1980701fd9562d054 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 17:29:37 -0700 Subject: [PATCH 0602/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/Readme.md diff --git a/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/Readme.md b/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/Readme.md new file mode 100644 index 000000000..878f04738 --- /dev/null +++ b/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/Readme.md @@ -0,0 +1,11 @@ +### 2189.Number-of-Ways-to-Build-House-of-Cards + +本题的直观解读是要将总数n分成若干行之和,每行的牌数是递增的,并且每行的牌数必须是```2*k+(k-1)```的形式,其中k可以理解为三角形的个数。 + +我们换个角度来想,假设将行数编号1,2,3,4...就对应三角形的个数,那么每行对应的牌数是```2*k+(k-1)```. 我们的任务其实是将在这些行里面挑选出若干,使得其总数为n。我们可以预料,可供选择的行号不会很多,撑死最多也就是n行(事实上单独的第n行就需要共3n-1张的牌数了)。 + +我们令dp[i][j]表示前i行里面(挑选若干行)、并且所用牌的总数为j可以得到的方案数。对于第i行而言只有两种选择:1. 我们不选第i行,即不搭建3i-1这种模式,那么```dp[i][j] = dp[i-1][j]```. 2.我们选择第i行,那么第i行本身占用了3i-1张牌,那么意味着我们关注的就是前i-1行里我们选用j-(3i-1)张牌能搭建多少种合法的方案,所以```dp[i][j] = dp[i-1][j-(3i-1)]```. + +于是本题的转移方程就是 ```dp[i][j] = dp[i-1][j] + dp[i-1][j-(3i-1)]```。 + +初始条件是```dp[0][0] = 1```,这是所有状态的“种子”。 From 4d5d56bbdf7d2542decfc27a41b84e16e53b0f49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 17:31:13 -0700 Subject: [PATCH 0603/2729] Update 2189.Number-of-Ways-to-Build-House-of-Cards.cpp --- .../2189.Number-of-Ways-to-Build-House-of-Cards.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/2189.Number-of-Ways-to-Build-House-of-Cards.cpp b/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/2189.Number-of-Ways-to-Build-House-of-Cards.cpp index 8466d7b88..e7e795735 100644 --- a/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/2189.Number-of-Ways-to-Build-House-of-Cards.cpp +++ b/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards/2189.Number-of-Ways-to-Build-House-of-Cards.cpp @@ -2,16 +2,12 @@ class Solution { public: int houseOfCards(int n) { - vectornums(501); - for (int i=1; i<=500; i++) - nums[i] = 2*i + (i-1); - - vector>dp(501, vector(501,0)); + vector>dp(n+1, vector(n+1,0)); dp[0][0] = 1; for (int i=1; i<=n/2; i++) for (int j=0; j<=n; j++) { - dp[i][j] = dp[i-1][j] + (j>=nums[i]?dp[i-1][j-nums[i]]:0); + dp[i][j] = dp[i-1][j] + (j>=(3*i-1)?dp[i-1][j-(3*i-1)]:0); } return dp[n/2][n]; From a99bb9e19155f4b949d4d5e3f840e829d8e3677e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 17:45:07 -0700 Subject: [PATCH 0604/2729] Create 2198.Number-of-Single-Divisor-Triplets.cpp --- ...2198.Number-of-Single-Divisor-Triplets.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Hash/2198.Number-of-Single-Divisor-Triplets/2198.Number-of-Single-Divisor-Triplets.cpp diff --git a/Hash/2198.Number-of-Single-Divisor-Triplets/2198.Number-of-Single-Divisor-Triplets.cpp b/Hash/2198.Number-of-Single-Divisor-Triplets/2198.Number-of-Single-Divisor-Triplets.cpp new file mode 100644 index 000000000..d11de6b7d --- /dev/null +++ b/Hash/2198.Number-of-Single-Divisor-Triplets/2198.Number-of-Single-Divisor-Triplets.cpp @@ -0,0 +1,33 @@ +using LL = long long; +class Solution { +public: + long long singleDivisorTriplet(vector& nums) + { + unordered_mapMap; + for (int i=0; i Date: Tue, 29 Mar 2022 17:45:42 -0700 Subject: [PATCH 0605/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a8614b3de..f7cce1849 100644 --- a/Readme.md +++ b/Readme.md @@ -123,7 +123,7 @@ [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) [2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal) (M) -#### [Hash Table](https://github.com/wisdompeak/LeetCode/tree/master/Hash) +#### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) [149.Max-Points-on-a-Line](https://github.com/wisdompeak/LeetCode/tree/master/Hash/149.Max-Points-on-a-Line) (H) [166.Fraction-to-Recurring-Decimal](https://github.com/wisdompeak/LeetCode/tree/master/Hash/166.Fraction-to-Recurring-Decimal) (M) @@ -149,6 +149,7 @@ [1487.Making-File-Names-Unique](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1487.Making-File-Names-Unique) (M+) [1573.Number-of-Ways-to-Split-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1573.Number-of-Ways-to-Split-a-String) (M) [2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words) (M) +[2198.Number-of-Single-Divisor-Triplets](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2198.Number-of-Single-Divisor-Triplets) (H-) * ``Hash+Prefix`` [525.Contiguous-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/525.Contiguous-Array) (M) [930.Binary-Subarrays-With-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/930.Binary-Subarrays-With-Sum) (M) From 36d3d61d3f6db4d57b60ddf967b9ac438b5b325f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 17:54:11 -0700 Subject: [PATCH 0606/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md diff --git a/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md b/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md new file mode 100644 index 000000000..ff2796700 --- /dev/null +++ b/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md @@ -0,0 +1,5 @@ +### 2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph + +本题就是常规的拓扑排序,依然是剥洋葱的思想,每个回合将当前入度减为零的节点放入队列中,持续BFS。 + +本题需要给每一个节点配一个集合ancestor来记录它的祖先。在将节点i弹出队列的时候,查看所有i的后续节点j,将ancestor[i]的元素和i本身都加入ancestor[j]中。 From 50a25d28849144007642404afd597cbc89fe8329 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 17:55:33 -0700 Subject: [PATCH 0607/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md b/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md index ff2796700..3e9283fa4 100644 --- a/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md +++ b/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md @@ -2,4 +2,4 @@ 本题就是常规的拓扑排序,依然是剥洋葱的思想,每个回合将当前入度减为零的节点放入队列中,持续BFS。 -本题需要给每一个节点配一个集合ancestor来记录它的祖先。在将节点i弹出队列的时候,查看所有i的后续节点j,将ancestor[i]的元素和i本身都加入ancestor[j]中。 +本题可以暴力一些,直接给每一个节点配一个集合ancestor来记录它的祖先。在将节点i弹出队列的时候,查看所有i的后续节点j,将ancestor[i]的元素和i本身都加入ancestor[j]中。 From 965634a9a28550ecf3750d85cb46db52b5792a65 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 17:55:51 -0700 Subject: [PATCH 0608/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md b/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md index 3e9283fa4..f90182f89 100644 --- a/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md +++ b/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph/Readme.md @@ -2,4 +2,4 @@ 本题就是常规的拓扑排序,依然是剥洋葱的思想,每个回合将当前入度减为零的节点放入队列中,持续BFS。 -本题可以暴力一些,直接给每一个节点配一个集合ancestor来记录它的祖先。在将节点i弹出队列的时候,查看所有i的后续节点j,将ancestor[i]的元素和i本身都加入ancestor[j]中。 +本题可以暴力一些,直接给每一个节点配一个集合ancestor来记录它的祖先。在将节点i弹出队列的时候,查看i的所有后续节点j,将ancestor[i]的元素和i本身都加入ancestor[j]中。 From e36ed1c9435f43af2464caad8f70ecc41b98c4bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 18:13:03 -0700 Subject: [PATCH 0609/2729] Create Readme.md --- Hash/2198.Number-of-Single-Divisor-Triplets/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Hash/2198.Number-of-Single-Divisor-Triplets/Readme.md diff --git a/Hash/2198.Number-of-Single-Divisor-Triplets/Readme.md b/Hash/2198.Number-of-Single-Divisor-Triplets/Readme.md new file mode 100644 index 000000000..03beda6e3 --- /dev/null +++ b/Hash/2198.Number-of-Single-Divisor-Triplets/Readme.md @@ -0,0 +1,11 @@ +### 2198.Number-of-Single-Divisor-Triplets + +本题的突破口在于数据约束:nums的数量很大,但是每个数字的数值很小,只有[1,100]。所以我们用三重循环来枚举每个数字可能的数值,复杂度上都是可以接受的。 + +我们在枚举三个数值a,b,c的时候,需要注意一个问题,那就是这三个数值是否可以相等。 + +如果三个数值彼此不等,那么(i,j,k)的组合数目就是```count[a]*count[b]*count[c]```,其中count[a]表示数值a在数组里出现了几次(即对应了不同的index)。但是注意本题求的是排列数,所以还要在刚才的数字上乘以6,即给定三个index的排列方式。 + +如果三个数值中有两个数值相等,不妨设为a,a,b,那么(i,j,k)的组合数目就是```count[a]*count[a]/2*count[b]```,这是因为我们要在所有数值为a的元素中挑出任意两个不同的index。注意我们最终拿出来的(i,j,k)还是三个不同的index,所以排列方式还是6. + +如果三个数值都相等的话,会发生什么呢?事实上这是不可能的。三个数值都相等的时候,这三个数值一定都能整除他们的和,不符合条件。 From c54bd7bb212b42307022507cf2d69dfc16b7e493 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 29 Mar 2022 22:36:08 -0700 Subject: [PATCH 0610/2729] Update 503.Next-Greater-Element-II.cpp --- .../503.Next-Greater-Element-II.cpp | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/Stack/503.Next-Greater-Element-II/503.Next-Greater-Element-II.cpp b/Stack/503.Next-Greater-Element-II/503.Next-Greater-Element-II.cpp index 0f807c37c..8ecafe63e 100644 --- a/Stack/503.Next-Greater-Element-II/503.Next-Greater-Element-II.cpp +++ b/Stack/503.Next-Greater-Element-II/503.Next-Greater-Element-II.cpp @@ -2,28 +2,24 @@ class Solution { public: vector nextGreaterElements(vector& nums) { - int N=nums.size(); - stack>Stack; + int N = nums.size(); + for (int i=0; iStack; vectorresults(N,-1); - for (int j=0; j=N) i=i-N; - - if (Stack.empty() || Stack.top().first>nums[i]) - Stack.push({nums[i],i}); - else + while (!Stack.empty() && nums[Stack.top()] Date: Wed, 30 Mar 2022 23:04:01 -0700 Subject: [PATCH 0611/2729] Create 2213.Longest-Substring-of-One-Repeating-Character.cpp --- ...t-Substring-of-One-Repeating-Character.cpp | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Heap/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp diff --git a/Heap/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp b/Heap/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp new file mode 100644 index 000000000..50c1f566e --- /dev/null +++ b/Heap/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp @@ -0,0 +1,101 @@ +class Solution { + mapMap; + multisetSet; +public: + vector longestRepeating(string s, string queryCharacters, vector& queryIndices) + { + int n = s.size(); + for (int i=0; irets; + for (int k=0; kfirst, b = iter->second; + if (a==b && a==idx) return; + + removeInterval(a); + + if (a == idx) + { + addInterval(a, a); + addInterval(a+1, b); + } + else if (b == idx) + { + addInterval(b, b); + addInterval(a, b-1); + } + else + { + addInterval(a, idx-1); + addInterval(idx, idx); + addInterval(idx+1, b); + } + } + + void mergeRight(int idx, string&s) + { + if (idx == s.size()-1) return; + if (s[idx] != s[idx+1]) return; + + auto iter = Map.lower_bound(idx+1); + int b = iter->second; + + removeInterval(idx); + removeInterval(idx+1); + addInterval(idx, b); + } + + void mergeLeft(int idx, string&s) + { + if (idx == 0) return; + if (s[idx] != s[idx-1]) return; + + auto iter = Map.lower_bound(idx); + iter = prev(iter); + int a = iter->first; + int b = Map[idx]; + + removeInterval(idx); + removeInterval(a); + addInterval(a, b); + } +}; From a16eff7464b95ea32cd096e5a83b9cadb4412e46 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 30 Mar 2022 23:05:18 -0700 Subject: [PATCH 0612/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f7cce1849..35d5a34c0 100644 --- a/Readme.md +++ b/Readme.md @@ -186,6 +186,7 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) +[2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/new/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From b22c17d4eb38c515fb3e3756090e391ddcf8b708 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 30 Mar 2022 23:37:03 -0700 Subject: [PATCH 0613/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Heap/2213.Longest-Substring-of-One-Repeating-Character/Readme.md diff --git a/Heap/2213.Longest-Substring-of-One-Repeating-Character/Readme.md b/Heap/2213.Longest-Substring-of-One-Repeating-Character/Readme.md new file mode 100644 index 000000000..5e3985f08 --- /dev/null +++ b/Heap/2213.Longest-Substring-of-One-Repeating-Character/Readme.md @@ -0,0 +1,15 @@ +### 2213.Longest-Substring-of-One-Repeating-Character + +字符串里连续的相同字符可以视为一个区间,那么整个字符串就包含了若干个“紧密”贴合的区间。我们可以用一个有序map来放置这些区间,将key设置为区间首的位置,val设置为区间尾的位置,并且map自动按照key来排列。 + +对于任何一个字符的改变,可能会产生一个或者多个新区间,也有可能会造成一些区间的合并,似乎头绪非常繁杂。在这里,一个比较好的思路就是分三步走:当改变位于idx的字符时,先无脑地新增一个区间[idx,idx],然后再考察往右合并邻接区间(如果可能的话),再考察往右左并邻接区间(如果可能的话)。 + +当我们考虑新增区间时,需要先找出原先包含idx的区间[a,b],其中a<=idx<=b。我们用```prev(Map.upper_bound(idx))```得到的最后一个小于等于idx的位置。接下来分为四种可能: +1. 如果a==b==idx,那么不用变化 +2. 如果a==idx Date: Fri, 1 Apr 2022 22:15:26 -0700 Subject: [PATCH 0614/2729] Update 715.Range-Module.cpp --- .../715.Range-Module/715.Range-Module.cpp | 65 +++++++------------ 1 file changed, 24 insertions(+), 41 deletions(-) diff --git a/Segment_Tree/715.Range-Module/715.Range-Module.cpp b/Segment_Tree/715.Range-Module/715.Range-Module.cpp index 182578df1..a976d7e84 100644 --- a/Segment_Tree/715.Range-Module/715.Range-Module.cpp +++ b/Segment_Tree/715.Range-Module/715.Range-Module.cpp @@ -8,64 +8,47 @@ class RangeModule { void addRange(int left, int right) { - auto pos1 = Map.lower_bound(left); + auto iter1 = Map.lower_bound(left); int leftboundary=left; - if (pos1!=Map.begin() && prev(pos1,1)->second>=left) - leftboundary = prev(pos1,1)->first; + if (iter1!=Map.begin() && prev(iter1,1)->second>=left) + leftboundary = prev(iter1,1)->first; - auto pos2 = Map.upper_bound(right); + auto iter2 = Map.upper_bound(right); int rightboundary = right; - if (pos2!=Map.begin()) - rightboundary = max(right, prev(pos2,1)->second); + if (iter2!=Map.begin()) + rightboundary = max(right, prev(iter2,1)->second); - Map.erase(pos1,pos2); + Map.erase(iter1,iter2); Map[leftboundary]=rightboundary; - - /* - for (auto a:Map) - cout<second>=right); + auto iter = Map.upper_bound(left); + return (iter!=Map.begin() && prev(iter)->second>=right); } void removeRange(int left, int right) { - auto pos1 = Map.lower_bound(left); - bool flag1=0; - int temp1; - if (pos1!=Map.begin() && prev(pos1,1)->second > left) + auto iter1 = Map.lower_bound(left); + int start1 = 0, end1 = 0; + if (iter1!=Map.begin() && prev(iter1)->second > left) { - temp1 = prev(pos1,1)->first; - flag1=1; + start1 = prev(iter1)->first; + end1 = left; } - - auto pos2 = Map.lower_bound(right); - int temp2; - bool flag2=0; - if (pos2!=Map.begin() && prev(pos2,1)->second > right) + + auto iter2 = Map.lower_bound(right); + int start2 = 0, end2 = 0; + if (iter2!=Map.begin() && prev(iter2)->first < right) { - temp2 = prev(pos2,1)->second; - flag2=1; + start2 = right; + end2 = prev(iter2)->second; } - - Map.erase(pos1,pos2); - if (flag1) Map[temp1]=left; - if (flag2) Map[right]=temp2; - - /* - for (auto a:Map) - cout< Date: Sun, 3 Apr 2022 18:09:56 -0700 Subject: [PATCH 0615/2729] Update Readme.md --- Segment_Tree/715.Range-Module/Readme.md | 81 ++++++++++--------------- 1 file changed, 31 insertions(+), 50 deletions(-) diff --git a/Segment_Tree/715.Range-Module/Readme.md b/Segment_Tree/715.Range-Module/Readme.md index 2a5e2d118..6e69ea7b2 100644 --- a/Segment_Tree/715.Range-Module/Readme.md +++ b/Segment_Tree/715.Range-Module/Readme.md @@ -2,64 +2,45 @@ #### 解法1:使用有序map -对于这种interval类型的题目,我们选用ordered_map,将左边界作为key,右边界作为val,则所有的interval都按左边界从小到大排序。 +我们需要在数轴上维护一个“干净的”区间序列,即每个区间从小到大排列,但彼此互不重合。每次addRange或removeRange时,都要依然维护区间的“干净”,这样queryRange时就方便很多。 -加入一个interval时,要考虑这么几点: +类似2213,我们会选择C++的有序map,将左边界作为key,右边界作为val,则所有的区间都按key(即左边界)从小到大排序。 -1. 新加入的区间是否和左边的某个区间部分重合?是的话,那么左边的那个区间就要拉长、重新赋值其右边界;如果不是,那么left就是一个新的左边界。 -2. 新加入的区间是否和右边的某个区间部分重合?是的话,那么右边的那个区间就要删除它的key,其右边界将作为一个新区间的右边界。 -3. 新加入的区间范围内的任何key都是需要抹去的。 -4. 新建立一个区间。 - -代码如下: -```cpp -int leftBound = left; -auto pos1=Map.lower_bound(left); -if (pos1!=Map.begin() && prev(pos1,1)->second >= left) //左边界部分重合 - leftBound = prev(pos1,1)->first; - -int rightBound = right; -auto pos2=Map.upper_bound(right); -if (pos2!=Map.begin() && prev(pos2,1)->first <= right) //右边界部分重合 - rightBound = max(right, prev(pos2,1)->second); - -Map.erase(pos1,pos2) // 删除一个前闭后开的迭代器区间 -Map[leftBound]=rightBound; +##### AddRange +加入一个新区间[left,right]时,我们考虑它与数轴上已有区间的关系。 +``` + A B C D +L____________ ______ __________R _____ + left_____________________right ``` +如上图所示,我们的目标是:删除已有的区间A、B、C,同时加入一个新的区间[L,R]. -删除一个interval时,要考虑这么几点: +如何定位区间A?A是左边界最后一个小于left的区间。所以我们用```iter1=prev(Map.lower_bound(left))```来定位这个区间,同时它可以拓展左边界,即```L = iter1->first```. 注意如果prev操作会越界的话,那么iter1就定位在Map.lower_bound(left),这是我们想要删除的最左边的区间。 -1. 要删除的区间是否和左边的某个区间部分重合?是的话,那么左边的那个区间就要缩短,重新赋值其右边界。 -2. 要删除的区间是否和右边的某个区间部分重合?是的话,那么右边的那个区间就要缩短,重新定义其左边界。 -3. 要删除的区间范围内的任何key都是需要抹去的。 +如果定位区间C?其实更容易定位的是区间D,那么就是第一个左边界大于right的区间。所以我们用```iter2=Map.upper_bound(right)```来定位这个区间。于是从iter1到iter2(不包括iter2本身)这些区间都可以删除,于是直接用```Map.erase(iter1, iter2)```. 注意到prev(iter2)就是区间C,区间C的右边界可能帮助我们拓展右边界,即```R = max(right, prev(iter2)->second)```. -代码如下: -```cpp -auto pos1=Map.lower_bound(left); -bool flag1=0; -if (pos1!=Map.begin() && prev(pos1,1)->second >= left) -{ - flag1=1; - temp1=prev(pos1,1)->second; -} - -auto pos2=Map.lower_bound(right); -bool flag=0; -int temp2; -if (pos2!=Map.begin() && prev(pos2,1)->second > right) -{ - flag2=1; - temp2=prev(pos2,1)->second; -} - -Map.erase(pos1,pos2); -if (flag1) Map[temp1]=left; -if (flag2) Map[right]=temp2; +最终我们添加新的区间[L,R]. + +##### RemoveRange +删除一个新区间[left,right]时,我们类似地考虑它与数轴上已有区间的关系。 ``` -特别注意,对于迭代器的修改操作,得安排在删除操作之后进行。 + A B C D +L____________ ______ __________R _____ + left_____________________right +``` +如上图所示,我们的目标是:删除已有的区间A、B、C,同时加入两个新区间[L,left], [right,R]. + +如何定位区间A?同上,A是左边界最后一个小于left的区间。所以我们用```iter1=prev(Map.lower_bound(left))```来定位这个区间。如果这个区间存在并且左边界比left更早,那么我们就要添加[L,left]. + +如何定位C?同理,先定位区间D,即```iter2=Map.upper_bound(right)```,然后我们考察D的前一个区间C的右边界是否比right更晚,那么我们就要添加[right,R]. + +注意,我们必须显操作```Map.erase(iter1, iter2)```,再添加这两个新区间。 + +##### QueryRange +只要用prev(Map.upper_bound(left))定位到左边界小于等于left的区间,再看区间右边界是否大于等于right即可。 -#### 解法2:使用线段树 +#### 解法2:使用线段树 (不推荐) 此题适合标准的线段树模型和数据结构。从难度上将,本题是基于307和370基础上的更进一步,因为我们需要再设计一个remove的操作。 @@ -133,4 +114,4 @@ setTree* right; ``` -[Leetcode Link](https://leetcode.com/problems/range-module) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/range-module) From a482a56ee743d1370599f1153a767b072572737a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Apr 2022 18:12:38 -0700 Subject: [PATCH 0616/2729] Update 715.Range-Module.cpp --- .../715.Range-Module/715.Range-Module.cpp | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/Segment_Tree/715.Range-Module/715.Range-Module.cpp b/Segment_Tree/715.Range-Module/715.Range-Module.cpp index a976d7e84..d17b4b5d6 100644 --- a/Segment_Tree/715.Range-Module/715.Range-Module.cpp +++ b/Segment_Tree/715.Range-Module/715.Range-Module.cpp @@ -1,22 +1,24 @@ class RangeModule { mapMap; public: - RangeModule() - { - Map.clear(); + RangeModule() { } void addRange(int left, int right) { - auto iter1 = Map.lower_bound(left); int leftboundary=left; - if (iter1!=Map.begin() && prev(iter1,1)->second>=left) - leftboundary = prev(iter1,1)->first; - - auto iter2 = Map.upper_bound(right); int rightboundary = right; - if (iter2!=Map.begin()) - rightboundary = max(right, prev(iter2,1)->second); + + auto iter1 = Map.lower_bound(left); + if (iter1!=Map.begin() && prev(iter1)->second>=left) + { + iter1 = prev(iter1); + leftboundary = iter1->first; + } + + auto iter2 = Map.upper_bound(right); + if (iter2!=Map.begin() && prev(iter2)->second >= rightboundary) + rightboundary = prev(iter2)->second; Map.erase(iter1,iter2); Map[leftboundary]=rightboundary; @@ -34,11 +36,12 @@ class RangeModule { int start1 = 0, end1 = 0; if (iter1!=Map.begin() && prev(iter1)->second > left) { - start1 = prev(iter1)->first; + iter1 = prev(iter1); + start1 = iter1->first; end1 = left; } - auto iter2 = Map.lower_bound(right); + auto iter2 = Map.upper_bound(right); int start2 = 0, end2 = 0; if (iter2!=Map.begin() && prev(iter2)->first < right) { From e7b06c674e64f3d8ad44b9316f9e54900fbafcc8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Apr 2022 18:51:53 -0700 Subject: [PATCH 0617/2729] Update 715.Range-Module.cpp --- Segment_Tree/715.Range-Module/715.Range-Module.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/715.Range-Module/715.Range-Module.cpp b/Segment_Tree/715.Range-Module/715.Range-Module.cpp index d17b4b5d6..a79019b39 100644 --- a/Segment_Tree/715.Range-Module/715.Range-Module.cpp +++ b/Segment_Tree/715.Range-Module/715.Range-Module.cpp @@ -43,7 +43,7 @@ class RangeModule { auto iter2 = Map.upper_bound(right); int start2 = 0, end2 = 0; - if (iter2!=Map.begin() && prev(iter2)->first < right) + if (iter2!=Map.begin() && prev(iter2)->second > right) { start2 = right; end2 = prev(iter2)->second; From 1286728937d078b953ea2afe4441be87869bf33e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Apr 2022 21:57:10 -0700 Subject: [PATCH 0618/2729] Update Readme.md --- .../2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md b/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md index e44e063d4..0896792da 100644 --- a/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md +++ b/String/2168.Unique-Substrings-With-Equal-Digit-Frequency/Readme.md @@ -5,5 +5,5 @@ 对于判定字符串重复,我们有固定的套路,那就是rolling hash,可以将任意长度的字符串编码为一个整数来存储。本题中需要注意的是,为了避免将"012"和"12"都哈希成同一个编码,我们可以将十进制的编码规则改为十一进制,这样字符0也会被编码。即 ```cpp for (int j=i; j Date: Sun, 3 Apr 2022 23:51:09 -0700 Subject: [PATCH 0619/2729] Create 2223.Sum-of-Scores-of-Built-Strings.cpp --- .../2223.Sum-of-Scores-of-Built-Strings.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 String/2223.Sum-of-Scores-of-Built-Strings/2223.Sum-of-Scores-of-Built-Strings.cpp diff --git a/String/2223.Sum-of-Scores-of-Built-Strings/2223.Sum-of-Scores-of-Built-Strings.cpp b/String/2223.Sum-of-Scores-of-Built-Strings/2223.Sum-of-Scores-of-Built-Strings.cpp new file mode 100644 index 000000000..895aa0183 --- /dev/null +++ b/String/2223.Sum-of-Scores-of-Built-Strings/2223.Sum-of-Scores-of-Built-Strings.cpp @@ -0,0 +1,46 @@ +using LL = long long; +using ULL = unsigned long long; +class Solution { + ULL hashes[100001]; + ULL power[100001]; +public: + ULL getHash(string&s, int i, int len) + { + return hashes[i+len-1] - (i==0 ? 0 : hashes[i-1]*power[len]); + } + + long long sumScores(string s) + { + int n = s.size(); + ULL hash = 0; + for (int i=0; i=0; i--) + { + if (s[i]!=s[0]) continue; + int left = 1, right = n-i; + while (left < right) + { + int mid = right - (right-left)/2; + if (getHash(s, i, mid) != hashes[mid-1]) + right = mid-1; + else + left = mid; + } + ret += left; + } + + return ret; + } +}; From d02b79f2c9da9657b3063544a3e3341d9c02d74a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Apr 2022 23:51:50 -0700 Subject: [PATCH 0620/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 35d5a34c0..120130914 100644 --- a/Readme.md +++ b/Readme.md @@ -825,6 +825,7 @@ [1923.Longest-Common-Subpath](https://github.com/wisdompeak/LeetCode/tree/master/String/1923.Longest-Common-Subpath) (H) [2156.Find-Substring-With-Given-Hash-Value](https://github.com/wisdompeak/LeetCode/tree/master/String/2156.Find-Substring-With-Given-Hash-Value) (M) [2168.Unique-Substrings-With-Equal-Digit-Frequency](https://github.com/wisdompeak/LeetCode/tree/master/String/2168.Unique-Substrings-With-Equal-Digit-Frequency) (M+) +[2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) From 320e9e68c4a1f5316e0784883c84377b321c28c8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Apr 2022 00:08:10 -0700 Subject: [PATCH 0621/2729] Create Readme.md --- String/2223.Sum-of-Scores-of-Built-Strings/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 String/2223.Sum-of-Scores-of-Built-Strings/Readme.md diff --git a/String/2223.Sum-of-Scores-of-Built-Strings/Readme.md b/String/2223.Sum-of-Scores-of-Built-Strings/Readme.md new file mode 100644 index 000000000..309586770 --- /dev/null +++ b/String/2223.Sum-of-Scores-of-Built-Strings/Readme.md @@ -0,0 +1,11 @@ +### 2223.Sum-of-Scores-of-Built-Strings + +#### 解法1:扩展KMP +本题乍看像KMP,但其实不是。KMP给出的dp[i]表示以s[i]结尾的最长后缀,使得其等于s的前缀。而本题需要求的是,以s[i]开头的最长前缀,使得其等于s的前缀。这其实叫做扩展KMP。相关的资料见[OI Wiki](https://oi-wiki.org/string/z-func/) + +#### 解法2:Rolling Hash + Binary Search +另一种更接地气的做法是Rolling Hash。对于任意的位置i,我们想查看子串s[i:n-1]与s相同的最长前缀,不妨暴力地二分尝试。即猜测一个长度len,查看s[i:i+len-1]是否与s[0,len-1]相同。但是此处显然不会无脑地逐个字符去对比,我们只需要用o(1)时间比较这两段区间的Hash值。 + +那么怎么得到任意一段区间的Hash值呢?这就类似于前缀和的思想。我们用hashes[i]表示将字符串前缀s[0:i]哈希为一个26进制数的结果。显然我们可以用o(n)提前预处理,得到所有的hashes[i]。于是对于任意一个区间[i:j],他们对应的hash值就是```hashes[j] - hashes[i-1]*26^(j-i)```. + +Hash的过程中显然会有数值溢出的问题,通常情况下我们要设计MOD在计算的过程中不停地取余。一个取巧的方法就是用无符号长整形unsigned long long,利用自然溢出的特性来省去手工取余。用ULL的另一个好处就是区间的hash值计算里永远不会出现负数,保持了一致性。 From f4ad5567889e11f1fab58fa5d2dc58f8b1191705 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Apr 2022 00:13:20 -0700 Subject: [PATCH 0622/2729] Create 2224.Minimum-Number-of-Operations-to-Convert-Time.cpp --- ...m-Number-of-Operations-to-Convert-Time.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Others/2224.Minimum-Number-of-Operations-to-Convert-Time/2224.Minimum-Number-of-Operations-to-Convert-Time.cpp diff --git a/Others/2224.Minimum-Number-of-Operations-to-Convert-Time/2224.Minimum-Number-of-Operations-to-Convert-Time.cpp b/Others/2224.Minimum-Number-of-Operations-to-Convert-Time/2224.Minimum-Number-of-Operations-to-Convert-Time.cpp new file mode 100644 index 000000000..4bf90468e --- /dev/null +++ b/Others/2224.Minimum-Number-of-Operations-to-Convert-Time/2224.Minimum-Number-of-Operations-to-Convert-Time.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int convertTime(string current, string correct) + { + int h1 = stoi(current.substr(0,2)); + int m1 = stoi(current.substr(3)); + + int h2= stoi(correct.substr(0,2)); + int m2 = stoi(correct.substr(3)); + + int delta = (h2-h1)*60+(m2-m1); + + int ret = INT_MAX; + + for (int i=0; i*60<=delta; i++) + for (int j=0; j*15+i*60<=delta; j++) + for (int k=0; k*5+j*15+i*60<=delta; k++) + ret = min(ret, i+j+k+delta-(k*5+j*15+i*60)); + + return ret; + + } +}; From d083588760022d9112cf3a78ab188c6ebab7f0e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Apr 2022 00:16:30 -0700 Subject: [PATCH 0623/2729] Delete 2224.Minimum-Number-of-Operations-to-Convert-Time.cpp --- ...m-Number-of-Operations-to-Convert-Time.cpp | 23 ------------------- 1 file changed, 23 deletions(-) delete mode 100644 Others/2224.Minimum-Number-of-Operations-to-Convert-Time/2224.Minimum-Number-of-Operations-to-Convert-Time.cpp diff --git a/Others/2224.Minimum-Number-of-Operations-to-Convert-Time/2224.Minimum-Number-of-Operations-to-Convert-Time.cpp b/Others/2224.Minimum-Number-of-Operations-to-Convert-Time/2224.Minimum-Number-of-Operations-to-Convert-Time.cpp deleted file mode 100644 index 4bf90468e..000000000 --- a/Others/2224.Minimum-Number-of-Operations-to-Convert-Time/2224.Minimum-Number-of-Operations-to-Convert-Time.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - int convertTime(string current, string correct) - { - int h1 = stoi(current.substr(0,2)); - int m1 = stoi(current.substr(3)); - - int h2= stoi(correct.substr(0,2)); - int m2 = stoi(correct.substr(3)); - - int delta = (h2-h1)*60+(m2-m1); - - int ret = INT_MAX; - - for (int i=0; i*60<=delta; i++) - for (int j=0; j*15+i*60<=delta; j++) - for (int k=0; k*5+j*15+i*60<=delta; k++) - ret = min(ret, i+j+k+delta-(k*5+j*15+i*60)); - - return ret; - - } -}; From d19fb0016650b0a59d5c1ba9922bf458069c8f2d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Apr 2022 21:12:38 -0700 Subject: [PATCH 0624/2729] Create 2221.Find-Triangular-Sum-of-an-Array.cpp --- .../2221.Find-Triangular-Sum-of-an-Array.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Math/2221.Find-Triangular-Sum-of-an-Array/2221.Find-Triangular-Sum-of-an-Array.cpp diff --git a/Math/2221.Find-Triangular-Sum-of-an-Array/2221.Find-Triangular-Sum-of-an-Array.cpp b/Math/2221.Find-Triangular-Sum-of-an-Array/2221.Find-Triangular-Sum-of-an-Array.cpp new file mode 100644 index 000000000..28de457c6 --- /dev/null +++ b/Math/2221.Find-Triangular-Sum-of-an-Array/2221.Find-Triangular-Sum-of-an-Array.cpp @@ -0,0 +1,27 @@ +using ll = long long; +class Solution { +public: + int triangularSum(vector& nums) + { + ll comb[1000][1000]; + int n = nums.size()-1; + for (int i = 0; i <= n; ++i) + { + comb[i][i] = comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j < i; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + comb[i][j] %= 10; + } + } + + ll ret = 0; + for (int i=0; i<=n; i++) + { + ret += nums[i]*comb[n][i]%10; + } + + return ret%10; + } +}; From 226d7029e7f0fde65cebf2a883b43c162f3f7abb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Apr 2022 22:52:13 -0700 Subject: [PATCH 0625/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 120130914..0f24f4606 100644 --- a/Readme.md +++ b/Readme.md @@ -1007,6 +1007,7 @@ [1830.Minimum-Number-of-Operations-to-Make-String-Sorted](https://github.com/wisdompeak/LeetCode/tree/master/Math/1830.Minimum-Number-of-Operations-to-Make-String-Sorted) (H) [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) [1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony](https://github.com/wisdompeak/LeetCode/tree/master/Math/1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony) (H) +[2221.Find-Triangular-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Math/2221.Find-Triangular-Sum-of-an-Array) (M) * ``Numerical Theory`` [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) [365.Water-and-Jug-Problem](https://github.com/wisdompeak/LeetCode/tree/master/Math/365.Water-and-Jug-Problem) (H) From d6af7a483d81e5423e9c79f470b4146dadbbfaf4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Apr 2022 22:52:48 -0700 Subject: [PATCH 0626/2729] Create Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Template/Math/Combination-Number.cpp diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp new file mode 100644 index 000000000..9cd05886a --- /dev/null +++ b/Template/Math/Combination-Number.cpp @@ -0,0 +1,28 @@ +typedef long long ll; + +main() +{ + // compute all C(n,m) saved in comb + ll comb[1000][1000]; + for (int i = 0; i <= n; ++i) + { + comb[i][i] = comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j < i; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + } + } +} + +// Compute C(n,m) on demand +ll help(int n, int m) +{ + long long cnt = 1; + for(int i = 0; i < m; i++) + { + cnt *= n - i; + cnt /= i + 1; + } + return cnt; +} From ce4a3536bfefe6b5d00f5b3dc0c395a7e99bf586 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Apr 2022 22:53:05 -0700 Subject: [PATCH 0627/2729] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0f24f4606..1c6ef6ad4 100644 --- a/Readme.md +++ b/Readme.md @@ -1256,7 +1256,6 @@ [Inverse_Element](https://github.com/wisdompeak/LeetCode/tree/master/Template/Inverse_Element) [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Template/Graph) [Bit_Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Template/Bit_manipulation) -[Combination-Number](https://github.com/wisdompeak/LeetCode/tree/master/Template/Combination-Number) [RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) [二维子矩阵求和](https://github.com/wisdompeak/LeetCode/tree/master/Template/Sub_Rect_Sum_2D) [二维差分数组](https://github.com/wisdompeak/LeetCode/tree/master/Template/Diff_Array_2D) From 16af602fc8a69ac7f3ca8bda75f6077508cc395d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Apr 2022 23:19:32 -0700 Subject: [PATCH 0628/2729] Create Readme.md --- .../Readme.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md diff --git a/Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md b/Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md new file mode 100644 index 000000000..c5203a567 --- /dev/null +++ b/Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md @@ -0,0 +1,31 @@ +### 2221.Find-Triangular-Sum-of-an-Array + +本题最直观的方法就是模拟,根据数据规模,N^2的时间复杂度是可以接受的。 + +本题其实还有另外一个切入的角度。从题目上看,三角形的构造方法与杨辉三角形非常相似,所以此题一定和二项式系数有关。 + +我们从下往上观察,最后两行是 +``` +1 1 + 1 +``` +这意味着此时最上面一行的每一个元素对于最终结果(即最底角的元素)的贡献是1:1. + +再观察最后三行 +``` +1 2 1 + 1 1 + 1 +``` +此时发现,最上面一行的每一个元素对于最终结果(即最底角的元素)的贡献恰好就是1:2:1. 究其原因,元素(1,1)会复制给(2,1),元素(1,2)会复制给(2,1)和(2,2)造成了双倍的贡献,而元素(1,3)又会只贡献给(2,2)。也就是说,我们只需要通过第二行,就可以推出第一行里每个元素对于底角元素的贡献值。 + +再观察最后四行 +``` +1 3 3 1 + 1 2 1 + 1 1 + 1 +``` +很明显了,最上面一行的每个元素对于底角元素的贡献值比例1:3:3:1,它就是(a+b)^3的二项式系数,即C(3,0),C(3,1),C(3,2),C(3,3)。 + +于是我们就可以得出结论,令n = nums.size()-1,那么原始数值里的nums[i],会复制C(n,i)份计入到递交元素中。我们只需要将nums按照n次二项式系数加权平均即可。 From e195be4243febf3dc5de6669bcf25a480fc47f1d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Apr 2022 23:20:33 -0700 Subject: [PATCH 0629/2729] Update Readme.md --- Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md b/Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md index c5203a567..3aebc9fda 100644 --- a/Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md +++ b/Math/2221.Find-Triangular-Sum-of-an-Array/Readme.md @@ -26,6 +26,8 @@ 1 1 1 ``` -很明显了,最上面一行的每个元素对于底角元素的贡献值比例1:3:3:1,它就是(a+b)^3的二项式系数,即C(3,0),C(3,1),C(3,2),C(3,3)。 +很明显了,最上面一行的每个元素对于底角元素的贡献值比例1:3:3:1,它就是(a+b)^3的二项式系数,即C(3,0),C(3,1),C(3,2),C(3,3),其中C(x,y)表示组合数。 于是我们就可以得出结论,令n = nums.size()-1,那么原始数值里的nums[i],会复制C(n,i)份计入到递交元素中。我们只需要将nums按照n次二项式系数加权平均即可。 + +计算二项式系数,就是算组合数,可以参考[模板代码](https://github.com/wisdompeak/LeetCode/blob/master/Template/Math/Combination-Number.cpp) From f5018d70af6b94e9697f643f910fa3d57f74b410 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 7 Apr 2022 21:59:27 -0700 Subject: [PATCH 0630/2729] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1c6ef6ad4..1487784ba 100644 --- a/Readme.md +++ b/Readme.md @@ -120,7 +120,6 @@ [1891.Cutting-Ribbons](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1891.Cutting-Ribbons) (E) [2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store) (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) -[2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) [2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal) (M) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) From 540e935633fc5560fcf05fcb2ad7490732338a7b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 7 Apr 2022 23:53:23 -0700 Subject: [PATCH 0631/2729] Create 2226.Maximum-Candies-Allocated-to-K-Children.cpp --- ...aximum-Candies-Allocated-to-K-Children.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/2226.Maximum-Candies-Allocated-to-K-Children.cpp diff --git a/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/2226.Maximum-Candies-Allocated-to-K-Children.cpp b/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/2226.Maximum-Candies-Allocated-to-K-Children.cpp new file mode 100644 index 000000000..3b6ca33c3 --- /dev/null +++ b/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/2226.Maximum-Candies-Allocated-to-K-Children.cpp @@ -0,0 +1,33 @@ +using LL = long long; +class Solution { +public: + int maximumCandies(vector& candies, long long k) + { + LL total = 0; + for (auto x: candies) + total += (LL)x; + + LL left= 0, right = total/k; + while (left < right) + { + LL mid = right - (right - left) / 2; + if (checkOK(candies, mid, k)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool checkOK(vector& candies, LL numPerPile, LL k) + { + LL count = 0; + for (LL x: candies) + { + count += x / numPerPile; + if (count >= k) + return true; + } + return false; + } +}; From 7ee43d3b9161d8f799bd7b8998bc8c85233de82a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 7 Apr 2022 23:53:49 -0700 Subject: [PATCH 0632/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1487784ba..cc062a431 100644 --- a/Readme.md +++ b/Readme.md @@ -121,6 +121,7 @@ [2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store) (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal) (M) +[2226.Maximum-Candies-Allocated-to-K-Children](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children) (M) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From a0b69376306b63b0228a51882f1e9d524ac551e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Apr 2022 00:08:01 -0700 Subject: [PATCH 0633/2729] Create Readme.md --- .../2226.Maximum-Candies-Allocated-to-K-Children/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/Readme.md diff --git a/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/Readme.md b/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/Readme.md new file mode 100644 index 000000000..5d802048d --- /dev/null +++ b/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/Readme.md @@ -0,0 +1,7 @@ +### 2226.Maximum-Candies-Allocated-to-K-Children + +这是一道非常明显的二分搜值的题目。 + +我们令每个孩子可以分得的糖果数目记做x。如果x很大,意味着我们可以构造的、符合条件(即每堆恰有x个糖果)的堆数会变少,极有可能最终不够k堆。反之,如果x很小,意味着我们可以构造出更多的、符合条件的堆数,甚至超过k堆,导致这个答案不够优秀。所以我们可以通过二分搜索尝试不同的x的值,来逼近最大的x,使得构造出的堆数恰好大于等于k。 + +对于给定的x,将每堆的糖果个数除以x,就是该堆可以拆分出的、符合条件的堆数。我们只需检验符合条件的总堆数是否大于等于k即可。 From dc0906c85137a58b494865d6719d9cd2e30418fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Apr 2022 13:35:29 -0700 Subject: [PATCH 0634/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cc062a431..1088d7966 100644 --- a/Readme.md +++ b/Readme.md @@ -69,7 +69,6 @@ [222.Count-Complete-Tree-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/222.Count-Complete-Tree-Nodes) (H-) [275.H-index II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/275.H-Index-II) (H) [302.Smallest-Rectangle-Enclosing-Black-Pixels](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/302.Smallest-Rectangle-Enclosing-Black-Pixels) (M+) -[410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H) [475.Heaters](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/475.Heaters) (H-) [483.Smallest-Good-Base](https://github.com/wisdompeak/LeetCode/blob/master/Binary_Search/483.Smallest-Good-Base) (H) [029.Divide-Two-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/029.Divide-Two-Integers) (M+) @@ -100,6 +99,7 @@ [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [786.Kth-Smallest-Prime-Fraction](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/786.K-th%20Smallest-Prime-Fraction) (H-) [793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) +[410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [1011.Capacity-To-Ship-Packages-Within-D-Days](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1011.Capacity-To-Ship-Packages-Within-D-Days) (M) [1060.Missing-Element-in-Sorted-Array](https://github.com/wisdompeak/LeetCode/blob/master/Binary_Search/1060.Missing-Element-in-Sorted-Array) (H) [1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) From 3a7d11ff2704ec272b714f49d6ab04ef88ded04b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Apr 2022 13:37:51 -0700 Subject: [PATCH 0635/2729] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1088d7966..384e9c62c 100644 --- a/Readme.md +++ b/Readme.md @@ -76,7 +76,6 @@ [658.Find-K-Closest-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/658.Find-K-Closest-Elements) (H) 1095.Find-in-Mountain-Array (TBD) [1157.Online-Majority-Element-In-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1157.Online-Majority-Element-In-Subarray) (H-) -1201.Ugly-Number-III (TBD) [1533.Find-the-Index-of-the-Large-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1533.Find-the-Index-of-the-Large-Integer) (M) [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) From 2cfe778cbc552bfb1b6170da3996c11e1328e5b3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Apr 2022 13:38:53 -0700 Subject: [PATCH 0636/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 384e9c62c..426ddae27 100644 --- a/Readme.md +++ b/Readme.md @@ -80,8 +80,6 @@ [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) -[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) -[2141.Maximum-Running-Time-of-N-Computers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2141.Maximum-Running-Time-of-N-Computers) (M+) * ``Binary Processing`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) @@ -119,7 +117,9 @@ [1891.Cutting-Ribbons](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1891.Cutting-Ribbons) (E) [2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2064.Minimized-Maximum-of-Products-Distributed-to-Any-Store) (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) +[2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) [2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal) (M) +[2141.Maximum-Running-Time-of-N-Computers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2141.Maximum-Running-Time-of-N-Computers) (M+) [2226.Maximum-Candies-Allocated-to-K-Children](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children) (M) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) From 0537233dbd98844f50ece0186aa3b34bc242b032 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Apr 2022 22:56:07 -0700 Subject: [PATCH 0637/2729] Update Readme.md --- .../2226.Maximum-Candies-Allocated-to-K-Children/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/Readme.md b/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/Readme.md index 5d802048d..5535a9e03 100644 --- a/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/Readme.md +++ b/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children/Readme.md @@ -5,3 +5,5 @@ 我们令每个孩子可以分得的糖果数目记做x。如果x很大,意味着我们可以构造的、符合条件(即每堆恰有x个糖果)的堆数会变少,极有可能最终不够k堆。反之,如果x很小,意味着我们可以构造出更多的、符合条件的堆数,甚至超过k堆,导致这个答案不够优秀。所以我们可以通过二分搜索尝试不同的x的值,来逼近最大的x,使得构造出的堆数恰好大于等于k。 对于给定的x,将每堆的糖果个数除以x,就是该堆可以拆分出的、符合条件的堆数。我们只需检验符合条件的总堆数是否大于等于k即可。 + +此题和```1891. Cutting Ribbons```一模一样. From f22238c8ba1c9c1848f3adf7eee037ad3a7a4363 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Apr 2022 17:30:19 -0700 Subject: [PATCH 0638/2729] Update Readme.md --- Readme.md | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/Readme.md b/Readme.md index 426ddae27..790370101 100644 --- a/Readme.md +++ b/Readme.md @@ -84,23 +84,11 @@ [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) * ``Binary Search by Value`` -[215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) -[287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) -[378.Kth-Smallest-Element-in-a-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix) (H-) -[373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums) (H) -[668.Kth-Smallest-Number-in-Multiplication-Table](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table) (H-) -[719.Find-Kth-Smallest-Pair-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/719.Find-K-th-Smallest-Pair-Distance) (H-) -[1918.Kth-Smallest-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1918.Kth-Smallest-Subarray-Sum) (M+) -[2040.Kth-Smallest-Product-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays) (H-) -[1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows) (H) -[774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) -[786.Kth-Smallest-Prime-Fraction](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/786.K-th%20Smallest-Prime-Fraction) (H-) -[793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) +[774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [1011.Capacity-To-Ship-Packages-Within-D-Days](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1011.Capacity-To-Ship-Packages-Within-D-Days) (M) [1060.Missing-Element-in-Sorted-Array](https://github.com/wisdompeak/LeetCode/blob/master/Binary_Search/1060.Missing-Element-in-Sorted-Array) (H) [1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) -[1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) [1201.Ugly-Number-III](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1201.Ugly-Number-III) (H-) [1231.Divide-Chocolate](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1231.Divide-Chocolate) (M) [1283.Find-the-Smallest-Divisor-Given-a-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1283.Find-the-Smallest-Divisor-Given-a-Threshold) (M) @@ -121,6 +109,19 @@ [2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal) (M) [2141.Maximum-Running-Time-of-N-Computers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2141.Maximum-Running-Time-of-N-Computers) (M+) [2226.Maximum-Candies-Allocated-to-K-Children](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children) (M) + * ``Find K-th Element`` +[215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) +[287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) +[378.Kth-Smallest-Element-in-a-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/378.Kth-Smallest-Element-in-a-Sorted-Matrix) (H-) +[373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums) (H) +[668.Kth-Smallest-Number-in-Multiplication-Table](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/668.Kth-Smallest-Number-in-Multiplication-Table) (H-) +[719.Find-Kth-Smallest-Pair-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/719.Find-K-th-Smallest-Pair-Distance) (H-) +[1918.Kth-Smallest-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1918.Kth-Smallest-Subarray-Sum) (M+) +[2040.Kth-Smallest-Product-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2040.Kth-Smallest-Product-of-Two-Sorted-Arrays) (H-) +[1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows) (H) +[786.Kth-Smallest-Prime-Fraction](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/786.K-th%20Smallest-Prime-Fraction) (H-) +[793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) +[1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From bce5828c53a36a200891d6d59b7e12f1e74f6629 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Apr 2022 17:57:18 -0700 Subject: [PATCH 0639/2729] Create 2214.Minimum-Health-to-Beat-Game.cpp --- .../2214.Minimum-Health-to-Beat-Game.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Dynamic_Programming/2214.Minimum-Health-to-Beat-Game/2214.Minimum-Health-to-Beat-Game.cpp diff --git a/Dynamic_Programming/2214.Minimum-Health-to-Beat-Game/2214.Minimum-Health-to-Beat-Game.cpp b/Dynamic_Programming/2214.Minimum-Health-to-Beat-Game/2214.Minimum-Health-to-Beat-Game.cpp new file mode 100644 index 000000000..e611d188a --- /dev/null +++ b/Dynamic_Programming/2214.Minimum-Health-to-Beat-Game/2214.Minimum-Health-to-Beat-Game.cpp @@ -0,0 +1,20 @@ +using LL = long long; +class Solution { +public: + long long minimumHealth(vector& damage, int armor) + { + int n = damage.size(); + LL dp0 = 0; + LL dp1 = 0; + LL ret = LLONG_MAX; + for (int i=0; i 0? 0 : (-ret+1); + } +}; From f3b3b1414790d855cdfb424faca4e53fb8e9996b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Apr 2022 18:03:06 -0700 Subject: [PATCH 0640/2729] Create Readme.md --- .../2214.Minimum-Health-to-Beat-Game/Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Dynamic_Programming/2214.Minimum-Health-to-Beat-Game/Readme.md diff --git a/Dynamic_Programming/2214.Minimum-Health-to-Beat-Game/Readme.md b/Dynamic_Programming/2214.Minimum-Health-to-Beat-Game/Readme.md new file mode 100644 index 000000000..47f9bd814 --- /dev/null +++ b/Dynamic_Programming/2214.Minimum-Health-to-Beat-Game/Readme.md @@ -0,0 +1,10 @@ +### 2214.Minimum-Health-to-Beat-Game + +我们用dp0[i]表示通过第i关时仍未使用盔甲能够存留的最大血量,dp1[i]表示通过第i关时已经使用盔甲能够存留的最大血量,于是转移方程就是 +``` +dp0[i] = dp0[i] - damage[i]; +dp1[i] = max(dp1[i] - damage[i], dp0[i] - max(0, damage[i]-armor)); +``` +我们假设初始血量是0,模拟走一遍上面的流程。由此,```max(dp0[i], dp1[i])```表示的就是通过第i关所能存留的最大血量。 + +要保证在通过的过程中的最大血量始终都大于0,那么就观察所有```max(dp0[i], dp1[i])```里的最低点,通过加上这个offset来保证全程的血量都不低于1. From 34014e9f1a516461801186d3485fdc581514e2cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Apr 2022 18:13:22 -0700 Subject: [PATCH 0641/2729] Create 2227.Encrypt-and-Decrypt-Strings.cpp --- .../2227.Encrypt-and-Decrypt-Strings.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Design/2227.Encrypt-and-Decrypt-Strings/2227.Encrypt-and-Decrypt-Strings.cpp diff --git a/Design/2227.Encrypt-and-Decrypt-Strings/2227.Encrypt-and-Decrypt-Strings.cpp b/Design/2227.Encrypt-and-Decrypt-Strings/2227.Encrypt-and-Decrypt-Strings.cpp new file mode 100644 index 000000000..d20fd1357 --- /dev/null +++ b/Design/2227.Encrypt-and-Decrypt-Strings/2227.Encrypt-and-Decrypt-Strings.cpp @@ -0,0 +1,51 @@ +class Encrypter { + unordered_mapMap1; + unordered_map>Map2; + unordered_mapcount; + +public: + Encrypter(vector& keys, vector& values, vector& dictionary) + { + + for (int i=0; iencrypt(word1); + * int param_2 = obj->decrypt(word2); + */ From 453db6093b1f32919d30ba14a15a2a4d7c8b44ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Apr 2022 18:35:36 -0700 Subject: [PATCH 0642/2729] Update 2227.Encrypt-and-Decrypt-Strings.cpp --- .../2227.Encrypt-and-Decrypt-Strings.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Design/2227.Encrypt-and-Decrypt-Strings/2227.Encrypt-and-Decrypt-Strings.cpp b/Design/2227.Encrypt-and-Decrypt-Strings/2227.Encrypt-and-Decrypt-Strings.cpp index d20fd1357..2d0486d19 100644 --- a/Design/2227.Encrypt-and-Decrypt-Strings/2227.Encrypt-and-Decrypt-Strings.cpp +++ b/Design/2227.Encrypt-and-Decrypt-Strings/2227.Encrypt-and-Decrypt-Strings.cpp @@ -1,6 +1,5 @@ class Encrypter { unordered_mapMap1; - unordered_map>Map2; unordered_mapcount; public: @@ -10,7 +9,6 @@ class Encrypter { for (int i=0; i Date: Sun, 10 Apr 2022 11:50:42 -0700 Subject: [PATCH 0643/2729] Create Readme.md --- Design/2227.Encrypt-and-Decrypt-Strings/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Design/2227.Encrypt-and-Decrypt-Strings/Readme.md diff --git a/Design/2227.Encrypt-and-Decrypt-Strings/Readme.md b/Design/2227.Encrypt-and-Decrypt-Strings/Readme.md new file mode 100644 index 000000000..cca42343f --- /dev/null +++ b/Design/2227.Encrypt-and-Decrypt-Strings/Readme.md @@ -0,0 +1,5 @@ +### 2227.Encrypt-and-Decrypt-Strings + +本题的关键在于解码的时候会遇到一对多的反映射,极有可能需要递归分支来处理。其实此题的巧解在于给出的dictionary规模非常小,我们可以将其加密之后与给出的word2进行比较。也就是说,有多少candidates加密之后是word2,那么就意味着word2解密之后有多少是在candidates里面。 + +特别注意,题中保证了所有的word1都能被加密,但是不保证所有的candidate都能够被加密。 From a668463b6c1ce94e44657285cf81059186f5741e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 12:03:21 -0700 Subject: [PATCH 0644/2729] Create 2233.Maximum-Product-After-K-Increments.cpp --- ...233.Maximum-Product-After-K-Increments.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Greedy/2233.Maximum-Product-After-K-Increments/2233.Maximum-Product-After-K-Increments.cpp diff --git a/Greedy/2233.Maximum-Product-After-K-Increments/2233.Maximum-Product-After-K-Increments.cpp b/Greedy/2233.Maximum-Product-After-K-Increments/2233.Maximum-Product-After-K-Increments.cpp new file mode 100644 index 000000000..7bfa737bf --- /dev/null +++ b/Greedy/2233.Maximum-Product-After-K-Increments/2233.Maximum-Product-After-K-Increments.cpp @@ -0,0 +1,35 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int maximumProduct(vector& nums, int k) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + + vectorpresum(n); + for (int i=0; idiff(n); + for (int i=0; i Date: Sun, 10 Apr 2022 12:04:32 -0700 Subject: [PATCH 0645/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 790370101..df7eab53c 100644 --- a/Readme.md +++ b/Readme.md @@ -1069,6 +1069,7 @@ [2182.Construct-String-With-Repeat-Limit](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2182.Construct-String-With-Repeat-Limit) (M+) [2193.Minimum-Number-of-Moves-to-Make-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome) (H+) [2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) +[2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 29bef74dd503b0130146ef67e1b8ee2a9ba3a706 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 12:22:34 -0700 Subject: [PATCH 0646/2729] Create Readme.md --- Greedy/2233.Maximum-Product-After-K-Increments/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2233.Maximum-Product-After-K-Increments/Readme.md diff --git a/Greedy/2233.Maximum-Product-After-K-Increments/Readme.md b/Greedy/2233.Maximum-Product-After-K-Increments/Readme.md new file mode 100644 index 000000000..434e83dba --- /dev/null +++ b/Greedy/2233.Maximum-Product-After-K-Increments/Readme.md @@ -0,0 +1,9 @@ +### 2233.Maximum-Product-After-K-Increments + +这道题的贪心策略非常明显。因为所有元素的和是固定的(包括原来的sum加上新增的K)、元素数目是固定的,那么尽量让这些元素变得相等,是让乘积最大化的唯一策略。 + +因为本题对于元素的操作是只增不减,所以我们需要将K都分配给较小的元素,尽量“共同富裕”。那么我们将nums排序之后,需要将K分配给前多少个较小元素呢?显然我们要找到一个位置p,使得前p个元素之和加上K之后再进行平均分配,依然达不到第p+1个元素. 为什么呢?如果前p个元素进行共产主义之后,均值大于了第p+1个元素,那为什么不在前p+1个元素内进行“共同富裕”呢,这样就有更多的元素可以趋近一致,从而使乘积最大化。 + +那么我们如何快速定位这个p呢?我们定义diff数组```diff[i] = presum[i]+K - nums[i]*(i+1)```,表明将前i+1个元素都提升至与nums[i]相等的话,需要多少“支援”。可以知道,这个diff一定是递增的。于是我们可以用二分找到最大的p,使得恰好```diff[p]<=K```,意味着K的支援能够将nums[0:p]抹平,但是不足以将nums[0:p+1]抹平。 + +我们接下来的任务就是,用```presum[p]+K```这些数量在前p+1个元素内平均分配。注意可能会有余数。我们令```each = (presum[p]+K)/(p+1)```表示每个元素至少能分配到each;再令```extra = (presum[p]+K)%(p+1)```表示有这么多余数,可以让extra元素能分配到each+1. 所以最终结果就是把```extra```个```each+1```,```p+1-extra```个```each```,以及从p+1开始的剩余的nums相乘。 From 1b6f7347b89a8b314ea79f31672f1800569cfd26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 12:23:11 -0700 Subject: [PATCH 0647/2729] Update Readme.md --- Greedy/2233.Maximum-Product-After-K-Increments/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2233.Maximum-Product-After-K-Increments/Readme.md b/Greedy/2233.Maximum-Product-After-K-Increments/Readme.md index 434e83dba..4378288c3 100644 --- a/Greedy/2233.Maximum-Product-After-K-Increments/Readme.md +++ b/Greedy/2233.Maximum-Product-After-K-Increments/Readme.md @@ -2,7 +2,7 @@ 这道题的贪心策略非常明显。因为所有元素的和是固定的(包括原来的sum加上新增的K)、元素数目是固定的,那么尽量让这些元素变得相等,是让乘积最大化的唯一策略。 -因为本题对于元素的操作是只增不减,所以我们需要将K都分配给较小的元素,尽量“共同富裕”。那么我们将nums排序之后,需要将K分配给前多少个较小元素呢?显然我们要找到一个位置p,使得前p个元素之和加上K之后再进行平均分配,依然达不到第p+1个元素. 为什么呢?如果前p个元素进行共产主义之后,均值大于了第p+1个元素,那为什么不在前p+1个元素内进行“共同富裕”呢,这样就有更多的元素可以趋近一致,从而使乘积最大化。 +因为本题对于元素的操作是只增不减,所以我们需要将K都分配给较小的元素,尽量“共同富裕”。那么我们将nums排序之后,需要将K分配给前多少个较小元素呢?显然我们要找到一个位置p,使得前p个元素之和加上K之后再进行平均分配,依然达不到第p+1个元素. 为什么呢?如果前p个元素进行共产主义之后,均值大于了第p+1个元素,那为什么不在前p+1个元素内进行“共同富裕”呢,这样就有更多的元素可以趋近一致,从而使乘积更大化。 那么我们如何快速定位这个p呢?我们定义diff数组```diff[i] = presum[i]+K - nums[i]*(i+1)```,表明将前i+1个元素都提升至与nums[i]相等的话,需要多少“支援”。可以知道,这个diff一定是递增的。于是我们可以用二分找到最大的p,使得恰好```diff[p]<=K```,意味着K的支援能够将nums[0:p]抹平,但是不足以将nums[0:p+1]抹平。 From b31fa31e9d6f0f1324ae8ff4f5e67e6ba1a5248e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 12:29:38 -0700 Subject: [PATCH 0648/2729] Create 2224.Maximum-Total-Beauty-of-the-Gardens.cpp --- ...24.Maximum-Total-Beauty-of-the-Gardens.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Greedy/2224.Maximum-Total-Beauty-of-the-Gardens/2224.Maximum-Total-Beauty-of-the-Gardens.cpp diff --git a/Greedy/2224.Maximum-Total-Beauty-of-the-Gardens/2224.Maximum-Total-Beauty-of-the-Gardens.cpp b/Greedy/2224.Maximum-Total-Beauty-of-the-Gardens/2224.Maximum-Total-Beauty-of-the-Gardens.cpp new file mode 100644 index 000000000..d86dc8470 --- /dev/null +++ b/Greedy/2224.Maximum-Total-Beauty-of-the-Gardens/2224.Maximum-Total-Beauty-of-the-Gardens.cpp @@ -0,0 +1,50 @@ +using LL = long long; +class Solution { +public: + long long maximumBeauty(vector& flowers, long long newFlowers, int target, int full, int partial) + { + sort(flowers.begin(), flowers.end()); + + LL ret0 = 0; + while (flowers.size()>0 && flowers.back()>=target) + { + ret0 += full; + flowers.pop_back(); + } + if (flowers.empty()) return ret0; + + LL n = flowers.size(); + vectorpresum(n); + for (LL i=0; idiff(n); + for (LL i=0; i=0; i--) + { + if (newFlowers < 0) break; + + if (presum[i]+(LL)newFlowers >= (LL)(target-1)*(LL)(i+1)) + { + ret = max(ret, (LL)(target-1)*partial + (n-1-i)*(LL)full); + newFlowers -= target-flowers[i]; + } + else + { + auto iter = upper_bound(diff.begin(), diff.begin()+i+1, newFlowers); + int k = prev(iter) - diff.begin(); + LL total = presum[k] + newFlowers; + LL each = total / (LL)(k+1); + ret = max(ret, each*partial + (LL)(n-1-i)*full); + newFlowers -= target-flowers[i]; + } + } + + if (newFlowers>=0) + ret = max(ret, n*full); + + return ret + ret0; + } +}; From 6660b2da56a3fe7ed40ff08f33e5cc7465038129 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 12:30:46 -0700 Subject: [PATCH 0649/2729] Rename Greedy/2224.Maximum-Total-Beauty-of-the-Gardens/2224.Maximum-Total-Beauty-of-the-Gardens.cpp to Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/2234.Maximum-Total-Beauty-of-the-Gardens.cpp --- .../2234.Maximum-Total-Beauty-of-the-Gardens.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/{2224.Maximum-Total-Beauty-of-the-Gardens/2224.Maximum-Total-Beauty-of-the-Gardens.cpp => 2234.Maximum-Total-Beauty-of-the-Gardens/2234.Maximum-Total-Beauty-of-the-Gardens.cpp} (100%) diff --git a/Greedy/2224.Maximum-Total-Beauty-of-the-Gardens/2224.Maximum-Total-Beauty-of-the-Gardens.cpp b/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/2234.Maximum-Total-Beauty-of-the-Gardens.cpp similarity index 100% rename from Greedy/2224.Maximum-Total-Beauty-of-the-Gardens/2224.Maximum-Total-Beauty-of-the-Gardens.cpp rename to Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/2234.Maximum-Total-Beauty-of-the-Gardens.cpp From 03e6691b251c2199785352c947c53dcc5ad306f5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 12:31:13 -0700 Subject: [PATCH 0650/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index df7eab53c..9f1c75876 100644 --- a/Readme.md +++ b/Readme.md @@ -1070,6 +1070,7 @@ [2193.Minimum-Number-of-Moves-to-Make-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome) (H+) [2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) +[2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 54d481e9821469b2ecc85c47fe2166af75390000 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 22:33:29 -0700 Subject: [PATCH 0651/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md diff --git a/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md b/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md new file mode 100644 index 000000000..c9c9aefb0 --- /dev/null +++ b/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md @@ -0,0 +1,13 @@ +### 2234.Maximum-Total-Beauty-of-the-Gardens + +很明显,我们要将所有的花园分为两部分,一部分是将其变为complete,另一部分是保持incomplete。相比之下,我们肯定是将那些flowers数值已经较大的花园变为complete更为合算,因为能省下更多的种植配额去提升那些incomplete花园的短板。 + +于是我们自然会将flowers数组从小到大排序。我们需要遍历两种花园的分界点i,即编号0到i的花园必须都是incomplete,编号i+1到n-1的花园必须都是complete。对于后者,我们很容易算出所需要额外种植的数目:即忽略已经超过target的花园,将那些未满target的花园补足至target。于是我们将这个需要补足的数目从newFlowers中减去,可以知道剩余的配额,将会用来处理那些认定是incomplete的花园(即编号从0到i的花园)。此外,根据规则,后者部分我们的收益是```(n-i)*full```. + +ok,此时我们的任务就是,在0到i的花园里分配剩余的newFlowers,使得可以将这些花园里的最小数目最大化(因为这部分的收益函数是最小的数目乘以partial)。但是需要注意一点的是,因为我们认定了这些花园是incomplete的,它们注定都不能超过target-1. 所以我们需要考虑第一种情况,如果newFlowers配额非常充裕,我们可以将这些incomplete的花园都补足到target-1,于是可以得分```(target-1)*partial```. + +第二种情况,就是newFlowers配额有限,只能用于增补那些数目最少的花园,以提升短板。此时我们就要考虑将可以将短板提升至多少?所谓提升短板,就是说我们需要确定一个位置p,使得newFlowers可以将编号从0到p的花园都提升到同一个数值。这个p是怎么得到的呢,其实是因为newFlowers不够大,只能将编号0到p的花园提升到同一个数值,但是无法将编号0到p+1的花园提升到同一个数值。所以我们就明确了p的意义,即寻找最大的p,使得```sum[0:p] + newFlowers >= flowers[p]*(p+1)```,或者说```flowers[p]*(p+1) - presum[p] <= newFlowers```。 我们令```diff[p] = flowers[p]*(p+1) - presum[p]```,即表示将前p+1个花园都提升至flowers[p]的数量所需要额外种植的配额,那么diff数值显然是个单调增函数,我们必然可以用二分法确定这个临界位置p。有了这个临界位置p,那么我们就可以用```(presum[p]+newFlowers) / (p+1)```来计算我们将前p+1个花园的短板最大提升至多少。 + +所以本题的时间复杂度是o(NlogN),外层就是遍历incomplete/complete的分界点i,内部就是二分查找短板的范围p。 + +事实上p肯定也是单调从大到小变化的,所以本题理论上可以优化至o(N). From b9b7e31dd8797ccb700fc788d84a9461bbea4def Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 22:34:10 -0700 Subject: [PATCH 0652/2729] Update Readme.md --- Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md b/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md index c9c9aefb0..2cdc2bd2a 100644 --- a/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md +++ b/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/Readme.md @@ -10,4 +10,4 @@ ok,此时我们的任务就是,在0到i的花园里分配剩余的newFlowers 所以本题的时间复杂度是o(NlogN),外层就是遍历incomplete/complete的分界点i,内部就是二分查找短板的范围p。 -事实上p肯定也是单调从大到小变化的,所以本题理论上可以优化至o(N). +事实上p肯定也是单调从大到小变化的,所以搜索的过程理论上可以优化至o(N),不过因为我们最开始需要对flowers排序,这点优化就没有必要了. From 690624f3e2a910a78586eaced3fd97cf3c8584c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Apr 2022 22:37:23 -0700 Subject: [PATCH 0653/2729] Update 2234.Maximum-Total-Beauty-of-the-Gardens.cpp --- .../2234.Maximum-Total-Beauty-of-the-Gardens.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/2234.Maximum-Total-Beauty-of-the-Gardens.cpp b/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/2234.Maximum-Total-Beauty-of-the-Gardens.cpp index d86dc8470..5ca86707d 100644 --- a/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/2234.Maximum-Total-Beauty-of-the-Gardens.cpp +++ b/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens/2234.Maximum-Total-Beauty-of-the-Gardens.cpp @@ -26,10 +26,9 @@ class Solution { { if (newFlowers < 0) break; - if (presum[i]+(LL)newFlowers >= (LL)(target-1)*(LL)(i+1)) + if (presum[i]+newFlowers >= (LL)(target-1)*(i+1)) { - ret = max(ret, (LL)(target-1)*partial + (n-1-i)*(LL)full); - newFlowers -= target-flowers[i]; + ret = max(ret, (LL)(target-1)*partial + (LL)(n-1-i)*full); } else { @@ -37,9 +36,9 @@ class Solution { int k = prev(iter) - diff.begin(); LL total = presum[k] + newFlowers; LL each = total / (LL)(k+1); - ret = max(ret, each*partial + (LL)(n-1-i)*full); - newFlowers -= target-flowers[i]; + ret = max(ret, each*partial + (LL)(n-1-i)*full); } + newFlowers -= target-flowers[i]; } if (newFlowers>=0) From e41a5acd1acc4520e40eeeb77adaa348c4f74754 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 12 Apr 2022 21:14:05 -0700 Subject: [PATCH 0654/2729] Update 1286.Iterator-for-Combination.cpp --- .../1286.Iterator-for-Combination.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Math/1286.Iterator-for-Combination/1286.Iterator-for-Combination.cpp b/Math/1286.Iterator-for-Combination/1286.Iterator-for-Combination.cpp index 9726993eb..f050f3ed1 100644 --- a/Math/1286.Iterator-for-Combination/1286.Iterator-for-Combination.cpp +++ b/Math/1286.Iterator-for-Combination/1286.Iterator-for-Combination.cpp @@ -1,7 +1,7 @@ class CombinationIterator { string cur; string end; - bool flag; + bool firstCall; string characters; int combinationLength; @@ -10,16 +10,16 @@ class CombinationIterator { { cur = characters.substr(0,combinationLength); end = characters.substr(characters.size()-combinationLength); - flag = 1; + firstCall = 1; this->characters = characters; this->combinationLength = combinationLength; } string next() { - if (flag) + if (firstCall) { - flag = 0; + firstCall = 0; return cur; } @@ -37,6 +37,6 @@ class CombinationIterator { bool hasNext() { - return cur!=end; + return firstCall==1 || cur!=end; } }; From 25981a6394a6870f05c415435c7c889df72e7a82 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 12 Apr 2022 21:17:34 -0700 Subject: [PATCH 0655/2729] Update 1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold.cpp --- ...-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold.cpp b/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold.cpp index d9b945455..bb528f47a 100644 --- a/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold.cpp +++ b/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold.cpp @@ -15,7 +15,7 @@ class Solution { for (int j=1; j<=n; j++) presum[i][j] = presum[i-1][j]+presum[i][j-1]-presum[i-1][j-1]+mat[i-1][j-1]; - int left = 1, right = min(m,n); + int left = 0, right = min(m,n); while (left < right) { int mid = right-(right-left)/2; @@ -24,8 +24,7 @@ class Solution { else right = mid-1; } - if (isOK(left, threshold)) return left; - else return 0; + return left; } bool isOK(int len, int threshold) From 53d681d444b981da7804e20af5b19f856fa54cfa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 12 Apr 2022 22:38:53 -0700 Subject: [PATCH 0656/2729] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/Readme.md b/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/Readme.md index 044a5f212..4fb211e37 100644 --- a/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/Readme.md +++ b/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/Readme.md @@ -1,7 +1,7 @@ ### 1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold -本题可以遍历每个方阵,查看方阵的和sum是否满足条件。这样的时间复杂度是o(N^3),其中遍历每个元素作为方阵的右下角需要o(N^2),探索不同的边长需要o(N)。 +本题可以遍历每个方阵,查看方阵的和sum是否满足条件。这样的时间复杂度是o(N^4),其中遍历每个元素作为方阵的右下角需要o(N^2),随着边长的增长,面积增长的速率是o(N^2)。 -本题更高效的方法就是二分搜值。猜测一个边长len,查看是否有一个方阵的sum满足条件。这样的时间复杂度是o(logN*N^2). +本题更高效的方法就是二分搜值。猜测一个边长len,查看是否有一个方阵的sum满足条件。这样的时间复杂度是```o(logN*N^2)```. 注意,本题中计算一个方阵的sum的方法可以是o(1),只要提前计算所有(0,0)到(i,j)的矩阵和presum[i][j]。 From 6329ccadd3c54c817459951a4f4e2a91e719231c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 12 Apr 2022 22:41:26 -0700 Subject: [PATCH 0657/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/Readme.md b/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/Readme.md index 4fb211e37..b1655a649 100644 --- a/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/Readme.md +++ b/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold/Readme.md @@ -4,4 +4,4 @@ 本题更高效的方法就是二分搜值。猜测一个边长len,查看是否有一个方阵的sum满足条件。这样的时间复杂度是```o(logN*N^2)```. -注意,本题中计算一个方阵的sum的方法可以是o(1),只要提前计算所有(0,0)到(i,j)的矩阵和presum[i][j]。 +注意,本题中计算任意一个方阵的元素sum的复杂度是o(1),因为只要提前计算二维的前缀和presum[i][j]即可。例如,以(a,b)为左上角、(x,y)为右下角的矩阵,其元素和就是```presum[x][y]-presum[i-1][y]-presum[i][y-1]+presum[i-1][j-1]```. From 5f79b5738e83ac787cdaf750925f7e7f2c77facb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 13 Apr 2022 22:07:21 -0700 Subject: [PATCH 0658/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/Readme.md b/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/Readme.md index 4a34980fe..56f4afacb 100644 --- a/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/Readme.md +++ b/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible/Readme.md @@ -18,7 +18,7 @@ 高中数学的全排列公式 ```A(n,m) = n!/(n-m)!``` #### 从n个数里取m个数,构造一个环排列 -基于全排列公式再去重 ```A(n,m) = n!/(n-m)!/m!``` +基于全排列公式再去重 ```A(n,m) = n!/(n-m)!/m``` #### 从n个数里构造m个全排列 令dp[i][j]表示从前i个数里面构造j个全排列。考虑第i个数: From 0cbbe69c84a3faba14b44c06e013c39cf0efc328 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Apr 2022 00:10:43 -0700 Subject: [PATCH 0659/2729] Update Readme.md --- Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md b/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md index 910ea9349..1aa52cdf8 100644 --- a/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md +++ b/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md @@ -4,7 +4,7 @@ ```wage[i]/quality[i]```最高的那位,意味着最不实惠的工人,它拉高了unitWage,使得其他工人都必须按照这个unitWage乘以各自的quality拿工资.但转念一想,如果我们必须雇佣这个最不实惠的工人的话,那么剩下的工人该如何选择呢?显然我们只要选K-1个quality最低的工人,他们可以拉高那个"最不实惠工人"的quality比重,从而减少其他工人的quality比重,从而降低总工资. -我们再考虑,如果选择了```wage[i]/quality[i]```第二高的那位,那么我们就在接下来的N-2个人里面选择K-1个quality最底的工人即可. +我们再考虑,如果选择了```wage[i]/quality[i]```第二高的那位,那么我们就在接下来的N-2个人(本质是性价比相对于i更优的N-2个人)里面选择K-1个quality最底的工人即可. 由此贪心法的最优策略就出来了.实际操作中,我们根据```wage[i]/quality[i]```从低到高进行处理. From 483130abef3276d2b1bf30995c1e8e0fc3a26c84 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Apr 2022 00:11:43 -0700 Subject: [PATCH 0660/2729] Update Readme.md --- Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md b/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md index 1aa52cdf8..969c7251f 100644 --- a/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md +++ b/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers/Readme.md @@ -6,7 +6,7 @@ 我们再考虑,如果选择了```wage[i]/quality[i]```第二高的那位,那么我们就在接下来的N-2个人(本质是性价比相对于i更优的N-2个人)里面选择K-1个quality最底的工人即可. -由此贪心法的最优策略就出来了.实际操作中,我们根据```wage[i]/quality[i]```从低到高进行处理. +由此贪心法的最优策略就出来了.实际操作中,我们根据```wage[i]/quality[i]```从低到高进行处理.如果选i,那么我们就在i之前的员工里挑K-1个quality最小的人。 [Leetcode Link](https://leetcode.com/problems/minimum-cost-to-hire-k-workers) From 7d3ca5aaa03a7315fb895cf255d9bb1903c20aa6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Apr 2022 20:30:31 -0700 Subject: [PATCH 0661/2729] Update Readme.md --- Others/1862.Sum-of-Floored-Pairs/Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Others/1862.Sum-of-Floored-Pairs/Readme.md b/Others/1862.Sum-of-Floored-Pairs/Readme.md index 67bd37a28..1244d1ef2 100644 --- a/Others/1862.Sum-of-Floored-Pairs/Readme.md +++ b/Others/1862.Sum-of-Floored-Pairs/Readme.md @@ -2,6 +2,8 @@ 首先,题目中计算任意两个元素之间的floor div,意味着数组里面的元素顺序并没有任何意义。我们可以任意选定一个元素i作为分母,考虑其他元素j做分子进行除法的结果。 -显然,对于比```nums[i] = x```小的元素做分子,结果都是零,没有意义。我们只关心那些比x大的元素。我们知道,数值位于区间```[x*k, x*(k+1)-1]```的元素作为分子,除法的结果就是k(k=1,2,3...)。自然地我们想知道数值位于该区间的元素多少?我们发现数组元素的数值大小的上限是100000,联想到桶排序,我们只需预处理每个数组元素s,将其出现的频次统计在count[s]里。如果想知道大小位于某个区间内的元素的频次和,只需要用count的前缀和数组presum即可。 +显然,对于比```nums[i] = x```小的元素做分子,结果都是零,没有意义。我们只关心那些比x大的元素。我们知道,数值位于区间```[x*k, x*(k+1)-1]```的元素作为分子(k=1,2,3...),除法的结果就是k。自然地我们想知道数值位于该区间的元素多少?我们发现数组元素的数值大小的上限是100000,联想到桶排序,我们只需预处理nums,将每个元素的频次统计在桶计数器count里。这样,如果想知道位于某个数值范围[l,r]内的nums元素共有多少个,只需要用count的前缀和相减即可,这里记做presum[r]-presum[l-1]。 -综上,对于x,我们从小到大遍历所有的k。```c = presum[x*(k+1)-1] - presum[x*k-1]```代表了有多少元素与x的商恰好是k,最终答案就可以加上```c*k```. 特别注意,k的遍历的上界可能会使得```x*(k+1)-1```超过100000(桶的个数)。所以最后一段区间是一个“零头”,需要单独处理```[x*k, 100000]```。 +最终的解法是:对于x,我们从小到大遍历所有的k。令```c = presum[x*(k+1)-1] - presum[x*k-1]```代表了有多少元素与x的商恰好是k,那么最终答案就可以加上```c*k```. 特别注意,k的遍历的上界可能会使得```x*(k+1)-1```超过100000(桶的个数)。所以最后一段区间是一个“零头”,需要单独处理```[x*k, 100000]```。 + +此外本题比较有趣的是对时间复杂度的分析。对于一个元素x,我们需要遍历的区间个数就是10^5/x个。本题最坏的情况是,所有的元素都不一样(x=1,2,3...),那么我们就没有任何可以重复利用的信息,那么最坏需要遍历的总次数就是```10^5/1 + 10^5/2 + 10^5/3 ... ```,即```N * (1/1 + 1/2 + 1/3 + ... 1/N)```。后半部分是注明的调和级数,它是发散的,但是有渐近线,趋向于log(N),证明见[这里](https://leetcode-cn.com/problems/sum-of-floored-pairs/solution/diao-he-ji-shu-de-shi-jian-fu-za-du-zhen-kf8j/)。所以总的额时间复杂度就是o(NlogN). From ca1ba142fe6f75d93b5c9111f8af4e33957843e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Apr 2022 20:32:20 -0700 Subject: [PATCH 0662/2729] Update Readme.md --- Others/1862.Sum-of-Floored-Pairs/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/1862.Sum-of-Floored-Pairs/Readme.md b/Others/1862.Sum-of-Floored-Pairs/Readme.md index 1244d1ef2..6a206942a 100644 --- a/Others/1862.Sum-of-Floored-Pairs/Readme.md +++ b/Others/1862.Sum-of-Floored-Pairs/Readme.md @@ -6,4 +6,4 @@ 最终的解法是:对于x,我们从小到大遍历所有的k。令```c = presum[x*(k+1)-1] - presum[x*k-1]```代表了有多少元素与x的商恰好是k,那么最终答案就可以加上```c*k```. 特别注意,k的遍历的上界可能会使得```x*(k+1)-1```超过100000(桶的个数)。所以最后一段区间是一个“零头”,需要单独处理```[x*k, 100000]```。 -此外本题比较有趣的是对时间复杂度的分析。对于一个元素x,我们需要遍历的区间个数就是10^5/x个。本题最坏的情况是,所有的元素都不一样(x=1,2,3...),那么我们就没有任何可以重复利用的信息,那么最坏需要遍历的总次数就是```10^5/1 + 10^5/2 + 10^5/3 ... ```,即```N * (1/1 + 1/2 + 1/3 + ... 1/N)```。后半部分是注明的调和级数,它是发散的,但是有渐近线,趋向于log(N),证明见[这里](https://leetcode-cn.com/problems/sum-of-floored-pairs/solution/diao-he-ji-shu-de-shi-jian-fu-za-du-zhen-kf8j/)。所以总的额时间复杂度就是o(NlogN). +此外本题比较有趣的是对时间复杂度的分析。对于一个元素x,我们需要遍历的区间个数就是10^5/x个。本题最坏的情况是,所有的元素都不一样(x=1,2,3...),那么我们就没有任何可以重复利用的信息,那么最坏需要遍历的总次数就是```10^5/1 + 10^5/2 + 10^5/3 ... ```,即```10^5 * (1/1 + 1/2 + 1/3 + ... 1/N)```。后半部分是注明的调和级数,它是发散的,但是有渐近线,趋向于log(N),证明见[这里](https://leetcode-cn.com/problems/sum-of-floored-pairs/solution/diao-he-ji-shu-de-shi-jian-fu-za-du-zhen-kf8j/)。所以总的额时间复杂度就是```o(10^5*logN)```. From dd4cd73bc232c6e8dd719594717bf15b8c6cc6f3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Apr 2022 15:07:30 -0700 Subject: [PATCH 0663/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9f1c75876..dbceb08a6 100644 --- a/Readme.md +++ b/Readme.md @@ -89,7 +89,6 @@ [1011.Capacity-To-Ship-Packages-Within-D-Days](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1011.Capacity-To-Ship-Packages-Within-D-Days) (M) [1060.Missing-Element-in-Sorted-Array](https://github.com/wisdompeak/LeetCode/blob/master/Binary_Search/1060.Missing-Element-in-Sorted-Array) (H) [1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) -[1201.Ugly-Number-III](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1201.Ugly-Number-III) (H-) [1231.Divide-Chocolate](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1231.Divide-Chocolate) (M) [1283.Find-the-Smallest-Divisor-Given-a-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1283.Find-the-Smallest-Divisor-Given-a-Threshold) (M) [1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold) (H-) @@ -121,6 +120,7 @@ [1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows) (H) [786.Kth-Smallest-Prime-Fraction](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/786.K-th%20Smallest-Prime-Fraction) (H-) [793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) +[1201.Ugly-Number-III](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1201.Ugly-Number-III) (H-) [1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) From e2b236236b316a7a7f84deb16fc970a72eb7fe04 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Apr 2022 22:36:05 -0700 Subject: [PATCH 0664/2729] Create 2251.Number-of-Flowers-in-Full-Bloom.cpp --- .../2251.Number-of-Flowers-in-Full-Bloom.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Others/2251.Number-of-Flowers-in-Full-Bloom/2251.Number-of-Flowers-in-Full-Bloom.cpp diff --git a/Others/2251.Number-of-Flowers-in-Full-Bloom/2251.Number-of-Flowers-in-Full-Bloom.cpp b/Others/2251.Number-of-Flowers-in-Full-Bloom/2251.Number-of-Flowers-in-Full-Bloom.cpp new file mode 100644 index 000000000..c94044955 --- /dev/null +++ b/Others/2251.Number-of-Flowers-in-Full-Bloom/2251.Number-of-Flowers-in-Full-Bloom.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + vector fullBloomFlowers(vector>& flowers, vector& persons) + { + unordered_mapMap; + for (auto x: flowers) + { + Map[x[0]]+=1; + Map[x[1]+1]-=1; + } + vector>diff(Map.begin(), Map.end()); + sort(diff.begin(), diff.end()); + + vector>p; + for (int i=0; irets(persons.size()); + for (int i=0; i Date: Mon, 25 Apr 2022 22:46:50 -0700 Subject: [PATCH 0665/2729] Create Readme.md --- Others/2251.Number-of-Flowers-in-Full-Bloom/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2251.Number-of-Flowers-in-Full-Bloom/Readme.md diff --git a/Others/2251.Number-of-Flowers-in-Full-Bloom/Readme.md b/Others/2251.Number-of-Flowers-in-Full-Bloom/Readme.md new file mode 100644 index 000000000..7fb017412 --- /dev/null +++ b/Others/2251.Number-of-Flowers-in-Full-Bloom/Readme.md @@ -0,0 +1,5 @@ +### 2251.Number-of-Flowers-in-Full-Bloom + +非常明显的差分数组。因为flowers的数值范围非常大,假如某朵花从第1天开到1e9天,我们不可能对于其中每一天都做标记。所以我们只需要在第1天标记“从此多开一朵花”,在第1e9+1天标记“从此少开一朵花”即可。也就是说,我们只需要关注每个开花区间的第一天和最后一天,就掌握整个区间的信息。 + +据此我们可以将差分数组建立起来:diff[i]表示第i天比之前多开多少花,注意这可以是正数,也可以是负数。然后就是双指针,我们把persons按照时间遍历,相应地diff数组也单调地遍历。如果某人是在第i天来看花,那么我们就将第i天及其之前的差分信息都累加起来,就得到这个人能够看到的花的总数了。 From 90e02473042756de397668204ad9d474f5af118e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Apr 2022 22:47:21 -0700 Subject: [PATCH 0666/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index dbceb08a6..121ba15e4 100644 --- a/Readme.md +++ b/Readme.md @@ -1216,6 +1216,7 @@ [1943.Describe-the-Painting](https://github.com/wisdompeak/LeetCode/tree/master/Others/1943.Describe-the-Painting) (H-) [2015.Average-Height-of-Buildings-in-Each-Segment](https://github.com/wisdompeak/LeetCode/tree/master/Others/2015.Average-Height-of-Buildings-in-Each-Segment) (H-) [2158.Amount-of-New-Area-Painted-Each-Day](https://github.com/wisdompeak/LeetCode/tree/master/Others/2158.Amount-of-New-Area-Painted-Each-Day) (H-) +[2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From d122b9052334b9a054a1ea591026e12a2d753955 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Apr 2022 23:50:54 -0700 Subject: [PATCH 0667/2729] Create 2250.Count-Number-of-Rectangles-Containing-Each-Point.cpp --- ...er-of-Rectangles-Containing-Each-Point.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point/2250.Count-Number-of-Rectangles-Containing-Each-Point.cpp diff --git a/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point/2250.Count-Number-of-Rectangles-Containing-Each-Point.cpp b/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point/2250.Count-Number-of-Rectangles-Containing-Each-Point.cpp new file mode 100644 index 000000000..b78c701ba --- /dev/null +++ b/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point/2250.Count-Number-of-Rectangles-Containing-Each-Point.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector countRectangles(vector>& rectangles, vector>& points) + { + sort(rectangles.begin(), rectangles.end()); + for (int i=0; icount(101); + vectorrets(points.size()); + for (int i=points.size()-1; i>=0; i--) + { + while (j>=0 && rectangles[j][0]>=points[i][0]) + { + count[rectangles[j][1]]++; + j--; + } + int total = 0; + for (int h=100; h>=points[i][1]; h--) + total+=count[h]; + rets[points[i][2]] = total; + } + + return rets; + } +}; From e2ab71b3a0d11921892a215e1439f561cc0c368b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Apr 2022 23:51:28 -0700 Subject: [PATCH 0668/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 121ba15e4..59afe4b12 100644 --- a/Readme.md +++ b/Readme.md @@ -1115,6 +1115,7 @@ [1665.Minimum-Initial-Energy-to-Finish-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1665.Minimum-Initial-Energy-to-Finish-Tasks) (H-) [1686.Stone-Game-VI](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1686.Stone-Game-VI) (H-) [1996.The-Number-of-Weak-Characters-in-the-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1996.The-Number-of-Weak-Characters-in-the-Game) (M+) +[2250.Count-Number-of-Rectangles-Containing-Each-Point](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point) (H-) * ``Indexing Sort`` [041.First-Missing-Positive](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/041.First-Missing-Positive/Readme.md) (H) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From a64e881e8d43af00f7be95cf8657a27a8bfeb891 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Apr 2022 00:39:05 -0700 Subject: [PATCH 0669/2729] Update Readme.md --- Greedy/1402.Reducing-Dishes/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Greedy/1402.Reducing-Dishes/Readme.md b/Greedy/1402.Reducing-Dishes/Readme.md index 020065bf9..31e5ede88 100644 --- a/Greedy/1402.Reducing-Dishes/Readme.md +++ b/Greedy/1402.Reducing-Dishes/Readme.md @@ -1,7 +1,7 @@ ### 1402.Reducing-Dishes -两个突破点。首先我们肯定会把dishes按照满意度排序,满意度高的肯定放在后面做。其次,我们肯定会取若干个满意度最高的,关键就是取多少个而已。 +两个突破点。首先我们肯定会把dishes按照满意度排序,满意度高的肯定放在后面做。其次,在选取相同数目的dishe的前提下,我们肯定会取满意度最高的若干个。于是答案的本质就是选多少dishes。 -于是我们就是要尝试取最高的1个,或者2个,或者3个,...,直至n个满意度最高的dishes,计算最后总得分,取最大值。 +于是我们就是要尝试取最高的1个,或者2个,或者3个...,直至n个满意度最高的dishes,计算最后总得分,取最大值。 -根据计算公式,显然每增加一道菜(按照满意度从高到底是第i个),总得分total就会增加的分值就是前i个菜的presum。 +这里有个化简计算的方法。我们将dishe按照满意度从高到低排列。如果取一个,答案是```satisfaction[0]```;如果取两个,答案是```2*satisfaction[0] + satisfaction[1]```;如果取三个,答案是```3*satisfaction[0] + 2*satisfaction[1] + satisfaction[2]```。可见答案每次都在前者的基础上增加```presum[i]```,其中presum是satisfaction的前缀和。 From 2b9e1520ab790158580c86e9c958480209ddf86a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Apr 2022 01:03:19 -0700 Subject: [PATCH 0670/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point/Readme.md diff --git a/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point/Readme.md b/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point/Readme.md new file mode 100644 index 000000000..21befe316 --- /dev/null +++ b/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point/Readme.md @@ -0,0 +1,9 @@ +### 2250.Count-Number-of-Rectangles-Containing-Each-Point + +对于矩阵而言,它有宽和高两个属性。和1996类似的思想,我们必然会将其中一个属性排序,方便我们定位,然后再解决另一个属性。 + +如果我们将所有的矩阵按照宽度排序之后,对于任何一个点P(x,y),我们就可以很容易定位到哪些矩阵在宽度方向是可以包括该点的(也就是所有宽度大于等于y的矩阵),我们把这些矩阵放入一个pool中。但是在高度方向上,pool里面的这些矩阵的高度值是参差不齐的,无法快速定位有多少矩阵的高度大于等y。有人会说把这些矩阵的高度值放入一个有序的容器中,但是常规的红黑树虽然支持二分定位这些高度值里第一个大于等于y的位置,但是它无法告诉大于等于y的值总共有多少个。 + +此时最关键的地方就是题目给的数据范围。我们发现矩阵的高度值的范围只有100,因此我们将1到100每个刻度作为buckets来处理,即每个bucket存储有多少个对应高度值的矩阵。于是只需要最多遍历100次,就可以知道pool里矩阵的高度值有多少是大于等于y的了。 + +综上,我们按照横坐标从大到小处理每个点。对于任意一个点(x,y),我们就可以把若干个符合宽度条件x>=x的矩形加入pool中,统计高度值的分布。再遍历100次,计算有多少高度值是大于等于y的。所以总的时间复杂度就是```o(rectangles)*100```. From abc59e987c181ff390b64b5467685452180d6c52 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Apr 2022 00:09:48 -0700 Subject: [PATCH 0671/2729] Create 2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp --- ...istance-to-a-Cycle-in-Undirected-Graph.cpp | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp diff --git a/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp b/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp new file mode 100644 index 000000000..a990c4739 --- /dev/null +++ b/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp @@ -0,0 +1,61 @@ +class Solution { +public: + vector distanceToCycle(int n, vector>& edges) + { + vectordegree(n); + vector>next(n); + for (auto edge: edges) + { + int a = edge[0], b = edge[1]; + degree[a]++; + degree[b]++; + next[a].push_back(b); + next[b].push_back(a); + } + + vectorrets(n); + queueq; + for (int i=0; i Date: Wed, 27 Apr 2022 00:10:23 -0700 Subject: [PATCH 0672/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 59afe4b12..4ad0644e4 100644 --- a/Readme.md +++ b/Readme.md @@ -499,6 +499,7 @@ [2115.Find-All-Possible-Recipes-from-Given-Supplies](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies) (M) [2127.Maximum-Employees-to-Be-Invited-to-a-Meeting](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting) (H) [2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph) (M) +[2204.Distance-to-a-Cycle-in-Undirected-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph) (M) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From 1afd8b5a00adf0e85e692ce891b39728c075b217 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Apr 2022 00:14:10 -0700 Subject: [PATCH 0673/2729] Create Readme.md --- BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/Readme.md diff --git a/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/Readme.md b/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/Readme.md new file mode 100644 index 000000000..e56ca5525 --- /dev/null +++ b/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/Readme.md @@ -0,0 +1,5 @@ +### 2204.Distance-to-a-Cycle-in-Undirected-Graph + +常规的拓扑排序。我们首先将所有度为1的点放入队列,按照层级遍历的顺序BFS:每弹出一个节点A,就考察其邻接节点并将度减去1,如果邻接节点度降为了1,就将其加入队列。持续BFS直至队列为空。 + +此时所有未曾访问的点都一定是在环上。我们再将这些点作为初始点放入队列中,重新开始BFS,就可以得到所有非环节点距离环的最短距离。 From b75b3c7fafd1f71f32ec6f54c746fd6aae85d9c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Apr 2022 00:41:05 -0700 Subject: [PATCH 0674/2729] Create 2246.Longest-Path-With-Different-Adjacent-Characters.cpp --- ...ath-With-Different-Adjacent-Characters.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Tree/2246.Longest-Path-With-Different-Adjacent-Characters/2246.Longest-Path-With-Different-Adjacent-Characters.cpp diff --git a/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/2246.Longest-Path-With-Different-Adjacent-Characters.cpp b/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/2246.Longest-Path-With-Different-Adjacent-Characters.cpp new file mode 100644 index 000000000..fb0f239a6 --- /dev/null +++ b/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/2246.Longest-Path-With-Different-Adjacent-Characters.cpp @@ -0,0 +1,53 @@ +class Solution { + vector children[100000]; + int len[100000]; + int globalRet = 1; + string s; +public: + int longestPath(vector& parent, string s) + { + int n = parent.size(); + this->s = s; + + for (int i=0; itemp; + for (int child: children[node]) + { + dfs(child); + if (s[child]!=s[node]) + { + ret = max(ret, len[child]+1); + temp.push_back(len[child]); + } + } + + sort(temp.rbegin(), temp.rend()); + if (temp.size()>=2) + globalRet = max(globalRet, temp[0]+temp[1]+1); + else if (temp.size()==1) + globalRet = max(globalRet, temp[0]+1); + else + globalRet = max(globalRet, 1); + + len[node] = ret; + } +}; From 93e510c5b4956d7ab51d472cb2c17c1d12e4f2c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Apr 2022 00:41:33 -0700 Subject: [PATCH 0675/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4ad0644e4..08a0e2ba4 100644 --- a/Readme.md +++ b/Readme.md @@ -232,6 +232,7 @@ [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) [687.Longest-Univalue-Path](https://github.com/wisdompeak/LeetCode/tree/master/Tree/687.Longest-Univalue-Path) (M+) [2049.Count-Nodes-With-the-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2049.Count-Nodes-With-the-Highest-Score) (M+) +[2246.Longest-Path-With-Different-Adjacent-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2246.Longest-Path-With-Different-Adjacent-Characters) (M+) * ``Serialization & Hashing`` [297.Serialize-and-Deserialize-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/297.Serialize-and-Deserialize-Binary-Tree) (H-) [652.Find-Duplicate-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/652.Find-Duplicate-Subtrees) (H) From 08606c2f43cdbaa3bbf224a084e4054c252fe1af Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Apr 2022 00:55:52 -0700 Subject: [PATCH 0676/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Tree/2246.Longest-Path-With-Different-Adjacent-Characters/Readme.md diff --git a/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/Readme.md b/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/Readme.md new file mode 100644 index 000000000..564482808 --- /dev/null +++ b/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/Readme.md @@ -0,0 +1,9 @@ +### 2246.Longest-Path-With-Different-Adjacent-Characters + +这是一道非常典型的rooted-tree内的路径问题。在给定root的树型图里,任何路径都必然有一个拐点,我们遍历所有的节点,考虑对每个节点作为拐点时的最优路径,这样我们就可以做到不遗漏地求出全局的最优路径。 + +对于本题而言,以Node为拐点的最长路径,必然由两条以它孩子节点为起点的最长单链路径(即一直向下没有拐弯)拼接组成。所以本题的核心就转化为,求对于每个节点,从它往下走能够找到的最长单链路径h。很显然这个函数具有递归性质: +``` +h(node) = h(node->child) +1 (if node is different from its child), otherwise 1 +``` +有了h之后,考虑每个节点作为拐点时,能否找到两个可以与自己拼接起来的最长单链即可。在全局中找最优解。 From aba19c9b51fe6731a34f267763a086dd9b092ea1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Apr 2022 00:56:51 -0700 Subject: [PATCH 0677/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/Readme.md b/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/Readme.md index 564482808..830ee9262 100644 --- a/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/Readme.md +++ b/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/Readme.md @@ -6,4 +6,4 @@ ``` h(node) = h(node->child) +1 (if node is different from its child), otherwise 1 ``` -有了h之后,考虑每个节点作为拐点时,能否找到两个可以与自己拼接起来的最长单链即可。在全局中找最优解。 +有了h之后,考虑每个节点作为拐点时,转化为能否找到两个可以与自己拼接起来的、孩子的最长单链即可。在全局中找最优解。 From 3c915946d951d5d54a2d1a0820816d15580c3d24 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Apr 2022 01:02:26 -0700 Subject: [PATCH 0678/2729] Update 2246.Longest-Path-With-Different-Adjacent-Characters.cpp --- .../2246.Longest-Path-With-Different-Adjacent-Characters.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/2246.Longest-Path-With-Different-Adjacent-Characters.cpp b/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/2246.Longest-Path-With-Different-Adjacent-Characters.cpp index fb0f239a6..961ba5cab 100644 --- a/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/2246.Longest-Path-With-Different-Adjacent-Characters.cpp +++ b/Tree/2246.Longest-Path-With-Different-Adjacent-Characters/2246.Longest-Path-With-Different-Adjacent-Characters.cpp @@ -39,6 +39,7 @@ class Solution { temp.push_back(len[child]); } } + len[node] = ret; sort(temp.rbegin(), temp.rend()); if (temp.size()>=2) @@ -46,8 +47,6 @@ class Solution { else if (temp.size()==1) globalRet = max(globalRet, temp[0]+1); else - globalRet = max(globalRet, 1); - - len[node] = ret; + globalRet = max(globalRet, 1); } }; From 0a870fe39e50fda12b3442d8316af069088149a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 00:01:15 -0700 Subject: [PATCH 0679/2729] Create 1522.Diameter-of-N-Ary-Tree.cpp --- .../1522.Diameter-of-N-Ary-Tree.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Tree/1522.Diameter-of-N-Ary-Tree/1522.Diameter-of-N-Ary-Tree.cpp diff --git a/Tree/1522.Diameter-of-N-Ary-Tree/1522.Diameter-of-N-Ary-Tree.cpp b/Tree/1522.Diameter-of-N-Ary-Tree/1522.Diameter-of-N-Ary-Tree.cpp new file mode 100644 index 000000000..812245a6d --- /dev/null +++ b/Tree/1522.Diameter-of-N-Ary-Tree/1522.Diameter-of-N-Ary-Tree.cpp @@ -0,0 +1,56 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + int ret = 0; +public: + int diameter(Node* root) + { + DFS(root); + return ret-1; + } + + int DFS(Node* node) + { + if (node==NULL) return 0; + vectordepths; + for (auto child: node->children) + depths.push_back(DFS(child)); + sort(depths.rbegin(), depths.rend()); + + int n = depths.size(); + if (n>=2) + { + ret = max(ret, depths[0]+depths[1]+1); + return depths.back()+1; + } + else if (n==1) + { + ret = max(ret, depths[0]+1); + return depths.back()+1; + } + else + { + ret = max(ret, 1); + return 1; + } + + } +}; From be897d4b1dcd0c06bf5ceb815064501077d01500 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 00:01:41 -0700 Subject: [PATCH 0680/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 08a0e2ba4..a4bab5e8c 100644 --- a/Readme.md +++ b/Readme.md @@ -231,6 +231,7 @@ [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) [687.Longest-Univalue-Path](https://github.com/wisdompeak/LeetCode/tree/master/Tree/687.Longest-Univalue-Path) (M+) +[1522.Diameter-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1522.Diameter-of-N-Ary-Tree) (M) [2049.Count-Nodes-With-the-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2049.Count-Nodes-With-the-Highest-Score) (M+) [2246.Longest-Path-With-Different-Adjacent-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2246.Longest-Path-With-Different-Adjacent-Characters) (M+) * ``Serialization & Hashing`` From 6b8e037c8ff1a1be5755a4f755a39a8ba88703a3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 00:35:48 -0700 Subject: [PATCH 0681/2729] Create Readme.md --- Tree/1522.Diameter-of-N-Ary-Tree/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Tree/1522.Diameter-of-N-Ary-Tree/Readme.md diff --git a/Tree/1522.Diameter-of-N-Ary-Tree/Readme.md b/Tree/1522.Diameter-of-N-Ary-Tree/Readme.md new file mode 100644 index 000000000..01832c971 --- /dev/null +++ b/Tree/1522.Diameter-of-N-Ary-Tree/Readme.md @@ -0,0 +1,7 @@ +### 1522.Diameter-of-N-Ary-Tree + +本题和```543.Diameter-of-Binary-Tree```一样的思路。在rooted-tree里,任何路径都一定有一个最高的拐点,往左是一条以某个孩子为起点的单链,往右是另一条以某个孩子为起点单链(所谓单链就是一路向下奔向叶子节点、不带拐弯的路径)。显然,我们会取所有孩子节点里最长的两条单链。 + +所以本题的本质就是求以任意节点node为起点的最长单链长度```h(node)```。显然有递推关系:```h(node) = max{h(node->child)}+1```. + +对于任意节点node,我们会找它孩子节点中最长的两条单链,再加1,就是以node为拐点的最长路径。全局的最长路径就是最终答案。 From 4256381d5933a5ce2581a7b78416844f14709c6d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 22:10:48 -0700 Subject: [PATCH 0682/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a4bab5e8c..30805e3d4 100644 --- a/Readme.md +++ b/Readme.md @@ -179,6 +179,7 @@ [1675.Minimize-Deviation-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1675.Minimize-Deviation-in-Array) (H) [1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers) (M) 1348.Tweet-Counts-Per-Frequency (H-) +[1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1488.Avoid-Flood-in-The-City) (H-) [1606.Find-Servers-That-Handled-Most-Number-of-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests) (M) 1797.Design Authentication Manager (M) [1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1825.Finding-MK-Average) (H) @@ -1047,7 +1048,6 @@ [1253.Reconstruct-a-2-Row-Binary-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1253.Reconstruct-a-2-Row-Binary-Matrix) (M) [1354.Construct-Target-Array-With-Multiple-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1354.Construct-Target-Array-With-Multiple-Sums) (H-) [1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K) (M+) -[1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1488.Avoid-Flood-in-The-City) (H-) [1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits) (H) [1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1535.Find-the-Winner-of-an-Array-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1535.Find-the-Winner-of-an-Array-Game) (M+) From 46c95b595dd4b9356d47c3719b1f75647e343c8f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 22:11:59 -0700 Subject: [PATCH 0683/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 30805e3d4..efdc96eb1 100644 --- a/Readme.md +++ b/Readme.md @@ -1181,7 +1181,7 @@ 825.Friends-Of-Appropriate-Ages (M+) [835.Image-Overlap](https://github.com/wisdompeak/LeetCode/tree/master/Others/835.Image-Overlap) (H) [843.Guess-the-Word](https://github.com/wisdompeak/LeetCode/tree/master/Others/843.Guess-the-Word) (M) -855.Exam-Room (M+) +[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Others/855.Exam-Room) (M+) 918.Maximum-Sum-Circular-Subarray (H-) [927.Three-Equal-Parts](https://github.com/wisdompeak/LeetCode/tree/master/Others/927.Three-Equal-Parts) (M) [978.Longest-Turbulent-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Others/978.Longest-Turbulent-Subarray) (H-) From b9bd31b953e83a918fd6d0284a519c978c70611a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 23:07:37 -0700 Subject: [PATCH 0684/2729] Create 855.Exam-Room_v2.cpp --- Others/855.Exam-Room/855.Exam-Room_v2.cpp | 56 +++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Others/855.Exam-Room/855.Exam-Room_v2.cpp diff --git a/Others/855.Exam-Room/855.Exam-Room_v2.cpp b/Others/855.Exam-Room/855.Exam-Room_v2.cpp new file mode 100644 index 000000000..423082783 --- /dev/null +++ b/Others/855.Exam-Room/855.Exam-Room_v2.cpp @@ -0,0 +1,56 @@ +class ExamRoom { + int N; + vectorL; +public: + ExamRoom(int N) + { + this->N = N; + } + + int seat() + { + if (L.size()==0) + { + L.push_back(0); + return 0; + } + + int maxGap = -1; + int pos; + + if (L[0]!=0) + { + pos = 0; + maxGap = L[0]-1; + } + for (int i=0; i maxGap) + { + maxGap = (L[i+1]-L[i]-2)/2 ; + pos = L[i]+maxGap+1; + } + } + if (L.back()!=N-1 && N-1-L.back()-1>maxGap) + { + maxGap = N-1-L.back()-1; + pos = N-1; + } + + L.insert(lower_bound(L.begin(),L.end(),pos), pos); + + return pos; + } + + void leave(int p) + { + L.erase(lower_bound(L.begin(),L.end(),p)); + } +}; + +/** + * Your ExamRoom object will be instantiated and called as such: + * ExamRoom obj = new ExamRoom(N); + * int param_1 = obj.seat(); + * obj.leave(p); + */ From 7737a12fbaef2eb220b628384abf77eea0cd0284 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 23:08:52 -0700 Subject: [PATCH 0685/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index efdc96eb1..33dd1cf49 100644 --- a/Readme.md +++ b/Readme.md @@ -174,6 +174,7 @@ [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [729.My-Calendar-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/729.My-Calendar-I) (M) +[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Others/855.Exam-Room) (M+) [975.Odd-Even-Jump](https://github.com/wisdompeak/LeetCode/tree/master/Heap/975.Odd-Even-Jump) (H-) [632.Smallest-Range-Covering-Elements-from-K-Lists](https://github.com/wisdompeak/LeetCode/tree/master/Heap/632.Smallest-Range-Covering-Elements-from-K-Lists) (H-) [1675.Minimize-Deviation-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1675.Minimize-Deviation-in-Array) (H) @@ -1181,7 +1182,6 @@ 825.Friends-Of-Appropriate-Ages (M+) [835.Image-Overlap](https://github.com/wisdompeak/LeetCode/tree/master/Others/835.Image-Overlap) (H) [843.Guess-the-Word](https://github.com/wisdompeak/LeetCode/tree/master/Others/843.Guess-the-Word) (M) -[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Others/855.Exam-Room) (M+) 918.Maximum-Sum-Circular-Subarray (H-) [927.Three-Equal-Parts](https://github.com/wisdompeak/LeetCode/tree/master/Others/927.Three-Equal-Parts) (M) [978.Longest-Turbulent-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Others/978.Longest-Turbulent-Subarray) (H-) From 8a43bdec2588c6eba026ceffc5f86e69def28e8c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 23:18:05 -0700 Subject: [PATCH 0686/2729] Delete 855.Exam-Room.cpp --- Others/855.Exam-Room/855.Exam-Room.cpp | 56 -------------------------- 1 file changed, 56 deletions(-) delete mode 100644 Others/855.Exam-Room/855.Exam-Room.cpp diff --git a/Others/855.Exam-Room/855.Exam-Room.cpp b/Others/855.Exam-Room/855.Exam-Room.cpp deleted file mode 100644 index 423082783..000000000 --- a/Others/855.Exam-Room/855.Exam-Room.cpp +++ /dev/null @@ -1,56 +0,0 @@ -class ExamRoom { - int N; - vectorL; -public: - ExamRoom(int N) - { - this->N = N; - } - - int seat() - { - if (L.size()==0) - { - L.push_back(0); - return 0; - } - - int maxGap = -1; - int pos; - - if (L[0]!=0) - { - pos = 0; - maxGap = L[0]-1; - } - for (int i=0; i maxGap) - { - maxGap = (L[i+1]-L[i]-2)/2 ; - pos = L[i]+maxGap+1; - } - } - if (L.back()!=N-1 && N-1-L.back()-1>maxGap) - { - maxGap = N-1-L.back()-1; - pos = N-1; - } - - L.insert(lower_bound(L.begin(),L.end(),pos), pos); - - return pos; - } - - void leave(int p) - { - L.erase(lower_bound(L.begin(),L.end(),p)); - } -}; - -/** - * Your ExamRoom object will be instantiated and called as such: - * ExamRoom obj = new ExamRoom(N); - * int param_1 = obj.seat(); - * obj.leave(p); - */ From 060b65f0e504cdd3a92fa0dcf7855a3cb9bd8172 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 23:18:16 -0700 Subject: [PATCH 0687/2729] Rename 855.Exam-Room_v2.cpp to 855.Exam-Room.cpp --- Others/855.Exam-Room/{855.Exam-Room_v2.cpp => 855.Exam-Room.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Others/855.Exam-Room/{855.Exam-Room_v2.cpp => 855.Exam-Room.cpp} (100%) diff --git a/Others/855.Exam-Room/855.Exam-Room_v2.cpp b/Others/855.Exam-Room/855.Exam-Room.cpp similarity index 100% rename from Others/855.Exam-Room/855.Exam-Room_v2.cpp rename to Others/855.Exam-Room/855.Exam-Room.cpp From 716c9980b38f3a57a0084dd5abcaf76da1f86cc0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 23:25:07 -0700 Subject: [PATCH 0688/2729] Update Readme.md --- Others/855.Exam-Room/Readme.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Others/855.Exam-Room/Readme.md b/Others/855.Exam-Room/Readme.md index 8a69b11cd..977621ad1 100644 --- a/Others/855.Exam-Room/Readme.md +++ b/Others/855.Exam-Room/Readme.md @@ -1,10 +1,13 @@ ### 855.Exam-Room.cpp -此题考虑什么样的数据结构最合适。我们需要存放什么呢?其实只要存放每个人的位置就可以了。人与人的间隔要不要单独存储呢?其实可以不必。线性的数组在这里就足够用了。虽然每次插入位置的搜索是线性的,内存的移动也会费时间,但似乎实际的效率还不错。 +本题比较偷懒的方法就是用有序容器set来盛装所有人的位置。在调用seat()的时候,就用迭代器遍历set的所有元素,查找相邻元素a和b之间的距离```diff=b-a```,那么如果要在这个区间内插入一人,显然只能插在```a+diff/2```这个地方,并且就是```diff/2```. -每次进来一个人,我们线性扫描现有人的位置,查找最大的间隔。另外,头和尾的间隔需要另行考虑。确定最大间隔,就能确定插入的位置,直接用数组的insert命令即可。 +需要特别注意的是如果set里的第一个元素不是0,那么我们可以选择在0位置插入。同理如果set里的最后一个元素不是n-1,那么我们可以选择在n-1位置插入。这两个地方需要单独处理。 -在人离开的时候,也是直接用lower_bound确定位置的迭代器,再删除迭代器即可。 +最终我们选择全局“离最近的人的最远距离”的最优解来安排新人的位置。所以seat()的时间复杂度是o(n). +对于leave(int p),则简单多了,可以直接o(1)从set里删除即可。 -[Leetcode Link](https://leetcode.com/problems/exam-room) \ No newline at end of file +当然本题还有复杂的做法,就是将所有连续的空座区间按照“插入后离最近的人的最远距离”放入优先队列。这样我们可以log(n)的时间实现seat()。但是对于leave(p)的操作,似乎就只能靠o(n)来遍历再删除了。 + +[Leetcode Link](https://leetcode.com/problems/exam-room) From c5b38760a62c2a7a3da51992c1db34eec62b3042 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 23:25:41 -0700 Subject: [PATCH 0689/2729] Update Readme.md --- Others/855.Exam-Room/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/855.Exam-Room/Readme.md b/Others/855.Exam-Room/Readme.md index 977621ad1..d5839f114 100644 --- a/Others/855.Exam-Room/Readme.md +++ b/Others/855.Exam-Room/Readme.md @@ -1,6 +1,6 @@ ### 855.Exam-Room.cpp -本题比较偷懒的方法就是用有序容器set来盛装所有人的位置。在调用seat()的时候,就用迭代器遍历set的所有元素,查找相邻元素a和b之间的距离```diff=b-a```,那么如果要在这个区间内插入一人,显然只能插在```a+diff/2```这个地方,并且就是```diff/2```. +本题比较偷懒的方法就是用有序容器set来盛装所有人的位置。在调用seat()的时候,就用迭代器遍历set的所有元素,查找相邻元素a和b之间的距离```diff=b-a```,那么如果要在这个区间内插入一人,显然只能插在```a+diff/2```这个地方,并且“离最近的人的最远距离”就是```diff/2```. 需要特别注意的是如果set里的第一个元素不是0,那么我们可以选择在0位置插入。同理如果set里的最后一个元素不是n-1,那么我们可以选择在n-1位置插入。这两个地方需要单独处理。 From 46e9334a48e0b11125b6c3156e51da04e05d307b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Apr 2022 23:26:11 -0700 Subject: [PATCH 0690/2729] Update Readme.md --- Others/855.Exam-Room/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Others/855.Exam-Room/Readme.md b/Others/855.Exam-Room/Readme.md index d5839f114..d9e8ea023 100644 --- a/Others/855.Exam-Room/Readme.md +++ b/Others/855.Exam-Room/Readme.md @@ -1,13 +1,13 @@ ### 855.Exam-Room.cpp -本题比较偷懒的方法就是用有序容器set来盛装所有人的位置。在调用seat()的时候,就用迭代器遍历set的所有元素,查找相邻元素a和b之间的距离```diff=b-a```,那么如果要在这个区间内插入一人,显然只能插在```a+diff/2```这个地方,并且“离最近的人的最远距离”就是```diff/2```. +本题比较偷懒的方法就是用有序容器set来盛装所有人的位置。在调用seat()的时候,就用迭代器遍历set的所有元素,查找相邻元素a和b之间的距离```diff=b-a```,那么如果要在这个区间内插入一人,显然只能插在```a+diff/2```这个地方,并且“离相邻人的最远距离”就是```diff/2```. 需要特别注意的是如果set里的第一个元素不是0,那么我们可以选择在0位置插入。同理如果set里的最后一个元素不是n-1,那么我们可以选择在n-1位置插入。这两个地方需要单独处理。 -最终我们选择全局“离最近的人的最远距离”的最优解来安排新人的位置。所以seat()的时间复杂度是o(n). +最终我们选择全局“离相邻人的最远距离”的最优解来安排新人的位置。所以seat()的时间复杂度是o(n). 对于leave(int p),则简单多了,可以直接o(1)从set里删除即可。 -当然本题还有复杂的做法,就是将所有连续的空座区间按照“插入后离最近的人的最远距离”放入优先队列。这样我们可以log(n)的时间实现seat()。但是对于leave(p)的操作,似乎就只能靠o(n)来遍历再删除了。 +当然本题还有复杂的做法,就是将所有连续的空座区间按照“插入后离相邻人的最远距离”放入优先队列。这样我们可以log(n)的时间实现seat()。但是对于leave(p)的操作,似乎就只能靠o(n)来遍历再删除了。 [Leetcode Link](https://leetcode.com/problems/exam-room) From 488875e7eece4ad2b18c02b431fac3646f1bea65 Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Fri, 29 Apr 2022 00:05:43 -0700 Subject: [PATCH 0691/2729] mv 855 1488 to Heap --- .../1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp | 0 {Greedy => Heap}/1488.Avoid-Flood-in-The-City/Readme.md | 0 {Others => Heap}/855.Exam-Room/855.Exam-Room.cpp | 0 {Others => Heap}/855.Exam-Room/Readme.md | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Heap}/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp (100%) rename {Greedy => Heap}/1488.Avoid-Flood-in-The-City/Readme.md (100%) rename {Others => Heap}/855.Exam-Room/855.Exam-Room.cpp (100%) rename {Others => Heap}/855.Exam-Room/Readme.md (100%) diff --git a/Greedy/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp b/Heap/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp similarity index 100% rename from Greedy/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp rename to Heap/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp diff --git a/Greedy/1488.Avoid-Flood-in-The-City/Readme.md b/Heap/1488.Avoid-Flood-in-The-City/Readme.md similarity index 100% rename from Greedy/1488.Avoid-Flood-in-The-City/Readme.md rename to Heap/1488.Avoid-Flood-in-The-City/Readme.md diff --git a/Others/855.Exam-Room/855.Exam-Room.cpp b/Heap/855.Exam-Room/855.Exam-Room.cpp similarity index 100% rename from Others/855.Exam-Room/855.Exam-Room.cpp rename to Heap/855.Exam-Room/855.Exam-Room.cpp diff --git a/Others/855.Exam-Room/Readme.md b/Heap/855.Exam-Room/Readme.md similarity index 100% rename from Others/855.Exam-Room/Readme.md rename to Heap/855.Exam-Room/Readme.md From e281d9ec930092144121a139aa40214dc2b5d5e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 29 Apr 2022 00:06:12 -0700 Subject: [PATCH 0692/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 33dd1cf49..9ff56eb96 100644 --- a/Readme.md +++ b/Readme.md @@ -174,13 +174,13 @@ [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [729.My-Calendar-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/729.My-Calendar-I) (M) -[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Others/855.Exam-Room) (M+) +[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/855.Exam-Room) (M+) [975.Odd-Even-Jump](https://github.com/wisdompeak/LeetCode/tree/master/Heap/975.Odd-Even-Jump) (H-) [632.Smallest-Range-Covering-Elements-from-K-Lists](https://github.com/wisdompeak/LeetCode/tree/master/Heap/632.Smallest-Range-Covering-Elements-from-K-Lists) (H-) [1675.Minimize-Deviation-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1675.Minimize-Deviation-in-Array) (H) [1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers) (M) 1348.Tweet-Counts-Per-Frequency (H-) -[1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1488.Avoid-Flood-in-The-City) (H-) +[1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1488.Avoid-Flood-in-The-City) (H-) [1606.Find-Servers-That-Handled-Most-Number-of-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests) (M) 1797.Design Authentication Manager (M) [1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1825.Finding-MK-Average) (H) From 58d158c2538c6735f831340e018da3ec994205af Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 29 Apr 2022 00:09:29 -0700 Subject: [PATCH 0693/2729] Create 828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp --- ...rs-of-All-Substrings-of-a-Given-String.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp new file mode 100644 index 000000000..558ab78ce --- /dev/null +++ b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp @@ -0,0 +1,26 @@ +class Solution { + long long M = pow(10,9)+7; +public: + int uniqueLetterString(string S) + { + vector>pos(26); + int result=0; + for (int i=0; i1) + { + int k = pos[i].size(); + result+=pos[i][k-1]-pos[i][k-2]; + } + result = result%M; + } + } + return result; + } + +}; From 4eeb94ca549e582d44d9be272633d80186048693 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 29 Apr 2022 00:09:58 -0700 Subject: [PATCH 0694/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9ff56eb96..c291bce4f 100644 --- a/Readme.md +++ b/Readme.md @@ -141,6 +141,7 @@ [446.Arithmetic-Slices-II-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Hash/446.Arithmetic-Slices-II-Subsequence) (H) [128.Longest-Consecutive-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/128.Longest-Consecutive-Sequence) (H-) [753.Cracking-the-Safe](https://github.com/wisdompeak/LeetCode/tree/master/Hash/753.Cracking-the-Safe) (H) +[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [890.Find-and-Replace-Pattern](https://github.com/wisdompeak/LeetCode/tree/master/Hash/890.Find-and-Replace-Pattern) (M+) [939.Minimum-Area-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Hash/939.Minimum-Area-Rectangle) (M+) 982.Triples-with-Bitwise-AND-Equal-To-Zero (M+) (TBD) From 065f41575db196ea73a30f715edcbe98298abc8c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 29 Apr 2022 00:37:17 -0700 Subject: [PATCH 0695/2729] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md new file mode 100644 index 000000000..1c214794f --- /dev/null +++ b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md @@ -0,0 +1,14 @@ +828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String + +暴力的方法是枚举substring,然后考察这个区间里的字符哪些是unique的。这需要大致```o(N^2*26)```的复杂度。聪明的方法是考察每个字符,它可能在哪些substring里是unique的。 + +我们逐一遍历每个字符,现在考虑以i为结尾的各种substring。假设字符A在i之前最近两次出现的位置分别是a和b,如下图 +``` +X X X X A X X [A X X i] + a b +``` +显然,形如[a+1:i], [a+2:i], ... [b:i]这些substring(总共b-a个)里面只出现过一次A,也就是说对于这些substring而言,A给它们的countUniqueChars都贡献了一分。我们可以直接将b-a分加入到全局的答案中。而以其他任何位置作为起点的substring,A都无法给countUniqueChars贡献分数了。 + +同理,我们可以考察字符B,C,...他们对以i结尾的substring的贡献,将这些分数直接加入总分里面。 + +综上,每考察一个位置i,我们遍历26个字母(即A-Z)在i之前出现的最后两个位置,可以计算它们各自可以给多少substring贡献UniqueChars。总的时间复杂度是o(26N)。 From 179b08a406d5f4ed0206f942b6a11499a8b31dd3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 29 Apr 2022 22:31:03 -0700 Subject: [PATCH 0696/2729] Update 1522.Diameter-of-N-Ary-Tree.cpp --- .../1522.Diameter-of-N-Ary-Tree.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tree/1522.Diameter-of-N-Ary-Tree/1522.Diameter-of-N-Ary-Tree.cpp b/Tree/1522.Diameter-of-N-Ary-Tree/1522.Diameter-of-N-Ary-Tree.cpp index 812245a6d..b965af975 100644 --- a/Tree/1522.Diameter-of-N-Ary-Tree/1522.Diameter-of-N-Ary-Tree.cpp +++ b/Tree/1522.Diameter-of-N-Ary-Tree/1522.Diameter-of-N-Ary-Tree.cpp @@ -39,12 +39,12 @@ class Solution { if (n>=2) { ret = max(ret, depths[0]+depths[1]+1); - return depths.back()+1; + return depths[0]+1; } else if (n==1) { ret = max(ret, depths[0]+1); - return depths.back()+1; + return depths[0]+1; } else { From c4cfff0eb5d66fc585638e5ad171df993dcf8983 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 29 Apr 2022 22:53:04 -0700 Subject: [PATCH 0697/2729] Update Readme.md --- Linked_List/061.Rotate-List/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Linked_List/061.Rotate-List/Readme.md b/Linked_List/061.Rotate-List/Readme.md index 516c251db..9e67cfdc0 100644 --- a/Linked_List/061.Rotate-List/Readme.md +++ b/Linked_List/061.Rotate-List/Readme.md @@ -3,7 +3,7 @@ 1. 确定链表的总长度Len,注意如果Len==0时的处理(此时可以顺便记录末尾节点end) 2. 确定实际需要旋转的次数 k=k%Len -3. 令p从头指针前进 Len-k+1 步,就到了断开链表的位置。 +3. 令p从头指针前进 Len-k-1 步,就到了断开链表的位置。 4. 将p->next作为新的head,原本的end之后指向原本的head,再把p的next指向NULL, [Leetcode Link](https://leetcode.com/problems/rotate-list) From ab00bd50ee8d00cc3cfdfb9bcb0b77894a299958 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 29 Apr 2022 23:13:28 -0700 Subject: [PATCH 0698/2729] Create 2245.Maximum-Trailing-Zeros-in-a-Cornered-Path.cpp --- ...imum-Trailing-Zeros-in-a-Cornered-Path.cpp | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path.cpp diff --git a/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path.cpp b/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path.cpp new file mode 100644 index 000000000..aec2ac4d6 --- /dev/null +++ b/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path.cpp @@ -0,0 +1,77 @@ +class Solution { +public: + int maxTrailingZeros(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + + vector>grid2(m, vector(n)); + vector>grid5(m, vector(n)); + + for (int i=0; i>left2(m, vector(n)); + vector>right2(m, vector(n)); + vector>up2(m, vector(n)); + vector>down2(m, vector(n)); + vector>left5(m, vector(n)); + vector>right5(m, vector(n)); + vector>up5(m, vector(n)); + vector>down5(m, vector(n)); + + for (int i=0; i=0; j--) + { + right2[i][j] = (j==n-1?0:right2[i][j+1]) + grid2[i][j]; + right5[i][j] = (j==n-1?0:right5[i][j+1]) + grid5[i][j]; + } + } + + for (int j=0; j=0; i--) + { + down2[i][j] = (i==m-1?0:down2[i+1][j]) + grid2[i][j]; + down5[i][j] = (i==m-1?0:down5[i+1][j]) + grid5[i][j]; + } + } + + int ret = 0; + for (int i=0; i Date: Fri, 29 Apr 2022 23:13:56 -0700 Subject: [PATCH 0699/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c291bce4f..22c8384f3 100644 --- a/Readme.md +++ b/Readme.md @@ -1238,6 +1238,7 @@ * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) +[2245.Maximum-Trailing-Zeros-in-a-Cornered-Path](https://github.com/wisdompeak/LeetCode/tree/master/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path) (M) * ``2D Presum`` 1314.Matrix-Block-Sum (M) [1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold) (H-) From 772043a9f4b45c8cda6d521f9ece5b7714e2c180 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Apr 2022 00:12:36 -0700 Subject: [PATCH 0700/2729] Create Readme.md --- .../2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md diff --git a/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md b/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md new file mode 100644 index 000000000..5862b001a --- /dev/null +++ b/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md @@ -0,0 +1,5 @@ +### 2245.Maximum-Trailing-Zeros-in-a-Cornered-Path + +作为常识,Trailing zero的个数只与因子2和因子5的个数有关。对于任何类型的cornered path,他们都有“拐点”。假设我们考虑这个拐点(i,j)伸出去的两条“长臂”分别是向上和向右,那么我们只需要统计向上走到顶的路径里有多少个2(记做up2)和多少个5(记做up5),向右走到边界的路径里有多少个2(记做right2)和多少个5(记做right5)。那么这个这个cornered path的trailing zero的个数就是```min(up2+right2-self2, up5+right5-self5)```. 其中self2表示(i,j)自身还有多少个2. + +因此,我们需要提前预处理,用前缀和的思想去计算每个位置的left2[i][j],right2[i][j],up2[i][j],down2[i][j],以及对应的left5[i][j],right5[i][j],up5[i][j],down5[i][j]。然后遍历每个位置,认为其是拐点,考虑四种形状,对于每种形状,计算两条长臂总共有多少个因子2和因子5. From c0768ed7c21c7e0c76bc3d59a493c2347fb01eeb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Apr 2022 00:13:41 -0700 Subject: [PATCH 0701/2729] Update Readme.md --- .../Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md b/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md index 5862b001a..e4da1ae62 100644 --- a/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md +++ b/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path/Readme.md @@ -1,5 +1,7 @@ ### 2245.Maximum-Trailing-Zeros-in-a-Cornered-Path -作为常识,Trailing zero的个数只与因子2和因子5的个数有关。对于任何类型的cornered path,他们都有“拐点”。假设我们考虑这个拐点(i,j)伸出去的两条“长臂”分别是向上和向右,那么我们只需要统计向上走到顶的路径里有多少个2(记做up2)和多少个5(记做up5),向右走到边界的路径里有多少个2(记做right2)和多少个5(记做right5)。那么这个这个cornered path的trailing zero的个数就是```min(up2+right2-self2, up5+right5-self5)```. 其中self2表示(i,j)自身还有多少个2. +首先,作为常识,Trailing zero的个数只与因子2和因子5的个数有关。 -因此,我们需要提前预处理,用前缀和的思想去计算每个位置的left2[i][j],right2[i][j],up2[i][j],down2[i][j],以及对应的left5[i][j],right5[i][j],up5[i][j],down5[i][j]。然后遍历每个位置,认为其是拐点,考虑四种形状,对于每种形状,计算两条长臂总共有多少个因子2和因子5. +对于任何类型的cornered path,他们都有“拐点”。假设我们考虑这个拐点(i,j)伸出去的两条“长臂”分别是向上和向右,那么我们只需要统计向上走到顶的路径里有多少个2(记做up2)和多少个5(记做up5),向右走到边界的路径里有多少个2(记做right2)和多少个5(记做right5)。那么这个这个cornered path的trailing zero的个数就是```min(up2+right2-self2, up5+right5-self5)```. 其中self2表示(i,j)自身还有多少个2. + +因此,我们需要提前预处理,用前缀和的思想去计算每个位置的left2[i][j],right2[i][j],up2[i][j],down2[i][j],以及对应的left5[i][j],right5[i][j],up5[i][j],down5[i][j]。然后遍历每个位置,认为其是拐点,考虑四种形状,对于每种形状,计算两条长臂总共有多少个因子2和因子5,就可以知道他们乘积的trailing zero了。 From d7baa37552695f7ad36fce0b3cff38331dc4892e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Apr 2022 20:36:48 -0700 Subject: [PATCH 0702/2729] Update Readme.md --- Others/1906.Minimum-Absolute-Difference-Queries/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/1906.Minimum-Absolute-Difference-Queries/Readme.md b/Others/1906.Minimum-Absolute-Difference-Queries/Readme.md index 6d98c38bc..7975a0ece 100644 --- a/Others/1906.Minimum-Absolute-Difference-Queries/Readme.md +++ b/Others/1906.Minimum-Absolute-Difference-Queries/Readme.md @@ -2,4 +2,4 @@ 本题的突破口在于nums的数值大小只有100. 意味着我们可以遍历这个数值。也就是说,对于一个nums的一个子区间,我们可以试图遍历它包含了多少个1,多少个2,多少个3,直至多少个100. 那么如果计算一个区间内某个元素的频次呢?可以用线段树,但是前缀和显然更简单。 -我们提前预处理得到persum[k][i],表示nums[0:i]这个前缀数组里包含了多少个数值k。显然,对于[left,right]的query,里面含有k的数目就是presum[k][right]-presum[k][left-1]. 我们将[left,right]内包含的所有数值(即presum之差大于零)排个序,找邻接最小的gap。 +我们提前预处理得到presum[k][i],表示nums[0:i]这个前缀数组里包含了多少个数值k。显然,对于[left,right]的query,里面含有k的数目就是presum[k][right]-presum[k][left-1]. 我们将[left,right]内包含的所有数值(即presum之差大于零)排个序,找邻接最小的gap。 From 95106d269d3a2817d63852db4f465a03cf065d5c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Apr 2022 20:37:59 -0700 Subject: [PATCH 0703/2729] Update Readme.md --- Others/1906.Minimum-Absolute-Difference-Queries/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/1906.Minimum-Absolute-Difference-Queries/Readme.md b/Others/1906.Minimum-Absolute-Difference-Queries/Readme.md index 7975a0ece..77bbb4c8e 100644 --- a/Others/1906.Minimum-Absolute-Difference-Queries/Readme.md +++ b/Others/1906.Minimum-Absolute-Difference-Queries/Readme.md @@ -1,5 +1,5 @@ ### 1906.Minimum-Absolute-Difference-Queries -本题的突破口在于nums的数值大小只有100. 意味着我们可以遍历这个数值。也就是说,对于一个nums的一个子区间,我们可以试图遍历它包含了多少个1,多少个2,多少个3,直至多少个100. 那么如果计算一个区间内某个元素的频次呢?可以用线段树,但是前缀和显然更简单。 +本题正面硬刚是很难做的。突破口在于nums的数值大小只有100. 意味着我们可以遍历这个数值。也就是说,对于一个nums的一个子区间,我们可以试图遍历它包含了多少个1,多少个2,多少个3,直至多少个100. 那么如果计算一个区间内某个元素的频次呢?可以用线段树,但是前缀和显然更简单。 我们提前预处理得到presum[k][i],表示nums[0:i]这个前缀数组里包含了多少个数值k。显然,对于[left,right]的query,里面含有k的数目就是presum[k][right]-presum[k][left-1]. 我们将[left,right]内包含的所有数值(即presum之差大于零)排个序,找邻接最小的gap。 From 4991013ecf708f911e5103a13ab9b0832f54d511 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 11:56:11 -0700 Subject: [PATCH 0704/2729] Update 1826.Faulty-Sensor.cpp --- .../1826.Faulty-Sensor/1826.Faulty-Sensor.cpp | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/Others/1826.Faulty-Sensor/1826.Faulty-Sensor.cpp b/Others/1826.Faulty-Sensor/1826.Faulty-Sensor.cpp index 508981d5f..b19b7020a 100644 --- a/Others/1826.Faulty-Sensor/1826.Faulty-Sensor.cpp +++ b/Others/1826.Faulty-Sensor/1826.Faulty-Sensor.cpp @@ -11,16 +11,29 @@ class Solution { } if (i>=n-1) return -1; - int flag = 1; + int flag1 = 1; for (int j=i; j Date: Sun, 1 May 2022 11:57:54 -0700 Subject: [PATCH 0705/2729] Update Readme.md --- Others/1826.Faulty-Sensor/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Others/1826.Faulty-Sensor/Readme.md b/Others/1826.Faulty-Sensor/Readme.md index 8b1d977b4..ad68aa629 100644 --- a/Others/1826.Faulty-Sensor/Readme.md +++ b/Others/1826.Faulty-Sensor/Readme.md @@ -2,4 +2,6 @@ 我们逐位比较,先定位第一次出现不同元素的位置i。如果不存在i,或者i在最后一个位置,那么就无法判断。 -接下来比较sensor1[i:n-2]是否和sensor2[i+1:n-1]完全对应。是的话,就说明前者丢失了数据;否则的话就是后者丢失了数据。 +接下来比较sensor1[i:n-2]是否和sensor2[i+1:n-1]完全对应。是的话,就有可能sensor1丢失了数据,我们标记为flag1为true。同理,比较sensor2[i:n-2]是否和sensor1[i+1:n-1]完全对应。是的话,就有可能sensor2丢失了数据,我们标记为flag2为true。 + +注意如果flag1和flag2都为true或者flase时,为无法判断。否则输出flag1或者flag2中为true的那个。 From f2879465a4ccb5f9912d386f4a0e9be7748502cf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 16:47:22 -0700 Subject: [PATCH 0706/2729] Create 2261.K-Divisible-Elements-Subarrays --- String/2261.K-Divisible-Elements-Subarrays | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 String/2261.K-Divisible-Elements-Subarrays diff --git a/String/2261.K-Divisible-Elements-Subarrays b/String/2261.K-Divisible-Elements-Subarrays new file mode 100644 index 000000000..f0b3f6d70 --- /dev/null +++ b/String/2261.K-Divisible-Elements-Subarrays @@ -0,0 +1,42 @@ +using ULL = unsigned long long; +class Solution { + ULL power[215]; + ULL P = 211; +public: + int countDistinct(vector& nums, int k, int p) + { + power[0] = 1; + for (int i=1; i<=211; i++) + power[i] = power[i-1]*P; + + int ret = 0; + + for (int len=1; len<=nums.size(); len++) + { + unordered_setSet; + ULL hash = 0; + int count = 0; + for (int i=0; i=len) + { + hash = hash - nums[i-len]*power[len-1]; + if (nums[i-len]%p==0) count--; + } + + hash = hash*P + nums[i]; + if (nums[i]%p==0) count++; + + if (i>=len-1) + { + if (Set.find(hash)!=Set.end()) continue; + Set.insert(hash); + if (count<=k) + ret += 1; + } + } + } + + return ret; + } +}; From edf121d151987ebfa1006fd887189a836b5f8095 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 16:48:38 -0700 Subject: [PATCH 0707/2729] Delete 2261.K-Divisible-Elements-Subarrays --- String/2261.K-Divisible-Elements-Subarrays | 42 ---------------------- 1 file changed, 42 deletions(-) delete mode 100644 String/2261.K-Divisible-Elements-Subarrays diff --git a/String/2261.K-Divisible-Elements-Subarrays b/String/2261.K-Divisible-Elements-Subarrays deleted file mode 100644 index f0b3f6d70..000000000 --- a/String/2261.K-Divisible-Elements-Subarrays +++ /dev/null @@ -1,42 +0,0 @@ -using ULL = unsigned long long; -class Solution { - ULL power[215]; - ULL P = 211; -public: - int countDistinct(vector& nums, int k, int p) - { - power[0] = 1; - for (int i=1; i<=211; i++) - power[i] = power[i-1]*P; - - int ret = 0; - - for (int len=1; len<=nums.size(); len++) - { - unordered_setSet; - ULL hash = 0; - int count = 0; - for (int i=0; i=len) - { - hash = hash - nums[i-len]*power[len-1]; - if (nums[i-len]%p==0) count--; - } - - hash = hash*P + nums[i]; - if (nums[i]%p==0) count++; - - if (i>=len-1) - { - if (Set.find(hash)!=Set.end()) continue; - Set.insert(hash); - if (count<=k) - ret += 1; - } - } - } - - return ret; - } -}; From a2777877b913223e0b4631932f8bb104cf9f13b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 16:48:59 -0700 Subject: [PATCH 0708/2729] Create 2261.K-Divisible-Elements-Subarrays.cpp --- .../2261.K-Divisible-Elements-Subarrays.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays.cpp diff --git a/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays.cpp b/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays.cpp new file mode 100644 index 000000000..f0b3f6d70 --- /dev/null +++ b/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays.cpp @@ -0,0 +1,42 @@ +using ULL = unsigned long long; +class Solution { + ULL power[215]; + ULL P = 211; +public: + int countDistinct(vector& nums, int k, int p) + { + power[0] = 1; + for (int i=1; i<=211; i++) + power[i] = power[i-1]*P; + + int ret = 0; + + for (int len=1; len<=nums.size(); len++) + { + unordered_setSet; + ULL hash = 0; + int count = 0; + for (int i=0; i=len) + { + hash = hash - nums[i-len]*power[len-1]; + if (nums[i-len]%p==0) count--; + } + + hash = hash*P + nums[i]; + if (nums[i]%p==0) count++; + + if (i>=len-1) + { + if (Set.find(hash)!=Set.end()) continue; + Set.insert(hash); + if (count<=k) + ret += 1; + } + } + } + + return ret; + } +}; From d659e0790d9c54099e89b2ed368bb33631fe1810 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 16:51:22 -0700 Subject: [PATCH 0709/2729] Create 2261.K-Divisible-Elements-Subarrays_v1.cpp --- ...2261.K-Divisible-Elements-Subarrays_v1.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v1.cpp diff --git a/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v1.cpp b/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v1.cpp new file mode 100644 index 000000000..40711f373 --- /dev/null +++ b/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v1.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int countDistinct(vector& nums, int k, int p) + { + int ret = 0; + + for (int len=1; len<=nums.size(); len++) + { + set>Set; + vectorarr; + int count = 0; + + for (int i=0; i=len) + { + arr.erase(arr.begin()); + if (nums[i-len]%p==0) count--; + } + + arr.push_back(nums[i]); + if (nums[i]%p==0) count++; + + if (i>=len-1) + { + if (Set.find(arr)!=Set.end()) continue; + Set.insert(arr); + if (count<=k) + ret += 1; + } + } + } + + return ret; + } +}; From 79cdc63ab2fe3e626cb9f01fc0153f5479785c6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 16:51:33 -0700 Subject: [PATCH 0710/2729] Rename 2261.K-Divisible-Elements-Subarrays.cpp to 2261.K-Divisible-Elements-Subarrays_v2.cpp --- ...s-Subarrays.cpp => 2261.K-Divisible-Elements-Subarrays_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename String/2261.K-Divisible-Elements-Subarrays/{2261.K-Divisible-Elements-Subarrays.cpp => 2261.K-Divisible-Elements-Subarrays_v2.cpp} (100%) diff --git a/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays.cpp b/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v2.cpp similarity index 100% rename from String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays.cpp rename to String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v2.cpp From 3cbacedabd97e617046eb65b3ee74ce9732bdde4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 16:55:14 -0700 Subject: [PATCH 0711/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 22c8384f3..411febc47 100644 --- a/Readme.md +++ b/Readme.md @@ -832,6 +832,7 @@ [2156.Find-Substring-With-Given-Hash-Value](https://github.com/wisdompeak/LeetCode/tree/master/String/2156.Find-Substring-With-Given-Hash-Value) (M) [2168.Unique-Substrings-With-Equal-Digit-Frequency](https://github.com/wisdompeak/LeetCode/tree/master/String/2168.Unique-Substrings-With-Equal-Digit-Frequency) (M+) [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) +[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) From 7996f3235b2f6286e0a84091edc8c331b8b40fce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 17:08:41 -0700 Subject: [PATCH 0712/2729] Create Readme.md --- String/2261.K-Divisible-Elements-Subarrays/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 String/2261.K-Divisible-Elements-Subarrays/Readme.md diff --git a/String/2261.K-Divisible-Elements-Subarrays/Readme.md b/String/2261.K-Divisible-Elements-Subarrays/Readme.md new file mode 100644 index 000000000..982303713 --- /dev/null +++ b/String/2261.K-Divisible-Elements-Subarrays/Readme.md @@ -0,0 +1,7 @@ +### 2261.K-Divisible-Elements-Subarrays + +#### 解法1:暴力 +用o(N^2)的算法枚举所有的subarray,然后强行将整个subarray放入一个集合之中判断是否重复。注意,这个集合操作不是o(1). 总的时间复杂度是o(N^3),刚好够。 + +#### 解法2:Rolling Hash +更高效的集合操作是存入subarray的某种编码,而不是subarray本身。这样对集合的写操作和查找操作才是真正的o(1)。考虑到每个元素不超过200,所以我们取201为base,将subarray拼接成一个201进制的数即可。同样,Rolling Hash会遇到数据类型溢出的问题。对于C++而言,采用unsigned long long的自然溢出来实现最大化的取模,是最方便的写法。参见```2223.Sum-of-Scores-of-Built-Strings```. From 7f12c78a1ffeb54fe51b27bd46319b1619a0fd9c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 17:43:47 -0700 Subject: [PATCH 0713/2729] Update 2261.K-Divisible-Elements-Subarrays_v2.cpp --- ...2261.K-Divisible-Elements-Subarrays_v2.cpp | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v2.cpp b/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v2.cpp index f0b3f6d70..1060f8f13 100644 --- a/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v2.cpp +++ b/String/2261.K-Divisible-Elements-Subarrays/2261.K-Divisible-Elements-Subarrays_v2.cpp @@ -1,42 +1,43 @@ using ULL = unsigned long long; + class Solution { - ULL power[215]; - ULL P = 211; + ULL power[211]; + ULL B = 201; public: int countDistinct(vector& nums, int k, int p) { + int n = nums.size(); power[0] = 1; - for (int i=1; i<=211; i++) - power[i] = power[i-1]*P; + for (int i=1; iSet; ULL hash = 0; int count = 0; - for (int i=0; i=len) { - hash = hash - nums[i-len]*power[len-1]; - if (nums[i-len]%p==0) count--; + hash = (hash - nums[i-len] * power[len-1] + M ) %M; + count -= (nums[i-len]%p==0); } - hash = hash*P + nums[i]; - if (nums[i]%p==0) count++; + hash = hash * B + nums[i]; + count += (nums[i]%p==0); if (i>=len-1) { if (Set.find(hash)!=Set.end()) continue; Set.insert(hash); - if (count<=k) - ret += 1; - } + if (count <= k) + ret+=1; + } } } - return ret; } }; From a1608ec0ed8a2fde71e99804bc2b26c5c114989b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 17:47:01 -0700 Subject: [PATCH 0714/2729] Create 2262.Total-Appeal-of-A-String.cpp --- .../2262.Total-Appeal-of-A-String.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp diff --git a/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp b/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp new file mode 100644 index 000000000..e91daf866 --- /dev/null +++ b/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + long long appealSum(string s) + { + vector>pos(26); + long long result=0; + for (int i=0; i=1) + { + int k = pos[i].size(); + result+=(long long)pos[i][k-1]+1; + } + } + } + return result; + + } +}; From 0204c5a78addc163be20c55d40f81997951c7269 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 17:48:06 -0700 Subject: [PATCH 0715/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 411febc47..e5f56e85e 100644 --- a/Readme.md +++ b/Readme.md @@ -151,6 +151,7 @@ [1573.Number-of-Ways-to-Split-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1573.Number-of-Ways-to-Split-a-String) (M) [2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words) (M) [2198.Number-of-Single-Divisor-Triplets](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2198.Number-of-Single-Divisor-Triplets) (H-) +[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2262.Total-Appeal-of-A-String) (M+) * ``Hash+Prefix`` [525.Contiguous-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/525.Contiguous-Array) (M) [930.Binary-Subarrays-With-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/930.Binary-Subarrays-With-Sum) (M) From fb5203d0fa79c5052d4b2e4219d4d12b58691d7b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 17:52:27 -0700 Subject: [PATCH 0716/2729] Create Readme.md --- Hash/2262.Total-Appeal-of-A-String/Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Hash/2262.Total-Appeal-of-A-String/Readme.md diff --git a/Hash/2262.Total-Appeal-of-A-String/Readme.md b/Hash/2262.Total-Appeal-of-A-String/Readme.md new file mode 100644 index 000000000..d230cc722 --- /dev/null +++ b/Hash/2262.Total-Appeal-of-A-String/Readme.md @@ -0,0 +1,14 @@ +### 2262.Total-Appeal-of-A-String + +此题几乎和```828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String```一模一样。 + +我们逐一遍历每个字符,现在考虑以i为结尾的各种substring。假设字符A在i之前最近一次出现的位置分别是a,如下图 +``` +X X X X X X [A X X i] + a +``` +显然,形如[a:i], [a-1:i], ... [0:i]这些substring(总共a+1个)里面必然都至少出现过一次A。也就是说对于这些substring而言,A给它们的appeal都贡献了一分。我们可以直接将a+1分加入到全局的答案中。而以其他任何位置作为起点的substring,A都无法给countUniqueChars贡献分数了。 + +同理,我们可以考察字符B,C,...他们对以i结尾的substring的贡献,将这些分数直接加入总分里面。 + +综上,每考察一个位置i,我们遍历26个字母(即A-Z)在i之前出现的最后位置,可以计算它们各自可以给多少substring贡献appeal。总的时间复杂度是o(26N)。 From d98f5fcb5a162230178df2f323d19f2ee47255a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 17:54:57 -0700 Subject: [PATCH 0717/2729] Update 2262.Total-Appeal-of-A-String.cpp --- .../2262.Total-Appeal-of-A-String.cpp | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp b/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp index e91daf866..3d708f1e9 100644 --- a/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp +++ b/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp @@ -2,21 +2,17 @@ class Solution { public: long long appealSum(string s) { - vector>pos(26); + vectorpos(26, -1); long long result=0; for (int i=0; i=1) - { - int k = pos[i].size(); - result+=(long long)pos[i][k-1]+1; - } + if (pos[i]!=-1) + result+=(long long)pos[i]+1; } } - return result; - + return result; } }; From 0a15d6aace512c1928b9123bcac2037e06ae36e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 18:31:50 -0700 Subject: [PATCH 0718/2729] Update 828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp --- ...rs-of-All-Substrings-of-a-Given-String.cpp | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp index 558ab78ce..b406067a3 100644 --- a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp +++ b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp @@ -1,26 +1,27 @@ class Solution { - long long M = pow(10,9)+7; public: - int uniqueLetterString(string S) - { - vector>pos(26); - int result=0; - for (int i=0; i>pos(26); // pos[k]: the pos of letter k so far (by i-th) + + int ret = 0; + for (int i=0; i1) + if (pos[k].size()>=2) { - int k = pos[i].size(); - result+=pos[i][k-1]-pos[i][k-2]; + int m = pos[k].size(); + ret += pos[k][m-1] - pos[k][m-2]; + } + else if (pos[k].size()==1) + { + ret += pos[k][0]+1; } - result = result%M; } } - return result; + return ret; } - }; From 1c5ad8219e95841c319dbca2db97ce8dd1328830 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 22:15:51 -0700 Subject: [PATCH 0719/2729] Create 2262.Total-Appeal-of-A-String_v2.cpp --- .../2262.Total-Appeal-of-A-String_v2.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp diff --git a/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp b/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp new file mode 100644 index 000000000..23f45731c --- /dev/null +++ b/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + long long appealSum(string s) + { + int n = s.size(); + vectorlast(26, -1); + + long long ret = 0; + for (int i=0; i Date: Sun, 1 May 2022 22:16:04 -0700 Subject: [PATCH 0720/2729] Rename 2262.Total-Appeal-of-A-String.cpp to 2262.Total-Appeal-of-A-String_v1.cpp --- ...ppeal-of-A-String.cpp => 2262.Total-Appeal-of-A-String_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hash/2262.Total-Appeal-of-A-String/{2262.Total-Appeal-of-A-String.cpp => 2262.Total-Appeal-of-A-String_v1.cpp} (100%) diff --git a/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp b/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v1.cpp similarity index 100% rename from Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String.cpp rename to Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v1.cpp From 4b50278036715190d6ceee9ab648fd1b531d87ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 22:22:17 -0700 Subject: [PATCH 0721/2729] Update Readme.md --- Hash/2262.Total-Appeal-of-A-String/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Hash/2262.Total-Appeal-of-A-String/Readme.md b/Hash/2262.Total-Appeal-of-A-String/Readme.md index d230cc722..95fd82c24 100644 --- a/Hash/2262.Total-Appeal-of-A-String/Readme.md +++ b/Hash/2262.Total-Appeal-of-A-String/Readme.md @@ -2,6 +2,7 @@ 此题几乎和```828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String```一模一样。 +#### 解法1: 我们逐一遍历每个字符,现在考虑以i为结尾的各种substring。假设字符A在i之前最近一次出现的位置分别是a,如下图 ``` X X X X X X [A X X i] @@ -12,3 +13,13 @@ X X X X X X [A X X i] 同理,我们可以考察字符B,C,...他们对以i结尾的substring的贡献,将这些分数直接加入总分里面。 综上,每考察一个位置i,我们遍历26个字母(即A-Z)在i之前出现的最后位置,可以计算它们各自可以给多少substring贡献appeal。总的时间复杂度是o(26N)。 + +#### 解法2: +如果同一个字符串里有多个A出现,那么我们约定,关于A的appeal只是由最左边的A给出。那么假设对于位置处于a的字母A而言,它之前最近的一个字母A位于b,如下图 +``` +X X X A X X [A] X X X + b a +``` +则确定由位置a上的A字符贡献appeal的substring,其左边界可以在“b右边”到“a左边”之间游动,其右边界可以在“a右边”到“最后一个字符右边”之间游动。所以组合的方案数是```(a-b)*(n-a)```. + +综上,依次遍历所有的字符串nums[i],找到该字符能贡献appeal的字符串的左右边界范围,计算组合数目。最终将全部结果都加起来,返回答案。时间复杂度是o(n). From 1a6962284fe881340ef41fd98f71b13ee5aca9a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 22:24:11 -0700 Subject: [PATCH 0722/2729] Update Readme.md --- Hash/2262.Total-Appeal-of-A-String/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash/2262.Total-Appeal-of-A-String/Readme.md b/Hash/2262.Total-Appeal-of-A-String/Readme.md index 95fd82c24..15c60e022 100644 --- a/Hash/2262.Total-Appeal-of-A-String/Readme.md +++ b/Hash/2262.Total-Appeal-of-A-String/Readme.md @@ -15,7 +15,7 @@ X X X X X X [A X X i] 综上,每考察一个位置i,我们遍历26个字母(即A-Z)在i之前出现的最后位置,可以计算它们各自可以给多少substring贡献appeal。总的时间复杂度是o(26N)。 #### 解法2: -如果同一个字符串里有多个A出现,那么我们约定,关于A的appeal只是由最左边的A给出。那么假设对于位置处于a的字母A而言,它之前最近的一个字母A位于b,如下图 +如果同一个字符串里有多个A出现,那么为了避免重复计数,我们约定,该字符串里关于A贡献的appeal只是由最左边的A给出。那么对于位置a处的字母A而言,假设它之前最近的一个字母A位于b,如下图 ``` X X X A X X [A] X X X b a From 4e8b2b79aaa040cb0f52ab9b19315eacc1ac3cd5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 May 2022 23:51:10 -0700 Subject: [PATCH 0723/2729] Create 2257.Count-Unguarded-Cells-in-the-Grid.cpp --- ...2257.Count-Unguarded-Cells-in-the-Grid.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Greedy/2257.Count-Unguarded-Cells-in-the-Grid/2257.Count-Unguarded-Cells-in-the-Grid.cpp diff --git a/Greedy/2257.Count-Unguarded-Cells-in-the-Grid/2257.Count-Unguarded-Cells-in-the-Grid.cpp b/Greedy/2257.Count-Unguarded-Cells-in-the-Grid/2257.Count-Unguarded-Cells-in-the-Grid.cpp new file mode 100644 index 000000000..ae14994d1 --- /dev/null +++ b/Greedy/2257.Count-Unguarded-Cells-in-the-Grid/2257.Count-Unguarded-Cells-in-the-Grid.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int countUnguarded(int m, int n, vector>& guards, vector>& walls) + { + vector>matrix(m, vector(n)); + for (auto guard: guards) + matrix[guard[0]][guard[1]] = 2; + for (auto wall: walls) + matrix[wall[0]][wall[1]] = 2; + + vector>dir({{1,0},{-1,0},{0,1},{0,-1}}); + for (auto guard: guards) + for (auto [dx, dy]: dir) + { + int i = guard[0], j = guard[1]; + while (1) + { + i+=dx; + j+=dy; + if (i<0||i>=m || j<0||j>=n) break; + if (matrix[i][j]==2) break; + matrix[i][j] = 1; + } + } + + int ret = 0; + for (int i=0; i Date: Sun, 1 May 2022 23:51:35 -0700 Subject: [PATCH 0724/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e5f56e85e..fc1d378eb 100644 --- a/Readme.md +++ b/Readme.md @@ -1078,6 +1078,7 @@ [2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) +[2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 40f93bd97ce078572b1216a3511e0cc3602c1682 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 00:08:58 -0700 Subject: [PATCH 0725/2729] Create Readme.md --- Greedy/2257.Count-Unguarded-Cells-in-the-Grid/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Greedy/2257.Count-Unguarded-Cells-in-the-Grid/Readme.md diff --git a/Greedy/2257.Count-Unguarded-Cells-in-the-Grid/Readme.md b/Greedy/2257.Count-Unguarded-Cells-in-the-Grid/Readme.md new file mode 100644 index 000000000..5dd737b94 --- /dev/null +++ b/Greedy/2257.Count-Unguarded-Cells-in-the-Grid/Readme.md @@ -0,0 +1,3 @@ +### 2257.Count-Unguarded-Cells-in-the-Grid + +从每个guard往四个方向扫,直至遇到wall或者另一个guard。最后统计整个矩阵里被没有被guard扫过的格子数目。 From 6dfc2800b811f5c39ca826d0dabc21857fca1544 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 00:25:11 -0700 Subject: [PATCH 0726/2729] Create 828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp --- ...of-All-Substrings-of-a-Given-String_v2.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp new file mode 100644 index 000000000..b4aa5feb4 --- /dev/null +++ b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int uniqueLetterString(string s) + { + int n = s.size(); + vector>pos(26); + + for (int k=0; k<26; k++) + pos[k].push_back(-1); + for (int i=0; i Date: Mon, 2 May 2022 00:25:23 -0700 Subject: [PATCH 0727/2729] Rename 828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp to 828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp --- ...-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/{828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp => 828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp} (100%) diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp similarity index 100% rename from Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String.cpp rename to Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp From 1da9e895b18de1da36da38d5af90a4c5b0ba0252 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 00:32:39 -0700 Subject: [PATCH 0728/2729] Update Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md index 1c214794f..dd7466cdb 100644 --- a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md +++ b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md @@ -2,6 +2,7 @@ 暴力的方法是枚举substring,然后考察这个区间里的字符哪些是unique的。这需要大致```o(N^2*26)```的复杂度。聪明的方法是考察每个字符,它可能在哪些substring里是unique的。 +### 解法1: 我们逐一遍历每个字符,现在考虑以i为结尾的各种substring。假设字符A在i之前最近两次出现的位置分别是a和b,如下图 ``` X X X X A X X [A X X i] @@ -12,3 +13,15 @@ X X X X A X X [A X X i] 同理,我们可以考察字符B,C,...他们对以i结尾的substring的贡献,将这些分数直接加入总分里面。 综上,每考察一个位置i,我们遍历26个字母(即A-Z)在i之前出现的最后两个位置,可以计算它们各自可以给多少substring贡献UniqueChars。总的时间复杂度是o(26N)。 + +### 解法2: +我们考虑位于s[i]的字母A,能够给哪些substring的countUniqueChars提供这一分?显然,我们就是要寻找哪些substring仅包含这一个A。我们假设i之前最近的一个A在位置j,i之后最近的一个A在位置k,如下图 +``` +X X X X A [X X A X X] A X X + j i k +``` +那么符合条件的substring的左边界可以在“j右边”到“i左边”之间游动;同理,这个substring的左边界可以在“i右边”到“k左边”之间游动。所以这样的substring的组合起来就有```(i-j)*(k-i)```个。 + +我们类似地对每一个s[i]这样处理,最终累加答案。 + +特别地,如果某个字符A在整个字符串里面只出现了一次或者两次,按照那么位置i之前或者之后可能就没有同样的字符出现。一个比较方便的处理方法是虚拟地认为在-1和n这两个位置都存在A。这样就依然可以当做上面的(j,i,k)的triplet来分析了。 From 68aaa7e35235299000d431edb8f678836d41dbb9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 00:32:54 -0700 Subject: [PATCH 0729/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md index dd7466cdb..6dbc8f725 100644 --- a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md +++ b/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md @@ -22,6 +22,6 @@ X X X X A [X X A X X] A X X ``` 那么符合条件的substring的左边界可以在“j右边”到“i左边”之间游动;同理,这个substring的左边界可以在“i右边”到“k左边”之间游动。所以这样的substring的组合起来就有```(i-j)*(k-i)```个。 -我们类似地对每一个s[i]这样处理,最终累加答案。 +我们类似地对每一个s[i]这样处理,最终累加答案。这个解法的时间复杂度是o(N). 特别地,如果某个字符A在整个字符串里面只出现了一次或者两次,按照那么位置i之前或者之后可能就没有同样的字符出现。一个比较方便的处理方法是虚拟地认为在-1和n这两个位置都存在A。这样就依然可以当做上面的(j,i,k)的triplet来分析了。 From b0049b763154bc7797c782cb5e02b3b9c96e0d1a Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Mon, 2 May 2022 00:35:23 -0700 Subject: [PATCH 0730/2729] move 828 and 2262 --- .../2262.Total-Appeal-of-A-String_v1.cpp | 0 .../2262.Total-Appeal-of-A-String_v2.cpp | 0 {Hash => Greedy}/2262.Total-Appeal-of-A-String/Readme.md | 0 ...t-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp | 0 ...t-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp | 0 .../Readme.md | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename {Hash => Greedy}/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v1.cpp (100%) rename {Hash => Greedy}/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp (100%) rename {Hash => Greedy}/2262.Total-Appeal-of-A-String/Readme.md (100%) rename {Hash => Greedy}/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp (100%) rename {Hash => Greedy}/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp (100%) rename {Hash => Greedy}/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md (100%) diff --git a/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v1.cpp b/Greedy/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v1.cpp similarity index 100% rename from Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v1.cpp rename to Greedy/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v1.cpp diff --git a/Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp b/Greedy/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp similarity index 100% rename from Hash/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp rename to Greedy/2262.Total-Appeal-of-A-String/2262.Total-Appeal-of-A-String_v2.cpp diff --git a/Hash/2262.Total-Appeal-of-A-String/Readme.md b/Greedy/2262.Total-Appeal-of-A-String/Readme.md similarity index 100% rename from Hash/2262.Total-Appeal-of-A-String/Readme.md rename to Greedy/2262.Total-Appeal-of-A-String/Readme.md diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp b/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp similarity index 100% rename from Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp rename to Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v1.cpp diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp b/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp similarity index 100% rename from Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp rename to Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String_v2.cpp diff --git a/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md b/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md similarity index 100% rename from Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md rename to Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md From 9113c32acf7f06d1c8657f0272079e3152ee60ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 00:36:46 -0700 Subject: [PATCH 0731/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index fc1d378eb..15ba6a946 100644 --- a/Readme.md +++ b/Readme.md @@ -141,7 +141,6 @@ [446.Arithmetic-Slices-II-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Hash/446.Arithmetic-Slices-II-Subsequence) (H) [128.Longest-Consecutive-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/128.Longest-Consecutive-Sequence) (H-) [753.Cracking-the-Safe](https://github.com/wisdompeak/LeetCode/tree/master/Hash/753.Cracking-the-Safe) (H) -[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [890.Find-and-Replace-Pattern](https://github.com/wisdompeak/LeetCode/tree/master/Hash/890.Find-and-Replace-Pattern) (M+) [939.Minimum-Area-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Hash/939.Minimum-Area-Rectangle) (M+) 982.Triples-with-Bitwise-AND-Equal-To-Zero (M+) (TBD) @@ -151,7 +150,6 @@ [1573.Number-of-Ways-to-Split-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1573.Number-of-Ways-to-Split-a-String) (M) [2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words) (M) [2198.Number-of-Single-Divisor-Triplets](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2198.Number-of-Single-Divisor-Triplets) (H-) -[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2262.Total-Appeal-of-A-String) (M+) * ``Hash+Prefix`` [525.Contiguous-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/525.Contiguous-Array) (M) [930.Binary-Subarrays-With-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/930.Binary-Subarrays-With-Sum) (M) @@ -1079,6 +1077,8 @@ [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) +[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) +[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2262.Total-Appeal-of-A-String) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 9ab6f3731138f9872b52b613dbb6c662cc8d1bae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 00:44:25 -0700 Subject: [PATCH 0732/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 15ba6a946..18802faf6 100644 --- a/Readme.md +++ b/Readme.md @@ -1077,8 +1077,8 @@ [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) -[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) -[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2262.Total-Appeal-of-A-String) (M+) +[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) +[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From f8f0e7c86f77a4e2b96df4b56227cc39813dd773 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 00:45:23 -0700 Subject: [PATCH 0733/2729] Update Readme.md --- .../Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md b/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md index 6dbc8f725..f47285524 100644 --- a/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md +++ b/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md @@ -1,8 +1,8 @@ -828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String +### 828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String 暴力的方法是枚举substring,然后考察这个区间里的字符哪些是unique的。这需要大致```o(N^2*26)```的复杂度。聪明的方法是考察每个字符,它可能在哪些substring里是unique的。 -### 解法1: +#### 解法1: 我们逐一遍历每个字符,现在考虑以i为结尾的各种substring。假设字符A在i之前最近两次出现的位置分别是a和b,如下图 ``` X X X X A X X [A X X i] @@ -14,7 +14,7 @@ X X X X A X X [A X X i] 综上,每考察一个位置i,我们遍历26个字母(即A-Z)在i之前出现的最后两个位置,可以计算它们各自可以给多少substring贡献UniqueChars。总的时间复杂度是o(26N)。 -### 解法2: +#### 解法2: 我们考虑位于s[i]的字母A,能够给哪些substring的countUniqueChars提供这一分?显然,我们就是要寻找哪些substring仅包含这一个A。我们假设i之前最近的一个A在位置j,i之后最近的一个A在位置k,如下图 ``` X X X X A [X X A X X] A X X From 855d42eb94f5cecb33cd4bf1b051764fed4fe2b7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 22:47:11 -0700 Subject: [PATCH 0734/2729] Update Readme.md --- Readme.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 18802faf6..69717ee9e 100644 --- a/Readme.md +++ b/Readme.md @@ -1077,8 +1077,6 @@ [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) -[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) -[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) @@ -1160,6 +1158,12 @@ [2122.Recover-the-Original-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2122.Recover-the-Original-Array) (H-) [1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) [2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) +* ``Count by Reverse Contribution`` +[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) +[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) +[1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) +[2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) +[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 050e238d5dfaf24d072e845cac1a277cb20b8014 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 22:51:02 -0700 Subject: [PATCH 0735/2729] Update Readme.md --- Readme.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Readme.md b/Readme.md index 69717ee9e..eff6fdf1d 100644 --- a/Readme.md +++ b/Readme.md @@ -1158,12 +1158,6 @@ [2122.Recover-the-Original-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2122.Recover-the-Original-Array) (H-) [1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) [2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) -* ``Count by Reverse Contribution`` -[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) -[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) -[1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) -[2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) -[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) @@ -1210,6 +1204,12 @@ * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) +* ``Count by Reverse Contribution`` +[828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) +[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) +[1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) +[2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) +[2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 7aa07c726595bfcdbb8fa5705a241d5fb1b32cc7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 22:55:20 -0700 Subject: [PATCH 0736/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index eff6fdf1d..7ec98e6e8 100644 --- a/Readme.md +++ b/Readme.md @@ -1204,7 +1204,7 @@ * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) -* ``Count by Reverse Contribution`` +* ``Aggregate Subarray by `` [828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) [1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) From 017650092d8beda51ac3d5f62eb1c6f5111c8278 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 22:57:28 -0700 Subject: [PATCH 0737/2729] Update Readme.md --- .../Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md b/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md index f47285524..c07e33c6e 100644 --- a/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md +++ b/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String/Readme.md @@ -25,3 +25,5 @@ X X X X A [X X A X X] A X X 我们类似地对每一个s[i]这样处理,最终累加答案。这个解法的时间复杂度是o(N). 特别地,如果某个字符A在整个字符串里面只出现了一次或者两次,按照那么位置i之前或者之后可能就没有同样的字符出现。一个比较方便的处理方法是虚拟地认为在-1和n这两个位置都存在A。这样就依然可以当做上面的(j,i,k)的triplet来分析了。 + +我们把这类技巧称为```aggregate subarray by element```.当我们想累加若干个不同subarray的某种属性时,因为遍历subarray的复杂度较高,我们改为遍历数组元素,反向计算每个元素对于总属性的贡献。 From b2232bb7bc60f21e6d3d97a3789b4668e73e9468 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 May 2022 23:43:47 -0700 Subject: [PATCH 0738/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7ec98e6e8..094acb634 100644 --- a/Readme.md +++ b/Readme.md @@ -1204,7 +1204,7 @@ * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) -* ``Aggregate Subarray by `` +* ``Aggregate Subarray by element`` [828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) [1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) From 5f74dbd30b2bd9b8dfff073835197033bd07cf92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 6 May 2022 23:42:38 -0700 Subject: [PATCH 0739/2729] Create 2258.Escape-the-Spreading-Fire_v1.cpp --- .../2258.Escape-the-Spreading-Fire_v1.cpp | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v1.cpp diff --git a/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v1.cpp b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v1.cpp new file mode 100644 index 000000000..7792ab49c --- /dev/null +++ b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v1.cpp @@ -0,0 +1,81 @@ +class Solution { +public: + int maximumMinutes(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + + vector>person = bfs(grid, 0); + vector>fire = bfs(grid, 1); + + if (person[m-1][n-1]==INT_MAX || person[m-1][n-1] > fire[m-1][n-1]) + return -1; + if (fire[m-1][n-1]==INT_MAX) + return 1e9; + + int ret = fire[m-1][n-1]-person[m-1][n-1]-1; + + if (fire[m-1][n-2] == fire[m-2][n-1]) return ret; + if (fire[m-1][n-2] < fire[m-2][n-1]) + { + if (person[m-2][n-1] == person[m-1][n-1]-1) + return ret+1; + } + else + { + if (person[m-1][n-2] == person[m-1][n-1]-1) + return ret+1; + } + + return ret; + } + + vector>bfs(vector>&grid, int type) + { + int m = grid.size(); + int n = grid[0].size(); + vector>rets(m, vector(n,INT_MAX)); + queue>q; + + if (type==0) + { + q.push({0,0}); + rets[0][0] = 0; + } + else + { + for (int i=0; i>dir({{1,0},{-1,0},{0,1},{0,-1}}); + int step = 0; + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + auto [x,y] = q.front(); + q.pop(); + + for (auto& [dx, dy] : dir) + { + int i = x+dx, j = y+dy; + if (i<0||i>=m||j<0||j>=n) continue; + if (grid[i][j]==2) continue; + if (rets[i][j]!=INT_MAX) continue; + rets[i][j] = step+1; + if (i!=m-1 || j!=n-1) + q.push({i,j}); + } + } + step++; + } + + return rets; + } +}; From 094455aacabf9d4f897eb6fd987a3640e450f5c1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 00:18:33 -0700 Subject: [PATCH 0740/2729] Create Readme.md --- BFS/2258.Escape-the-Spreading-Fire/Readme.md | 32 ++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 BFS/2258.Escape-the-Spreading-Fire/Readme.md diff --git a/BFS/2258.Escape-the-Spreading-Fire/Readme.md b/BFS/2258.Escape-the-Spreading-Fire/Readme.md new file mode 100644 index 000000000..8ead4d40e --- /dev/null +++ b/BFS/2258.Escape-the-Spreading-Fire/Readme.md @@ -0,0 +1,32 @@ +### 2258.Escape-the-Spreading-Fire + +#### 解法1:2遍BFS +首先,我们容易走两遍BFS,得到两个新矩阵person和fire。其中person[i][j]表示人从起点到达(i,j)点的最短时间,fire[i][j]表示任意火源到达(i,j)点的最短时间。显然我们的关注点就在右下角的位置。我们容易依次做出这些判断: +1. person[m-1][n-1] == INT_MAX,说明人永远到达不了终点,返回-1 +2. person[m-1][n-1] > fire[m-1][j],说明人永远不会比火更早到达终点,返回-1 +3. fire[m-1][n-1] == INT_MAX,说明火永远不会达到终点,那么人可以慢慢走,返回1e9 +4. 剩下的情况,必然是person[m-1][j]<=fire[m-1][n-1]. 我们令D = fire[m-1][j]-person[m-1][n-1]表示人比火早到的天数。接下来针对这种情况做详细的分析。 + +首先,我们保守一点,如果让人停留D-1天再出发,那么人最终达到终点的时间,恰好是火到达终点的前一天,所以还是符合题意的。因此D-1至少是一个解。有人会问,停留D-1天出发,意味着原先人到终点的最短路径要全体抬升D-1,如果保证这条路径上所有的位置依然有```person[i][j]+D-1 < fire[i][j]```呢?事实上,如果停留D-1天,造成人与火同时到达中间某一个位置,那么火就可以借用这条“路径”,必然也会造成人与火同时到达终点。这与之前“人停留D-1天出发,依然会比火早一天到达终点”矛盾。因此这个担忧是不必要的。 + +接下来是分析的难点。本题虽然不允许中途的任何位置人与火同时到达,但是允许终点位置人与火可以同时到达。所以我们需要考虑再多停留一天,也就是D是否是可行的答案。表面上,人停留D天后,依然可以与火同时到达终点,但是我们发现,如果人与火share同一条路径时,是不合题意的。如下图 +``` + F + O +P O O O D +``` +P可以走4步到达终点D,F可以走5步到达终点D。但事实上,P不能停留一天再出发(即5-4)。因为停留的话,人与火会在非终点的位置相遇,这就不合条件。那么该如何判定,人最多是否可以停留D天再出发呢?这个结论比较难总结。答案是:人到终点的最快路径,和火到终点的最快路径,必须是从两个不同方向,即(m-2,n-1)或者(m-1,n-2)进入终点。如下图 + +``` + F + O +P O O O D +``` +P可以走4步到达终点D,F可以走2步到达终点D。这中情况下,人可以停留两天再出发(即4-2)。因为人与火的最优路径只在终点才相遇。 + +所以判定D是否能是答案的过程如下顺序: +1. 如果```fire[m-1][n-2]==fire[m-2][n-1]```,说明两个方向上火都是最快路径,人无法避开,所以D不能是答案。 +2. 如果```fire[m-1][n-2]fire[m-2][n-1]```,说明从上边来是火的最快路径,那么我们希望人的最快路径是从左边来,故需查看是否```person[m-1][n-2]==person[m-1][n-1]-1````。是的话返回D。 + +判定完以上之后,就返回D-1. From 2ffb04ca4c5240cb3dba31a963343f8c9c421d2a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 00:19:06 -0700 Subject: [PATCH 0741/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 094acb634..067338063 100644 --- a/Readme.md +++ b/Readme.md @@ -480,6 +480,7 @@ [1905.Count-Sub-Islands](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1905.Count-Sub-Islands) (M+) [2045.Second-Minimum-Time-to-Reach-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2045.Second-Minimum-Time-to-Reach-Destination) (M+) [2101.Detonate-the-Maximum-Bombs](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2101.Detonate-the-Maximum-Bombs) (M+) +[2258.Escape-the-Spreading-Fire](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2258.Escape-the-Spreading-Fire) (H+) * ``Multi State`` [847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) [864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) From 16131a6c9b4ab66cea50e176d6216c4b5658fef6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 00:20:06 -0700 Subject: [PATCH 0742/2729] Update Readme.md --- BFS/2258.Escape-the-Spreading-Fire/Readme.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/BFS/2258.Escape-the-Spreading-Fire/Readme.md b/BFS/2258.Escape-the-Spreading-Fire/Readme.md index 8ead4d40e..fbe3be607 100644 --- a/BFS/2258.Escape-the-Spreading-Fire/Readme.md +++ b/BFS/2258.Escape-the-Spreading-Fire/Readme.md @@ -2,10 +2,10 @@ #### 解法1:2遍BFS 首先,我们容易走两遍BFS,得到两个新矩阵person和fire。其中person[i][j]表示人从起点到达(i,j)点的最短时间,fire[i][j]表示任意火源到达(i,j)点的最短时间。显然我们的关注点就在右下角的位置。我们容易依次做出这些判断: -1. person[m-1][n-1] == INT_MAX,说明人永远到达不了终点,返回-1 -2. person[m-1][n-1] > fire[m-1][j],说明人永远不会比火更早到达终点,返回-1 -3. fire[m-1][n-1] == INT_MAX,说明火永远不会达到终点,那么人可以慢慢走,返回1e9 -4. 剩下的情况,必然是person[m-1][j]<=fire[m-1][n-1]. 我们令D = fire[m-1][j]-person[m-1][n-1]表示人比火早到的天数。接下来针对这种情况做详细的分析。 +1. ```person[m-1][n-1] == INT_MAX```,说明人永远到达不了终点,返回-1 +2. ```person[m-1][n-1] > fire[m-1][j]```,说明人永远不会比火更早到达终点,返回-1 +3. ```fire[m-1][n-1] == INT_MAX```,说明火永远不会达到终点,那么人可以慢慢走,返回1e9 +4. 剩下的情况,必然是```person[m-1][j]<=fire[m-1][n-1]```. 我们令```D = fire[m-1][j]-person[m-1][n-1]```表示人比火早到的天数。接下来针对这种情况做详细的分析。 首先,我们保守一点,如果让人停留D-1天再出发,那么人最终达到终点的时间,恰好是火到达终点的前一天,所以还是符合题意的。因此D-1至少是一个解。有人会问,停留D-1天出发,意味着原先人到终点的最短路径要全体抬升D-1,如果保证这条路径上所有的位置依然有```person[i][j]+D-1 < fire[i][j]```呢?事实上,如果停留D-1天,造成人与火同时到达中间某一个位置,那么火就可以借用这条“路径”,必然也会造成人与火同时到达终点。这与之前“人停留D-1天出发,依然会比火早一天到达终点”矛盾。因此这个担忧是不必要的。 From af12ebb18942bcb548cc323544ea8f081f1da3db Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 00:25:45 -0700 Subject: [PATCH 0743/2729] Update 2258.Escape-the-Spreading-Fire_v1.cpp --- .../2258.Escape-the-Spreading-Fire_v1.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v1.cpp b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v1.cpp index 7792ab49c..c3ef7540a 100644 --- a/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v1.cpp +++ b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v1.cpp @@ -13,21 +13,21 @@ class Solution { if (fire[m-1][n-1]==INT_MAX) return 1e9; - int ret = fire[m-1][n-1]-person[m-1][n-1]-1; + int D = fire[m-1][n-1]-person[m-1][n-1]; - if (fire[m-1][n-2] == fire[m-2][n-1]) return ret; + if (fire[m-1][n-2] == fire[m-2][n-1]) return D-1; if (fire[m-1][n-2] < fire[m-2][n-1]) { if (person[m-2][n-1] == person[m-1][n-1]-1) - return ret+1; + return D; } else { if (person[m-1][n-2] == person[m-1][n-1]-1) - return ret+1; + return D; } - return ret; + return D-1; } vector>bfs(vector>&grid, int type) From 755b977a41bf808280fc2c565d944358c1dda413 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 00:34:41 -0700 Subject: [PATCH 0744/2729] Create 2258.Escape-the-Spreading-Fire_v2.cpp --- .../2258.Escape-the-Spreading-Fire_v2.cpp | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v2.cpp diff --git a/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v2.cpp b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v2.cpp new file mode 100644 index 000000000..7c7a07fe1 --- /dev/null +++ b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v2.cpp @@ -0,0 +1,106 @@ +class Solution { + vector>dir = {{1,0},{-1,0},{0,1},{0,-1}}; +public: + int maximumMinutes(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + + vector>person = bfs(grid, 0); + vector>fire = bfs(grid, 1); + + if (person[m-1][n-1]==INT_MAX || person[m-1][n-1] > fire[m-1][n-1]) + return -1; + if (fire[m-1][n-1]==INT_MAX) + return 1e9; + + int D = fire[m-1][n-1]-person[m-1][n-1]; + if (checkOK(grid, fire, D)) + return D; + else + return D-1; + } + + bool checkOK(vector>& grid, vector>fire, int D) + { + int m = grid.size(); + int n = grid[0].size(); + vector>visited(m, vector(n)); + + queue>q; + q.push({0,0}); + visited[0][0] = 1; + int step = D; + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + auto [x,y] = q.front(); + q.pop(); + for (auto& [dx, dy] : dir) + { + int i = x+dx, j = y+dy; + if (i<0||i>=m||j<0||j>=n) continue; + if (grid[i][j]==2) continue; + if (visited[i][j]) continue; + if ((i!=m-1 || j!=n-1) && step+1 >= fire[i][j]) continue; + q.push({i,j}); + visited[i][j] = 1; + if (i==m-1 && j==n-1) return true; + } + } + step++; + } + return false; + } + + vector>bfs(vector>&grid, int type) + { + int m = grid.size(); + int n = grid[0].size(); + vector>rets(m, vector(n,INT_MAX)); + queue>q; + + if (type==0) + { + q.push({0,0}); + rets[0][0] = 0; + } + else + { + for (int i=0; i=m||j<0||j>=n) continue; + if (grid[i][j]==2) continue; + if (rets[i][j]!=INT_MAX) continue; + rets[i][j] = step+1; + if (i!=m-1 || j!=n-1) + q.push({i,j}); + } + } + step++; + } + + return rets; + } +}; From 95fdf91e28d834dde6b88c7b2b4bb19f25078b24 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 00:40:01 -0700 Subject: [PATCH 0745/2729] Update Readme.md --- BFS/2258.Escape-the-Spreading-Fire/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/BFS/2258.Escape-the-Spreading-Fire/Readme.md b/BFS/2258.Escape-the-Spreading-Fire/Readme.md index fbe3be607..c87f54752 100644 --- a/BFS/2258.Escape-the-Spreading-Fire/Readme.md +++ b/BFS/2258.Escape-the-Spreading-Fire/Readme.md @@ -30,3 +30,9 @@ P可以走4步到达终点D,F可以走2步到达终点D。这中情况下, 3. 如果```fire[m-1][n-2]>fire[m-2][n-1]```,说明从上边来是火的最快路径,那么我们希望人的最快路径是从左边来,故需查看是否```person[m-1][n-2]==person[m-1][n-1]-1````。是的话返回D。 判定完以上之后,就返回D-1. + +#### 解法2:3遍BFS +在解法1中,我们的难点在于判断D是否是可行的解。其实有一个直观的做法,就是让人在起点停留D天,然后查看一下能否通过BFS顺利到达终点。BFS过程的要求就是人到任何一个中间位置(i,j)的时间,必须小于fire[i][j],否则就不能加入队列。如果最终能到达终点,就返回D,否则返回D-1. + +#### 解法3:二分搜值 +既然解法2中写了check函数来判断人停留D天后是否能到终点,那么我们索性就利用这个函数来二分搜值,找到最大的天数使得check的结果是OK。 From 71d4d137dae385cbf22fca091a487313daccf788 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 00:49:17 -0700 Subject: [PATCH 0746/2729] Create 2258.Escape-the-Spreading-Fire_v3.cpp --- .../2258.Escape-the-Spreading-Fire_v3.cpp | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v3.cpp diff --git a/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v3.cpp b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v3.cpp new file mode 100644 index 000000000..57c049894 --- /dev/null +++ b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v3.cpp @@ -0,0 +1,112 @@ +class Solution { + vector>dir = {{1,0},{-1,0},{0,1},{0,-1}}; +public: + int maximumMinutes(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + + vector>person = bfs(grid, 0); + vector>fire = bfs(grid, 1); + + if (person[m-1][n-1]==INT_MAX || person[m-1][n-1] > fire[m-1][n-1]) + return -1; + if (fire[m-1][n-1]==INT_MAX) + return 1e9; + + int left = 0, right = m*n; + while (left < right) + { + int mid = right-(right-left)/2; + if (checkOK(grid, fire, mid)) + left = mid; + else + right = mid-1; + } + if (checkOK(grid, fire, left)) return left; + else return -1; + } + + bool checkOK(vector>& grid, vector>fire, int D) + { + int m = grid.size(); + int n = grid[0].size(); + vector>visited(m, vector(n)); + + queue>q; + q.push({0,0}); + visited[0][0] = 1; + int step = D; + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + auto [x,y] = q.front(); + q.pop(); + for (auto& [dx, dy] : dir) + { + int i = x+dx, j = y+dy; + if (i<0||i>=m||j<0||j>=n) continue; + if (grid[i][j]==2) continue; + if (visited[i][j]) continue; + if ((i!=m-1 || j!=n-1) && step+1 >= fire[i][j]) continue; + q.push({i,j}); + visited[i][j] = 1; + if (i==m-1 && j==n-1 && step+1 <= fire[m-1][n-1]) return true; + } + } + step++; + } + return false; + } + + vector>bfs(vector>&grid, int type) + { + int m = grid.size(); + int n = grid[0].size(); + vector>rets(m, vector(n,INT_MAX)); + queue>q; + + if (type==0) + { + q.push({0,0}); + rets[0][0] = 0; + } + else + { + for (int i=0; i=m||j<0||j>=n) continue; + if (grid[i][j]==2) continue; + if (rets[i][j]!=INT_MAX) continue; + rets[i][j] = step+1; + if (i!=m-1 || j!=n-1) + q.push({i,j}); + } + } + step++; + } + + return rets; + } +}; From fee7a171ce95967dd5d777986adc866a1827ced3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 00:49:38 -0700 Subject: [PATCH 0747/2729] Update 2258.Escape-the-Spreading-Fire_v2.cpp --- .../2258.Escape-the-Spreading-Fire_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v2.cpp b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v2.cpp index 7c7a07fe1..aa967a04d 100644 --- a/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v2.cpp +++ b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v2.cpp @@ -47,7 +47,7 @@ class Solution { if ((i!=m-1 || j!=n-1) && step+1 >= fire[i][j]) continue; q.push({i,j}); visited[i][j] = 1; - if (i==m-1 && j==n-1) return true; + if (i==m-1 && j==n-1 && step+1 <= fire[m-1][n-1]) return true; } } step++; From a3b598d4006c8ccc2d2f7709dbdc31ba3be17846 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 01:15:47 -0700 Subject: [PATCH 0748/2729] Update Readme.md --- BFS/2258.Escape-the-Spreading-Fire/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/BFS/2258.Escape-the-Spreading-Fire/Readme.md b/BFS/2258.Escape-the-Spreading-Fire/Readme.md index c87f54752..bd2295603 100644 --- a/BFS/2258.Escape-the-Spreading-Fire/Readme.md +++ b/BFS/2258.Escape-the-Spreading-Fire/Readme.md @@ -36,3 +36,11 @@ P可以走4步到达终点D,F可以走2步到达终点D。这中情况下, #### 解法3:二分搜值 既然解法2中写了check函数来判断人停留D天后是否能到终点,那么我们索性就利用这个函数来二分搜值,找到最大的天数使得check的结果是OK。 + +#### 解法4:BFS+反向Dijkstra +在正向BFS求得fire矩阵之后,假设人到达终点的时间就是fire[m-1][n-1],然后反向从右下角开始Dijkstra,求得右下角到矩阵每个位置的最短路径。也就是说,我们可以求得一个矩阵,ret[i][j]表示人最晚什么时候到达(i,j),才能保证能在fire[m-1][n-1]时刻到达右下角。 + +举个例子,假设右下角的初始时刻是9,相邻的两个位置上有fire[m-1][n-2]是8,fire[m-2][n-1]是10;那么rets[m-1][n-2]就是7,fire[m-1][n-2]是8. Dijkstra的传播过程要遵守两个规则:随着图的伸入,ret[i][j]必须是递减的过程;其次ret[i][j]必须小于fire[i][j]. + +最终的答案是ret[0][0]. + From 902304f0f1fb9da79806f411725c5ed4d51c4203 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 01:17:32 -0700 Subject: [PATCH 0749/2729] Update Readme.md --- BFS/2258.Escape-the-Spreading-Fire/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/2258.Escape-the-Spreading-Fire/Readme.md b/BFS/2258.Escape-the-Spreading-Fire/Readme.md index bd2295603..2d329a4b1 100644 --- a/BFS/2258.Escape-the-Spreading-Fire/Readme.md +++ b/BFS/2258.Escape-the-Spreading-Fire/Readme.md @@ -40,7 +40,7 @@ P可以走4步到达终点D,F可以走2步到达终点D。这中情况下, #### 解法4:BFS+反向Dijkstra 在正向BFS求得fire矩阵之后,假设人到达终点的时间就是fire[m-1][n-1],然后反向从右下角开始Dijkstra,求得右下角到矩阵每个位置的最短路径。也就是说,我们可以求得一个矩阵,ret[i][j]表示人最晚什么时候到达(i,j),才能保证能在fire[m-1][n-1]时刻到达右下角。 -举个例子,假设右下角的初始时刻是9,相邻的两个位置上有fire[m-1][n-2]是8,fire[m-2][n-1]是10;那么rets[m-1][n-2]就是7,fire[m-1][n-2]是8. Dijkstra的传播过程要遵守两个规则:随着图的伸入,ret[i][j]必须是递减的过程;其次ret[i][j]必须小于fire[i][j]. +举个例子,假设右下角的初始时刻是9,相邻的两个位置上有fire[m-1][n-2]是8,fire[m-2][n-1]是10;那么rets[m-1][n-2]就是7,fire[m-1][n-2]是8. Dijkstra的传播过程要遵守两个规则:随着BFS的过程,ret[i][j]必须逐步是变小;其次任何位置上,ret[i][j]必须小于fire[i][j]. 最终的答案是ret[0][0]. From ba323fd287d52205e7ab2b6103eac11b89dd926a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 10:21:21 -0700 Subject: [PATCH 0750/2729] Update Readme.md --- BFS/2258.Escape-the-Spreading-Fire/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/2258.Escape-the-Spreading-Fire/Readme.md b/BFS/2258.Escape-the-Spreading-Fire/Readme.md index 2d329a4b1..f6787845b 100644 --- a/BFS/2258.Escape-the-Spreading-Fire/Readme.md +++ b/BFS/2258.Escape-the-Spreading-Fire/Readme.md @@ -40,7 +40,7 @@ P可以走4步到达终点D,F可以走2步到达终点D。这中情况下, #### 解法4:BFS+反向Dijkstra 在正向BFS求得fire矩阵之后,假设人到达终点的时间就是fire[m-1][n-1],然后反向从右下角开始Dijkstra,求得右下角到矩阵每个位置的最短路径。也就是说,我们可以求得一个矩阵,ret[i][j]表示人最晚什么时候到达(i,j),才能保证能在fire[m-1][n-1]时刻到达右下角。 -举个例子,假设右下角的初始时刻是9,相邻的两个位置上有fire[m-1][n-2]是8,fire[m-2][n-1]是10;那么rets[m-1][n-2]就是7,fire[m-1][n-2]是8. Dijkstra的传播过程要遵守两个规则:随着BFS的过程,ret[i][j]必须逐步是变小;其次任何位置上,ret[i][j]必须小于fire[i][j]. +举个例子,假设右下角的初始时刻是9,相邻的两个位置上有fire[m-1][n-2]是8,fire[m-2][n-1]是10;那么rets[m-1][n-2]就是7,fire[m-1][n-2]是8. Dijkstra的传播过程要遵守两个规则:随着BFS的过程,ret[i][j]必须逐步是变小;其次任何位置上,ret[i][j]必须小于fire[i][j]. 这也解释了为什么得用Dijkstra和PQ,而不是传统的BFS和队列,这是因为相邻两点之间的时间差不一定是1. 最终的答案是ret[0][0]. From 930063ae729f3cd1e4ac2e241409054dcd97afba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 May 2022 10:27:21 -0700 Subject: [PATCH 0751/2729] Create 2258.Escape-the-Spreading-Fire_v4.cpp --- .../2258.Escape-the-Spreading-Fire_v4.cpp | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v4.cpp diff --git a/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v4.cpp b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v4.cpp new file mode 100644 index 000000000..072c97f72 --- /dev/null +++ b/BFS/2258.Escape-the-Spreading-Fire/2258.Escape-the-Spreading-Fire_v4.cpp @@ -0,0 +1,122 @@ +class Solution { + vector>dir = {{1,0},{-1,0},{0,1},{0,-1}}; +public: + int maximumMinutes(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + + vector>person = bfs(grid, 0); + vector>fire = bfs(grid, 1); + + if (person[m-1][n-1]==INT_MAX || person[m-1][n-1] > fire[m-1][n-1]) + return -1; + if (fire[m-1][n-1]==INT_MAX) + return 1e9; + + vector>visited(m, vector(n)); + priority_queue>pq; + pq.push({fire[m-1][n-1], m-1, n-1}); + while (!pq.empty()) + { + auto [t, x, y] = pq.top(); + pq.pop(); + if (visited[x][y]) continue; + visited[x][y] = 1; + if (x==0 && y==0) return t; + + for (auto& [dx, dy] : dir) + { + int i = x+dx, j = y+dy; + if (i<0||i>=m||j<0||j>=n) continue; + if (grid[i][j]==2) continue; + if (visited[i][j]) continue; + pq.push({min(t-1,fire[i][j]-1), i,j}); + } + } + return -1; + } + + bool checkOK(vector>& grid, vector>fire, int D) + { + int m = grid.size(); + int n = grid[0].size(); + vector>visited(m, vector(n)); + + queue>q; + q.push({0,0}); + visited[0][0] = 1; + int step = D; + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + auto [x,y] = q.front(); + q.pop(); + for (auto& [dx, dy] : dir) + { + int i = x+dx, j = y+dy; + if (i<0||i>=m||j<0||j>=n) continue; + if (grid[i][j]==2) continue; + if (visited[i][j]) continue; + if ((i!=m-1 || j!=n-1) && step+1 >= fire[i][j]) continue; + q.push({i,j}); + visited[i][j] = 1; + if (i==m-1 && j==n-1 && step+1 <= fire[m-1][n-1]) return true; + } + } + step++; + } + return false; + } + + vector>bfs(vector>&grid, int type) + { + int m = grid.size(); + int n = grid[0].size(); + vector>rets(m, vector(n,INT_MAX)); + queue>q; + + if (type==0) + { + q.push({0,0}); + rets[0][0] = 0; + } + else + { + for (int i=0; i=m||j<0||j>=n) continue; + if (grid[i][j]==2) continue; + if (rets[i][j]!=INT_MAX) continue; + rets[i][j] = step+1; + if (i!=m-1 || j!=n-1) + q.push({i,j}); + } + } + step++; + } + + return rets; + } +}; From 707d64accb892107e768dee9212a33da3f51ec3d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 May 2022 18:31:10 -0700 Subject: [PATCH 0752/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 067338063..84b989de1 100644 --- a/Readme.md +++ b/Readme.md @@ -1229,6 +1229,7 @@ [1943.Describe-the-Painting](https://github.com/wisdompeak/LeetCode/tree/master/Others/1943.Describe-the-Painting) (H-) [2015.Average-Height-of-Buildings-in-Each-Segment](https://github.com/wisdompeak/LeetCode/tree/master/Others/2015.Average-Height-of-Buildings-in-Each-Segment) (H-) [2158.Amount-of-New-Area-Painted-Each-Day](https://github.com/wisdompeak/LeetCode/tree/master/Others/2158.Amount-of-New-Area-Painted-Each-Day) (H-) +2237.Count-Positions-on-Street-With-Required-Brightness (M) [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) From c53516b6103a66af9306b6c6cebab1f9ef8b9981 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 May 2022 22:28:10 -0700 Subject: [PATCH 0753/2729] Create 2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp --- ...ere-Is-a-Valid-Parentheses-String-Path.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp diff --git a/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp new file mode 100644 index 000000000..8d7770187 --- /dev/null +++ b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + bool hasValidPath(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + vector>>dp(m, vector>(n)); + + if (grid[0][0]=='(') + dp[0][0] = {1}; + else + dp[0][0] = {}; + + for (int i=0; i=1) + { + for (int x: dp[i-1][j]) + if (x+k>=0 && (m+n-1)-(i+j+1)>=(x+k)) + dp[i][j].insert(x+k); + } + if (j>=1) + for (int x: dp[i][j-1]) + { + if (x+k>=0 && (m+n-1)-(i+j+1)>=(x+k)) + dp[i][j].insert(x+k); + } + } + + return dp[m-1][n-1].find(0)!=dp[m-1][n-1].end(); + } +}; From c24400d31777e364cea181697563965606ac35ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 May 2022 22:43:51 -0700 Subject: [PATCH 0754/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/Readme.md diff --git a/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/Readme.md b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/Readme.md new file mode 100644 index 000000000..82a8f045c --- /dev/null +++ b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/Readme.md @@ -0,0 +1,11 @@ +### 2267.Check-if-There-Is-a-Valid-Parentheses-String-Path + +我们做过很多关于valid parentheses的题目。对于一个合法的括号字符串,必须满足两个条件:1. 任意的前缀字符串必须满足左括号的数目不能少于右括号的数目。2. 整个字符串结尾处,左右括号的数目必须相等。更具体的做法,就是用一个计数器count,来记录当前未被匹配的左括号的数量,一定在从左往右遍历的过程中发现count小于0,那么即可判定该字符串不可能是valid parentheses. + +本题形式上非常类似常规的“走迷宫”型DP。事实上,也确实是同样的套路。我们想用dp[i][j]表示某个字符串路径到达(i,j)时是否依然合法,必然需要记录的就是未被匹配的左括号数量。但是由于之前路径的不同,到达(i,j)时的未匹配左括号的数量也必然可能有多个,所以本题里dp[i][j]其实是一个集合。 + +dp[i][j]的前驱状态有两个,dp[i-1][j]和dp[i][j-1]. 假设前驱状态的两个集合总共包含了{0,2,3},并且(i,j)是一个左括号,那么dp[i][j]就可以是{1,3,4},也就是将前者集合的元素都增1. 相反地,如果(i,j)是一个右括号,那么需要和之前的左括号对消,故dp[i][j]就是{1,2}. 特别注意,d[i][j]里面不能加入-1,因为不会有valid parentheses里面(哪怕是暂时地)出现未匹配的左括号是负数。 + +特别地,如果dp[i][j]的前驱状态的集合是空集,那么意味着无论如何,从起点到(i,j)都不会有合法的路径,故dp[i][j]也必须赋值为空集。 + +最终的答案就是查看dp[m-1][n-1]这个集合是否包含零元素。 From 1d3d45d5f785153a4b050f00d3c107170d371d8a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 May 2022 22:44:17 -0700 Subject: [PATCH 0755/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 84b989de1..d4f5d6b98 100644 --- a/Readme.md +++ b/Readme.md @@ -662,6 +662,7 @@ [1289.Minimum-Falling-Path-Sum-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1289.Minimum-Falling-Path-Sum-II) (M+) [1301.Number-of-Paths-with-Max-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1301.Number-of-Paths-with-Max-Score) (M+) [1594.Maximum-Non-Negative-Product-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1594.Maximum-Non-Negative-Product-in-a-Matrix) (M) +[2267.Check-if-There-Is-a-Valid-Parentheses-String-Path](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path) (H-) * ``背包型`` [322.Coin-Change](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/322.Coin-Change) (M) [416.Partition-Equal-Subset-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/416.Partition-Equal-Subset-Sum) (M+) From 728f006a796492ed5441f4d8823e2b04385d7840 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 May 2022 23:24:08 -0700 Subject: [PATCH 0756/2729] Update 2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp --- .../2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp index 8d7770187..ac936c5b0 100644 --- a/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp +++ b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path.cpp @@ -3,7 +3,7 @@ class Solution { bool hasValidPath(vector>& grid) { int m = grid.size(), n = grid[0].size(); - vector>>dp(m, vector>(n)); + set dp[101][101]; if (grid[0][0]=='(') dp[0][0] = {1}; From b30dc76acc7124db9d537634be29b723e1149740 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 May 2022 23:35:42 -0700 Subject: [PATCH 0757/2729] Create 2267.Check-if-There-Is-a-Valid-Parentheses-String-Path_v2.cpp --- ...-Is-a-Valid-Parentheses-String-Path_v2.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path_v2.cpp diff --git a/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path_v2.cpp b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path_v2.cpp new file mode 100644 index 000000000..70d684190 --- /dev/null +++ b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path_v2.cpp @@ -0,0 +1,26 @@ +class Solution { + bool dp[101][101][103]; +public: + bool hasValidPath(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + + if (grid[0][0]=='(') + dp[0][0][1] = true; + + for (int i=0; i0 && grid[i][j]=='(') + dp[i][j][k] = (i>=1 && dp[i-1][j][k-1]) || (j>=1 && dp[i][j-1][k-1]); + else if (grid[i][j]==')') + dp[i][j][k] = (i>=1 && dp[i-1][j][k+1]) || (j>=1 && dp[i][j-1][k+1]); + } + + return dp[m-1][n-1][0]; + + } +}; From a76217e1ee868e0bda23b1aecf0556539a8c769b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 10 May 2022 01:26:16 -0700 Subject: [PATCH 0758/2729] Update 056.Merge-Intervals.cpp --- .../056.Merge-Intervals.cpp | 59 +++++++++---------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/Others/056.Merge-Intervals/056.Merge-Intervals.cpp b/Others/056.Merge-Intervals/056.Merge-Intervals.cpp index 36b89ec9d..80dc7fb0e 100644 --- a/Others/056.Merge-Intervals/056.Merge-Intervals.cpp +++ b/Others/056.Merge-Intervals/056.Merge-Intervals.cpp @@ -1,43 +1,40 @@ -/** - * Definition for an interval. - * struct Interval { - * int start; - * int end; - * Interval() : start(0), end(0) {} - * Interval(int s, int e) : start(s), end(e) {} - * }; - */ class Solution { + static bool cmp(pair&a, pair&b) + { + if (a.first!=b.first) + return a.first b.second; + } public: - vector merge(vector& intervals) + vector> merge(vector>& intervals) { - vector>q; - for (int i=0; i>diff; + for (auto& interval: intervals) { - q.push_back({intervals[i].start,-1}); - q.push_back({intervals[i].end,1}); + diff.push_back({interval[0], 1}); + diff.push_back({interval[1], -1}); } + + sort(diff.begin(), diff.end(), cmp); - sort(q.begin(),q.end()); - - int count=0; - int start, end; - - vectorresults; - - for (int i=0; i>rets; + int start = 0, end = 0; + int sum = 0; + for (int i=0; i 0) + { + start = diff[i].first; + } + else if (sum > 0 && sum + diff[i].second == 0) { - end = q[i].first; - results.push_back({start,end}); + end = diff[i].first; + rets.push_back({start,end}); } + sum += diff[i].second; } - - return results; + + return rets; } }; From 14905de12c923709ade72c785d093f365bf5ec2c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 00:09:21 -0700 Subject: [PATCH 0759/2729] Update Readme.md --- Others/056.Merge-Intervals/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Others/056.Merge-Intervals/Readme.md b/Others/056.Merge-Intervals/Readme.md index 90e3bb855..58b28a487 100644 --- a/Others/056.Merge-Intervals/Readme.md +++ b/Others/056.Merge-Intervals/Readme.md @@ -1,8 +1,8 @@ ### 056.Merge-Intervals -和252类似的解题手法. +对于区间合并的题目,一般都会采用和252类似的“扫描线”算法。对于每一个区间[a,b],我们在a时刻记录+1,在b时刻记录-1. 然后我们再在时间轴上顺次遍历每一个时间点,统计这些+1和-1的总和。我们会发现当sum从0变为正数时,意味着一个merged interval的开始;当sum从正数变成0时,意味着一个merged interval的结束。这样就巧妙地把所有存在overlap的区间都合并到了一起。 -需要注意的是,此题中的有效区间长度可以为0,即[t,t]也是合法的,所以在数组q中,我们除了按时间排序之外,第二指标应该按照先1后-1的次序.即如果遇到相同的时刻,{start,1}要比{end,-1}先进行处理,这样就能顺利地包容[t,t]这样的区间. +需要注意的是,对于相同的时刻,如果同时存在多个+1或者-1,应该先处理+1后处理-1。比如[a,b]和[b,c]两个区间,在处理b时刻时,按照先+1再-1的顺序,就不会出现sum=0的情况了,也就避免了merged interval在b处断开。 -[Leetcode Link](https://leetcode.com/problems/merge-intervals) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/merge-intervals) From bf36143690d643efcc5a6ec587d68a9041f3eafa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 00:51:39 -0700 Subject: [PATCH 0760/2729] Update Readme.md --- Others/732.My-Calendar-III/Readme.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Others/732.My-Calendar-III/Readme.md b/Others/732.My-Calendar-III/Readme.md index 3e0066e7d..3bd3d1cd3 100644 --- a/Others/732.My-Calendar-III/Readme.md +++ b/Others/732.My-Calendar-III/Readme.md @@ -1,10 +1,7 @@ ### 732.My-Calendar-III -此题有奇思妙解. +典型的扫描线算法。 -我们设计一个顺序的multiset>Set,每次调用我们就往里面放置{start,1}和{end,-1}.然后遍历这个集合,按照从小到大的顺序更新一个计数器,遇到1就加一,遇到-1就减一. +我们用一个按key有序的Map。每次调用book函数时,我们就操作```Map[start]+=1```和```Map[end]-=1```。然后遍历这个Map的key,按照时间轴的顺序累加差分值,即遇到1就加一,遇到-1就减一。这样就得到每个时刻有多少并行的会议。最终输出其中的最大值。 -奇妙的就是,你这样可以实时得到的,就是当前k booking的状态.遍历完之后这个计数器的历史最大值就是答案. - - -[Leetcode Link](https://leetcode.com/problems/my-calendar-iii) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/my-calendar-iii) From f4c967f4cd54eb8d242747a14a6f9a3dd528c629 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 00:51:59 -0700 Subject: [PATCH 0761/2729] Update 732.My-Calendar-III.cpp --- .../732.My-Calendar-III.cpp | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Others/732.My-Calendar-III/732.My-Calendar-III.cpp b/Others/732.My-Calendar-III/732.My-Calendar-III.cpp index 1009c4644..413162289 100644 --- a/Others/732.My-Calendar-III/732.My-Calendar-III.cpp +++ b/Others/732.My-Calendar-III/732.My-Calendar-III.cpp @@ -1,6 +1,6 @@ class MyCalendarThree { public: - multiset>Set; + mapMap; MyCalendarThree() { @@ -9,23 +9,23 @@ class MyCalendarThree { int book(int start, int end) { - Set.insert({start,1}); - Set.insert({end,-1}); + Map[start]+=1; + Map[end]-=1; int count=0; - int result=0; - for (auto a: Set) + int ret=0; + for (auto& [t, diff]: Map) { - count+=a.second; - result = max(result,count); + count += diff; + ret = max(ret, count); } - return result; + return ret; } }; /** * Your MyCalendarThree object will be instantiated and called as such: - * MyCalendarThree obj = new MyCalendarThree(); - * int param_1 = obj.book(start,end); + * MyCalendarThree* obj = new MyCalendarThree(); + * int param_1 = obj->book(start,end); */ From 8f0936e8d7fa3a733d8ab8158aaff3cd676a3eb4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 01:24:00 -0700 Subject: [PATCH 0762/2729] Update Readme.md --- Others/253.Meeting-Rooms-II/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Others/253.Meeting-Rooms-II/Readme.md b/Others/253.Meeting-Rooms-II/Readme.md index a8a798fb1..38c297c29 100644 --- a/Others/253.Meeting-Rooms-II/Readme.md +++ b/Others/253.Meeting-Rooms-II/Readme.md @@ -16,11 +16,11 @@ 对于pq的数据结构,我们在C++中还可以用multiset来实现,因为它也是自动有序的。 -#### 解法2: +#### 解法2: 扫描线 将所有{startTime,1}和{endTime,-1}加入一个数组,然后将这个数组按照时间戳排序.注意,本题中所有的有效区间的长度必须大于0,所以,{time,-1}要比{time,1}排序更靠前. 使用一个count依时间顺序将所有的+1/-1进行累加.当count>0的时候标志着一个会议的开始,重新归为0的时候标着一个会议的结束. -[Leetcode Link](https://leetcode.com/problems/meeting-rooms-ii) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/meeting-rooms-ii) From 4f2379f0b6c963f29abf6c1f2f5ad8ef8417334c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 01:32:19 -0700 Subject: [PATCH 0763/2729] Update 253.Meeting-Rooms-II_v2.cpp --- .../253.Meeting-Rooms-II_v2.cpp | 44 +++++++------------ 1 file changed, 15 insertions(+), 29 deletions(-) diff --git a/Others/253.Meeting-Rooms-II/253.Meeting-Rooms-II_v2.cpp b/Others/253.Meeting-Rooms-II/253.Meeting-Rooms-II_v2.cpp index f1ea07acb..a4763c5ea 100644 --- a/Others/253.Meeting-Rooms-II/253.Meeting-Rooms-II_v2.cpp +++ b/Others/253.Meeting-Rooms-II/253.Meeting-Rooms-II_v2.cpp @@ -1,34 +1,20 @@ -/** - * Definition for an interval. - * struct Interval { - * int start; - * int end; - * Interval() : start(0), end(0) {} - * Interval(int s, int e) : start(s), end(e) {} - * }; - */ class Solution { - static bool cmp1(Interval a, Interval b) - { - return a.start& intervals) - { - sort(intervals.begin(),intervals.end(),cmp1); - multisetSet; - int count=0; - int i=0; - while (iintervals[i].start) - { - Set.insert(intervals[i].end); - count = max(count,int(Set.size())); - i++; - } - Set.erase(Set.begin()); + int minMeetingRooms(vector>& intervals) { + mapMap; + for (auto interval:intervals) + { + Map[interval[0]]+=1; + Map[interval[1]]-=1; + } + + int sum = 0; + int ret = 0; + for (auto& [t,diff]: Map) + { + sum += diff; + ret = max(sum, ret); } - return count; + return ret; } }; From 6b48384833ce75c159163be0f9314d12da0c1513 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 01:33:04 -0700 Subject: [PATCH 0764/2729] Update Readme.md --- Others/253.Meeting-Rooms-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/253.Meeting-Rooms-II/Readme.md b/Others/253.Meeting-Rooms-II/Readme.md index 38c297c29..78e72ed80 100644 --- a/Others/253.Meeting-Rooms-II/Readme.md +++ b/Others/253.Meeting-Rooms-II/Readme.md @@ -18,7 +18,7 @@ #### 解法2: 扫描线 -将所有{startTime,1}和{endTime,-1}加入一个数组,然后将这个数组按照时间戳排序.注意,本题中所有的有效区间的长度必须大于0,所以,{time,-1}要比{time,1}排序更靠前. +本题和732一模一样。将所有{startTime,1}和{endTime,-1}加入一个数组,然后将这个数组按照时间戳排序.注意,本题中所有的有效区间的长度必须大于0,所以,{time,-1}要比{time,1}排序更靠前. 使用一个count依时间顺序将所有的+1/-1进行累加.当count>0的时候标志着一个会议的开始,重新归为0的时候标着一个会议的结束. From 0e98ccd41a47e0201b570d7106091a4d892567bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 01:33:35 -0700 Subject: [PATCH 0765/2729] Update Readme.md --- Others/732.My-Calendar-III/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/732.My-Calendar-III/Readme.md b/Others/732.My-Calendar-III/Readme.md index 3bd3d1cd3..e91eecae4 100644 --- a/Others/732.My-Calendar-III/Readme.md +++ b/Others/732.My-Calendar-III/Readme.md @@ -1,6 +1,6 @@ ### 732.My-Calendar-III -典型的扫描线算法。 +本题和253一模一样。典型的扫描线算法。 我们用一个按key有序的Map。每次调用book函数时,我们就操作```Map[start]+=1```和```Map[end]-=1```。然后遍历这个Map的key,按照时间轴的顺序累加差分值,即遇到1就加一,遇到-1就减一。这样就得到每个时刻有多少并行的会议。最终输出其中的最大值。 From 4674eea93c4d46d133e8192d91f061623b2581e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 17:54:27 -0700 Subject: [PATCH 0766/2729] Create 2272.Substring-With-Largest-Variance.cpp --- .../2272.Substring-With-Largest-Variance.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance.cpp diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance.cpp b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance.cpp new file mode 100644 index 000000000..7b91e9785 --- /dev/null +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + int largestVariance(string s) + { + vectorcount(26,0); + for (auto x: s) + count[x-'a']++; + + int ret = 0; + int n = s.size(); + for (int i=0; i<26; i++) + for (int j=0; j<26; j++) + { + if (i==j) continue; + if (count[i]==0 || count[j]==0) continue; + vectorarr(n, 0); + for (int k=0; k&nums) + { + int n = nums.size(); + vectordp(n); + int curSum = 0; + + for (int i = 0; i < n; i++) + { + curSum = max(curSum+nums[i], nums[i]); + dp[i] = curSum; + } + + curSum = 0; + int ret = 0; + for (int i=n-1; i>=0; i--) + { + curSum = max(curSum+nums[i], nums[i]); + if (nums[i]==-1) + ret = max(ret, curSum + dp[i] - nums[i]); + } + return ret; + } +}; From 1c66e00e15f162d94c79c74e102bc9c264937350 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 17:58:08 -0700 Subject: [PATCH 0767/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d4f5d6b98..fe01b0db3 100644 --- a/Readme.md +++ b/Readme.md @@ -609,6 +609,7 @@ [2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H) [2189.Number-of-Ways-to-Build-House-of-Cards](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards) (H-) [2218.Maximum-Value-of-K-Coins-From-Piles](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles) (H-) +[2272.Substring-With-Largest-Variance](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2272.Substring-With-Largest-Variance) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From af821e345ace1e2bf18e22c75bd18932745c8a04 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 18:08:47 -0700 Subject: [PATCH 0768/2729] Create Readme.md --- .../2272.Substring-With-Largest-Variance/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md new file mode 100644 index 000000000..7b3f197d3 --- /dev/null +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md @@ -0,0 +1,7 @@ +### 2272.Substring-With-Largest-Variance + +本题的突破口是数据范围n=1e4.这是一个比较奇怪的数字。通常来说如果允许nlogn的复杂度,那么n可以达到1e5;类似的,如果是n^2的复杂度,那么n大概就是1000. 在这里,很可能是一个大概是存在100的常数k,使得复杂度的限制在o(kn)。于是我们大概可以猜到,这个k就是跟26或者26^2相关,也就是英文字母的个数。 + +于是我们就想到了穷举本题中的最大频次字符x和最小频次字母y。这样的话,我们需要在原字符串里面找一个滑窗,使得x的频次与y的频次之差最大,而其他字母都没有任何作用。这就联想到,如果将x的字符都替换为1,y的字符都替换为-1,其他字符都替换为0,那么不就是变成了寻找```max subarray sum```的题目了吗? + +但是注意,这里有一点不同,根据题意,我们想要找的subarray必须至少包含一个-1. 传统的kadane算法,我们很有可能找出只有+1的subarray。那么怎么办呢?我们可以找那个-1为突破口。根据Kadane的思想,我们找到以每个元素为结尾的最大subarray sum记做dp1[i],那么反过来走一遍就可以得到以每个元素为开头的最大subarray sum记做dp2[i]。那么我们再遍历所有的-1元素i,那么dp1[i]+dp2[i]-nums[i]必然是包含了至少一个-1的max subarray sum。我们再全局找一个最大值即可。 From 63cba9294ccd602e21c400f1ae69f67f6691a419 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 18:39:05 -0700 Subject: [PATCH 0769/2729] Update Readme.md --- Readme.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index fe01b0db3..e91adede2 100644 --- a/Readme.md +++ b/Readme.md @@ -578,9 +578,7 @@ [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [1277.Count-Square-Submatrices-with-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1277.Count-Square-Submatrices-with-All-Ones) (M+) [600.Non-negative-Integers-without-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/600.Non-negative-Integers-without-Consecutive-Ones) (H) -[656.Coin-Path](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/656.Coin-Path) (H-) -[053.Maximum-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/053.Maximum-Subarray) (E+) -[152.Maximum-Product-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/152.Maximum-Product-Subarray) (M+) +[656.Coin-Path](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/656.Coin-Path) (H-) [818.Race-Car](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/818.Race-Car) (H) [377.Combination-Sum-IV](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/377.Combination-Sum-IV) (M) [837.New-21-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/837.New-21-Game) (H-) @@ -609,7 +607,6 @@ [2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H) [2189.Number-of-Ways-to-Build-House-of-Cards](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards) (H-) [2218.Maximum-Value-of-K-Coins-From-Piles](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles) (H-) -[2272.Substring-With-Largest-Variance](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2272.Substring-With-Largest-Variance) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) @@ -764,6 +761,10 @@ [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) * ``Infer future from current`` [2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) +* ``max subarray`` +[053.Maximum-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/053.Maximum-Subarray) (E+) +[152.Maximum-Product-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/152.Maximum-Product-Subarray) (M+) +[2272.Substring-With-Largest-Variance](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2272.Substring-With-Largest-Variance) (H-) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From ed7bc1ec4d881017c7403794eb812ea32412dcb8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 20:41:51 -0700 Subject: [PATCH 0770/2729] Update 493.Reverse-Pairs_v1.cpp --- .../493.Reverse-Pairs_v1.cpp | 62 ++++++++++--------- 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/Divide_Conquer/493.Reverse-Pairs/493.Reverse-Pairs_v1.cpp b/Divide_Conquer/493.Reverse-Pairs/493.Reverse-Pairs_v1.cpp index 0131dfb07..19ac47544 100644 --- a/Divide_Conquer/493.Reverse-Pairs/493.Reverse-Pairs_v1.cpp +++ b/Divide_Conquer/493.Reverse-Pairs/493.Reverse-Pairs_v1.cpp @@ -21,36 +21,38 @@ class Solution { auto iter = upper_bound(sorted.begin()+a, sorted.begin()+mid+1, 2*(long)nums[j]); ret += sorted.begin()+mid+1 - iter; } - // sort(sorted.begin()+a, sorted.begin()+b+1); - int i=a, j=mid+1, p = 0; - while (i<=mid && j<=b) - { - if (sorted[i]<=sorted[j]) - { - temp[p] = sorted[i]; - i++; - } - else - { - temp[p] = sorted[j]; - j++; - } - p++; - } - while (i<=mid) - { - temp[p] = sorted[i]; - i++; - p++; - } - while (j<=b) - { - temp[p] = sorted[j]; - j++; - p++; - } - for (int i=0; i Date: Sat, 14 May 2022 23:41:35 -0700 Subject: [PATCH 0771/2729] Create 2272.Substring-With-Largest-Variance_v2.cpp --- ...272.Substring-With-Largest-Variance_v2.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp new file mode 100644 index 000000000..9180ed22d --- /dev/null +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + int largestVariance(string s) + { + vectorcount(26,0); + for (auto x: s) + count[x-'a']++; + + int ret = 0; + int n = s.size(); + for (int i=0; i<26; i++) + for (int j=0; j<26; j++) + { + if (i==j) continue; + if (count[i]==0 || count[j]==0) continue; + vectorarr(n, 0); + for (int k=0; k&nums) + { + int n = nums.size(); + int curSum0 = 0; + int curSum1 = INT_MIN/2; + int ret = 0; + + for (int i = 0; i < n; i++) + { + if (nums[i]==1) + { + curSum1 = curSum1+nums[i]; + curSum0 = max(curSum0+nums[i], nums[i]); + } + else if (nums[i] == -1) + { + curSum1 = max(nums[i], max(curSum0, curSum1)+nums[i]); + curSum0 = 0; + } + + ret = max(ret, curSum1); + } + + return ret; + } +}; From c3ede06398a10c795d316ab1a519e499f81e9bd0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 23:44:22 -0700 Subject: [PATCH 0772/2729] Update Readme.md --- .../Readme.md | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md index 7b3f197d3..a6723c0a2 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md @@ -4,4 +4,28 @@ 于是我们就想到了穷举本题中的最大频次字符x和最小频次字母y。这样的话,我们需要在原字符串里面找一个滑窗,使得x的频次与y的频次之差最大,而其他字母都没有任何作用。这就联想到,如果将x的字符都替换为1,y的字符都替换为-1,其他字符都替换为0,那么不就是变成了寻找```max subarray sum```的题目了吗? -但是注意,这里有一点不同,根据题意,我们想要找的subarray必须至少包含一个-1. 传统的kadane算法,我们很有可能找出只有+1的subarray。那么怎么办呢?我们可以找那个-1为突破口。根据Kadane的思想,我们找到以每个元素为结尾的最大subarray sum记做dp1[i],那么反过来走一遍就可以得到以每个元素为开头的最大subarray sum记做dp2[i]。那么我们再遍历所有的-1元素i,那么dp1[i]+dp2[i]-nums[i]必然是包含了至少一个-1的max subarray sum。我们再全局找一个最大值即可。 +但是注意,这里有一点不同,根据题意,我们想要找的subarray必须至少包含一个-1. 传统的kadane算法,我们很有可能找出只有+1的subarray。那么怎么办呢?有两种方法。 + +#### 解法1 +我们可以找那个-1为突破口。根据Kadane的思想,我们找到以每个元素为结尾的最大subarray sum记做dp1[i],那么反过来走一遍就可以得到以每个元素为开头的最大subarray sum记做dp2[i]。那么我们再遍历所有的-1元素i,那么dp1[i]+dp2[i]-nums[i]必然是包含了至少一个-1的max subarray sum。我们再全局找一个最大值即可。 + +#### 解法2 +我们依然按照kadane算法的思路,但是设置两个临时变量curSum0表示以当前元素为结尾、不包含-1的最大subarray sum,另外用curSum1表示以当前元素为结尾、已经包含-1的最大subarray sum。转移方程如下: +```cpp + for (int i = 0; i < n; i++) + { + if (nums[i] == 1) + { + curSum1 = curSum1+nums[i]; + curSum0 = max(curSum0+nums[i], nums[i]); + } + else if (nums[i] == -1) + { + curSum1 = max(nums[i], max(curSum0, curSum1)+nums[i]); + curSum0 = 0; + } + + ret = max(ret, curSum1); + } +``` +特别注意,curSum0的初始值可以是0,但是curSum1的初始值必须设置为INT_MIN. From e22071ec7dd8addb957945b8c1d8edd10bc40112 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 May 2022 23:46:28 -0700 Subject: [PATCH 0773/2729] Update Readme.md --- .../2272.Substring-With-Largest-Variance/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md index a6723c0a2..fcfaa211b 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md @@ -10,7 +10,7 @@ 我们可以找那个-1为突破口。根据Kadane的思想,我们找到以每个元素为结尾的最大subarray sum记做dp1[i],那么反过来走一遍就可以得到以每个元素为开头的最大subarray sum记做dp2[i]。那么我们再遍历所有的-1元素i,那么dp1[i]+dp2[i]-nums[i]必然是包含了至少一个-1的max subarray sum。我们再全局找一个最大值即可。 #### 解法2 -我们依然按照kadane算法的思路,但是设置两个临时变量curSum0表示以当前元素为结尾、不包含-1的最大subarray sum,另外用curSum1表示以当前元素为结尾、已经包含-1的最大subarray sum。转移方程如下: +我们依然按照kadane算法的思路,但是设置两个临时变量:curSum0表示以当前元素为结尾、不包含-1的最大subarray sum,另外用curSum1表示以当前元素为结尾、已经包含-1的最大subarray sum。转移方程如下: ```cpp for (int i = 0; i < n; i++) { @@ -21,8 +21,8 @@ } else if (nums[i] == -1) { - curSum1 = max(nums[i], max(curSum0, curSum1)+nums[i]); - curSum0 = 0; + curSum1 = max(nums[i], max(curSum0, curSum1)+nums[i]); // 三种情况可以转移到新的curSum1 + curSum0 = 0; // 因为nums[i]是-1,curSum0没有意义,只能置零 } ret = max(ret, curSum1); From 91f879aa9965da37db745a239524b7e9faadadee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 00:39:33 -0700 Subject: [PATCH 0774/2729] Create 2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp --- ...aximum-White-Tiles-Covered-by-a-Carpet.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp diff --git a/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp b/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp new file mode 100644 index 000000000..36b4f7ca4 --- /dev/null +++ b/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp @@ -0,0 +1,26 @@ +class Solution { + vectorpresum; +public: + int maximumWhiteTiles(vector>& tiles, int carpetLen) + { + sort(tiles.begin(), tiles.end()); + int n = tiles.size(); + presum.resize(n); + for (int i=0; i= tiles[j][1]) + j++; + int len = presum[j-1] - (i==0?0:presum[i-1]); + if (j Date: Sun, 15 May 2022 00:40:04 -0700 Subject: [PATCH 0775/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e91adede2..8ce955e2c 100644 --- a/Readme.md +++ b/Readme.md @@ -1081,6 +1081,7 @@ [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) +[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 54578182e39a19ba5142afee64dc2cb4d8ded540 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 00:57:54 -0700 Subject: [PATCH 0776/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/Readme.md diff --git a/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/Readme.md b/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/Readme.md new file mode 100644 index 000000000..8b85a0e52 --- /dev/null +++ b/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/Readme.md @@ -0,0 +1,15 @@ +### 2271.Maximum-White-Tiles-Covered-by-a-Carpet + +本题有非常直观的一种方案。我们放毯子,必然会把毯子的左边界和某一段tile的左边界对齐,以最大化毯子的覆盖(或者说最小化毯子的浪费)。假想我们把毯子的左边界与某tile的中段对齐,直觉上我们不妨将毯子再往左边拉一拉:这个过程中我们本质上,挪用了一部分毯子右侧的空间来覆盖了左边一部分瓷砖,而这个操作肯定是不亏的,甚至还可能赚(因为毯子右侧有可能覆盖的是空隙)。 + +所以本题我们只要逐一考察毯子的左边界应该对齐哪个tile的左边界即可。在这个过程中,毯子的右边界的位置自然也是单调递增的。所以本题就是维护一个双指针的滑窗。 + +假设毯子的左边界对应的是tiles[i][0],那么我们向右移动指针j来定位毯子右边界解出的是哪个tile,直至```tiles[i][0]+carpetLen-1 < tiles[j][1]```。如图 +``` +carpet ____________________________ + tiles _____ ________ ________ _______ + i j +``` +此时tiles[i: j-1]这部分的瓷砖是完全被覆盖的,我们可以用前缀和之差来计算这些tiles的瓷砖总数。另外我们需要计算第j个tile被额外覆盖了多少,这也容易得到:```tiles[i][0]+carpetLen-1 - tiles[j][0] + 1```. 两部分相加就是地毯在这个位置的覆盖面积。 + +随着地毯移动n次,取全局的最大值即可。 From cc1fd3d1b92c342d0691e822439c1d96e401ce1d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 16:06:14 -0700 Subject: [PATCH 0777/2729] Create 2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero.cpp --- ...tion-With-Bitwise-AND-Greater-Than-Zero.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero.cpp diff --git a/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero.cpp b/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero.cpp new file mode 100644 index 000000000..1ba06cb5e --- /dev/null +++ b/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int largestCombination(vector& candidates) + { + int ret = 0; + for (int i=0; i<31; i++) + { + int count = 0; + for (int x: candidates) + { + if ((x>>i)&1) + count++; + } + ret = max(ret, count); + } + return ret; + } +}; From b4faf372b6fb3df264108f089c0a874b54ff55fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 16:06:42 -0700 Subject: [PATCH 0778/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8ce955e2c..40e48bbd0 100644 --- a/Readme.md +++ b/Readme.md @@ -1082,6 +1082,7 @@ [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) +[2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From f2d87dd927437a56b9871299d4de708c31c1f6ad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 17:14:54 -0700 Subject: [PATCH 0779/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/Readme.md diff --git a/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/Readme.md b/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/Readme.md new file mode 100644 index 000000000..56f6d44c1 --- /dev/null +++ b/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero/Readme.md @@ -0,0 +1,5 @@ +### 2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero + +将若干个数Bitwise AND之后的结果S如果不为零,说明S至少有一个bit位不为零,也就是说所有的数在该bit位上不能有0存在。于是我们可以检查每个bit,统计有多少元素在该bit位上非零。假设有M个元素在某个二进制位上都是1,那么他们的AND结果必然就不是零。 + +显然,对于32bit的整形,我们检查每个位置之后,可以找到这样一个最大的M。但M是否是最终的答案呢,有没有可能更多呢?答案是否定的。如果有M+1个元素的AND结果非零,必然有一个bit位上该M+1个元素都非零。这和之前的假设“M是所有bit位上我们找到的非零元素最多的那个”相矛盾。 From 646a39953fe3bb755b036fa4066c4974f69fb71c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 18:15:29 -0700 Subject: [PATCH 0780/2729] Create 2276.Count-Integers-in-Intervals.cpp --- .../2276.Count-Integers-in-Intervals.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Heap/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp diff --git a/Heap/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp b/Heap/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp new file mode 100644 index 000000000..603350629 --- /dev/null +++ b/Heap/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp @@ -0,0 +1,52 @@ +class CountIntervals { + mapMap; + int ret = 0; +public: + CountIntervals() { + + } + + void add(int left, int right) + { + unordered_settemp; + + int start = left; + auto iter = Map.lower_bound(left); + if (iter!=Map.begin() && prev(iter)->second>=start) + { + iter = prev(iter); + temp.insert(iter->first); + start = min(start, iter->first); + } + + int end = right; + iter = Map.lower_bound(left); + if (iter!=Map.begin()) + end = max(end, prev(iter)->second); + while (iter!=Map.end() && iter->first<=end) + { + temp.insert(iter->first); + end = max(end, iter->second); + iter = next(iter); + } + + for (int x: temp) + { + ret -= Map[x]-x+1; + Map.erase(x); + } + ret += end-start+1; + Map[start] = end; + } + + int count() { + return ret; + } +}; + +/** + * Your CountIntervals object will be instantiated and called as such: + * CountIntervals* obj = new CountIntervals(); + * obj->add(left,right); + * int param_2 = obj->count(); + */ From 2d20c78e73496180c59ba316fc87e81f40fcc853 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 18:16:39 -0700 Subject: [PATCH 0781/2729] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 40e48bbd0..d6d3eae3e 100644 --- a/Readme.md +++ b/Readme.md @@ -172,7 +172,6 @@ [480.Sliding-Window-Median](https://github.com/wisdompeak/LeetCode/blob/master/Heap/480.Sliding-Window-Median) (H) [218.The-Skyline-Problem](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/218.The-Skyline-Problem) (H) [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) -[715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [729.My-Calendar-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/729.My-Calendar-I) (M) [855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/855.Exam-Room) (M+) [975.Odd-Even-Jump](https://github.com/wisdompeak/LeetCode/tree/master/Heap/975.Odd-Even-Jump) (H-) @@ -188,7 +187,10 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) +```maintain intervals``` +[715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/new/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) +[2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From 219555d4cab2caf4f3b48b10f7c0ad9dfb97a5fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 18:16:58 -0700 Subject: [PATCH 0782/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d6d3eae3e..5e1635559 100644 --- a/Readme.md +++ b/Readme.md @@ -187,7 +187,7 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) -```maintain intervals``` +```maintain intervals``` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/new/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) [2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) From 677cff4cc6279b8ad3b1efd7b89d741e78ef34b7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 18:17:33 -0700 Subject: [PATCH 0783/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5e1635559..812994031 100644 --- a/Readme.md +++ b/Readme.md @@ -187,7 +187,7 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) -```maintain intervals``` + * ``maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/new/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) [2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) From 0df9bde3e4758b39473ece30108adc878c647771 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 18:18:04 -0700 Subject: [PATCH 0784/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 812994031..8d6344e5a 100644 --- a/Readme.md +++ b/Readme.md @@ -187,7 +187,7 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) - * ``maintain intervals`` +* ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/new/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) [2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) From 8c34a2bb7e6693c4e077296c96cece247008bfce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 18:34:13 -0700 Subject: [PATCH 0785/2729] Create Readme.md --- .../Readme.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Heap/2276.Count-Integers-in-Intervals/Readme.md diff --git a/Heap/2276.Count-Integers-in-Intervals/Readme.md b/Heap/2276.Count-Integers-in-Intervals/Readme.md new file mode 100644 index 000000000..d41546d9c --- /dev/null +++ b/Heap/2276.Count-Integers-in-Intervals/Readme.md @@ -0,0 +1,41 @@ +### 2276.Count-Integers-in-Intervals + +此题的本质就是```715.Range-Module```. 我们常用map来维护互不重叠的区间,其中的key代表了区间的起点(并是有序排列),value表示区间的终点。 + +基本思想:我们维护一个计数器count表示当前有多少整数被记录。每当加入一个新区间,我们需要标记删除哪些旧区间(因为会与新区间重叠或相交),同时在count里减去这些旧区间对应的数字个数。然后加入新区间,同时在count里加上新区间的个数。注意新区间不一定就是[left,right],而是可能与旧区间merge后的大区间。 + +对于一个新区间[left,right],我们首先考虑left左边需要删除哪些旧区间。只有一种情况,就是如果left左边有一个区间与新区间重合的时候。如图 +``` + A B +_________ _____ _________ + __________________ + left right +``` +判定起来也很方便,用```iter = Map.lower_bound(left)```来定位区间B,然后prev(iter)就是区间A。如果A的右边界大于left,那么A区间就要被删除。此时,我们需要注意,之后加入的新区间因为要与A区间merge,它的起点将是```start = A->first```. + +对于一个新区间[left,right]右边需要删除的区间,则可能会有多个。如图 +``` + A B C D +_________ __ ___ _________ + __________________ + left right +``` +我们从B开始,一路向后遍历区间,直至发现D是最后一个左边界与right勾搭上的区间。于是区间B、C、D都会是需要待删除的区间。同理我们需要注意,之后加入的新区间因为要与BCD区间merge,它的终点将是```end = D->second```. 因此我们的代码长得如下: +```cpp +int end = right; +auto iter = Map.lower_bound(left); +while (iter!=Map.end() && iter->first <= end) +{ + end = max(end, iter->second); + iter = next(iter); +} +``` +但是这里有个疏漏,事实上A的右边界可以很靠后,所以初始值的end必须同样要考虑到A->second。所以要添加一行: +```cpp +int end = right; +auto iter = Map.lower_bound(left); +if (iter!=Map.begin()) + end = max(end, prev(iter)->second); +``` + +最终我们将这些标记要删除的区间都从Map里删除,并添加上新的```Map[start] = end```. From 3fa97d95e57f73d69d301651e5207ead54649958 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 22:51:18 -0700 Subject: [PATCH 0786/2729] Create 1893.Check-if-All-the-Integers-in-a-Range-Are-Covered.cpp --- ...ll-the-Integers-in-a-Range-Are-Covered.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered.cpp diff --git a/Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered.cpp b/Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered.cpp new file mode 100644 index 000000000..4cc423a71 --- /dev/null +++ b/Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool isCovered(vector>& ranges, int left, int right) + { + vectordiff(52); + for (auto range:ranges) + { + diff[range[0]]+=1; + diff[range[1]+1]+=-1; + } + + int sum = 0; + for (int i=1; i<=50; i++) + { + sum += diff[i]; + if (i>=left && i<=right && sum==0) + return false; + } + return true; + } +}; From 5e1f37bdad918af22a952792a45e1b65f867eb6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 22:51:44 -0700 Subject: [PATCH 0787/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8d6344e5a..60b9f15e5 100644 --- a/Readme.md +++ b/Readme.md @@ -1232,7 +1232,7 @@ [1589.Maximum-Sum-Obtained-of-Any-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Others/1589.Maximum-Sum-Obtained-of-Any-Permutation) (M) [1674.Minimum-Moves-to-Make-Array-Complementary](https://github.com/wisdompeak/LeetCode/tree/master/Others/1674.Minimum-Moves-to-Make-Array-Complementary) (H) [1871.Jump-Game-VII](https://github.com/wisdompeak/LeetCode/tree/master/Others/1871.Jump-Game-VII) (M+) -1893.Check if All the Integers in a Range Are Covered (E) +[1893.Check-if-All-the-Integers-in-a-Range-Are-Covered](https://github.com/wisdompeak/LeetCode/tree/master/Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered) (E) [1943.Describe-the-Painting](https://github.com/wisdompeak/LeetCode/tree/master/Others/1943.Describe-the-Painting) (H-) [2015.Average-Height-of-Buildings-in-Each-Segment](https://github.com/wisdompeak/LeetCode/tree/master/Others/2015.Average-Height-of-Buildings-in-Each-Segment) (H-) [2158.Amount-of-New-Area-Painted-Each-Day](https://github.com/wisdompeak/LeetCode/tree/master/Others/2158.Amount-of-New-Area-Painted-Each-Day) (H-) From 8619c6d0746cae1d8359d3e439dcf0a876605096 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 May 2022 22:56:07 -0700 Subject: [PATCH 0788/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered/Readme.md diff --git a/Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered/Readme.md b/Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered/Readme.md new file mode 100644 index 000000000..c797b73f7 --- /dev/null +++ b/Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered/Readme.md @@ -0,0 +1,5 @@ +### 1893.Check-if-All-the-Integers-in-a-Range-Are-Covered + +本题的数据范围非常小,每个数字的数值只在[1,50]之间,因为我们在数轴的[1,50]范围内用差分数组/扫描线来做。对于任何区间[a,b]的两个端点,我们标记差分信息:即在数轴上的a位置标记+1,在b+1位置标记-1,这样做积分的时候,就相当于只在区间[a,b]被抬升了1. + +最终我们只要考察积分曲线在[left,right]是否有任意一点的值为0.是的话返回false,否则返回true。 From dccf2d99296add4e36c15cdf4eaf92ad4c232b83 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 May 2022 22:49:08 -0700 Subject: [PATCH 0789/2729] Update Readme.md --- DFS/1192.Critical-Connections-in-a-Network/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DFS/1192.Critical-Connections-in-a-Network/Readme.md b/DFS/1192.Critical-Connections-in-a-Network/Readme.md index 64537cb6b..94a2c7e37 100644 --- a/DFS/1192.Critical-Connections-in-a-Network/Readme.md +++ b/DFS/1192.Critical-Connections-in-a-Network/Readme.md @@ -6,11 +6,11 @@ 简单地说,我们可以以任意一个未访问过的节点作为根节点,用DFS的顺序来进行搜索,即永远深度优先,然后回溯再搜索其他分支。如果碰到访问过的节点,就停止,保证不行成环。 -我们在dfs的过程中维护两个数组,一个是dfs[u],表示节点u被第一次访问时的顺序(可以理解为时间戳),这个是唯一且不变的量。另一个数组low[u]比较关键,初始的时候```low[u]=dfn[u]```。我们以u为节点的开始dfs(注意抵达u之前可能还有u的父节点,但我们dfs的时候不走回头路),想象它最终形成一棵搜索树,那么u的所有子节点中止的条件不外乎有两个:一个是走进了死胡同;另一个就是遇到了已经访问过的节点,特别的,这个已经访问过的节点有可能是u的祖先节点!所以,有了这样的搜索树之后,low[u]可以有机会更新为它所有的子节点v可以接触到的最小时间戳low[v]。 +我们在dfs的过程中维护两个数组,一个是dfn[u],表示节点u被第一次访问时的顺序(可以理解为时间戳),这个是唯一且不变的量。另一个数组low[u]比较关键,初始的时候```low[u]=dfn[u]```。我们以u为节点的开始dfs(注意抵达u之前可能还有u的父节点,但我们dfs的时候不走回头路),想象它最终形成一棵搜索树,那么u的所有子节点中止的条件不外乎有两个:一个是走进了死胡同;另一个就是遇到了已经访问过的节点,特别的,这个已经访问过的节点有可能是u的祖先节点!所以,有了这样的搜索树之后,low[u]可以有机会更新为它所有的子节点v可以接触到的最小时间戳low[v]。 令v是u的一个子节点,且有```low[v]>dfn[u]```,这说明什么呢?说明从v出发最终无法绕道u的前面去。因此(v,u)就是割边。如果消除了这条边,v及其子树就是一个孤岛,无法与u或u的祖先相通。同理,如果```low[v]>=dfn[u]```,说明u是一个割点,如果消除了这个点,那么v及其子树也是一个孤岛。 本题中我们还设置了一个parent,其实是为了标记dfs过程中的搜索顺序。因为无向图```for auto v: next[u]```的遍历过程中,v可能是u的父节点,这种情况下v其实不能作为从u开始dfs的下一个目的地(否则就是走回头路了),所以得排除。 -[Leetcode Link](https://leetcode.com/problems/critical-connections-in-a-network) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/critical-connections-in-a-network) From 0626bc0ca65035e707a31a90c7f6c24fcb0bdd57 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 May 2022 23:21:05 -0700 Subject: [PATCH 0790/2729] Update 351.Android-Unlock-Patterns.cpp --- .../351.Android-Unlock-Patterns.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/DFS/351.Android-Unlock-Patterns/351.Android-Unlock-Patterns.cpp b/DFS/351.Android-Unlock-Patterns/351.Android-Unlock-Patterns.cpp index 040ab40e3..78a9af0d7 100644 --- a/DFS/351.Android-Unlock-Patterns/351.Android-Unlock-Patterns.cpp +++ b/DFS/351.Android-Unlock-Patterns/351.Android-Unlock-Patterns.cpp @@ -1,26 +1,26 @@ class Solution { int count = 0; int m,n; + int visited[3][3]; + vector>dir = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{-1,1},{1,-1},{-1,-1},{-1,2},{1,2},{-2,1},{2,1},{-1,-2},{1,-2},{-2,-1},{2,-1}}; public: int numberOfPatterns(int m, int n) { this->m = m; this->n = n; - auto visited = vector>(3, vector(3,0)); - + for (int i=0; i<3; i++) for (int j=0; j<3; j++) { visited[i][j] = 1; - dfs(i,j,1,visited); + dfs(i,j,1); visited[i][j] = 0; } return count; } - void dfs(int x, int y, int r, vector>&visited) - { - auto dir = vector>({{1,0},{-1,0},{0,1},{0,-1},{1,1},{-1,1},{1,-1},{-1,-1},{-1,2},{1,2},{-2,1},{2,1},{-1,-2},{1,-2},{-2,-1},{2,-1}}); + void dfs(int x, int y, int r) + { if (r>=m && r<=n) count++; if (r>n) return; @@ -34,7 +34,7 @@ class Solution { if (visited[i][j] == 0) { visited[i][j] = 1; - dfs(i,j,r+1,visited); + dfs(i,j,r+1); visited[i][j] = 0; } else @@ -45,7 +45,7 @@ class Solution { continue; if (visited[i][j]==1) continue; visited[i][j] = 1; - dfs(i,j,r+1,visited); + dfs(i,j,r+1); visited[i][j] = 0; } } From 7b1f1524be03853f6da881a1e62da0c6352c4e38 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 18 May 2022 23:11:49 -0700 Subject: [PATCH 0791/2729] Update 2015.Average-Height-of-Buildings-in-Each-Segment.cpp --- ...ge-Height-of-Buildings-in-Each-Segment.cpp | 45 +++++++------------ 1 file changed, 15 insertions(+), 30 deletions(-) diff --git a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp index 28700cdd3..e88dadf1a 100644 --- a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp +++ b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp @@ -2,42 +2,27 @@ class Solution { public: vector> averageHeightOfBuildings(vector>& buildings) { - vector>p; + map>Map; // pos=>{sum, count} for (auto build: buildings) { int start = build[0], end = build[1], height = build[2]; - p.push_back({start, height}); - p.push_back({end, -height}); - } + Map[start].first += height; + Map[start].second += 1; + Map[end].first -= height; + Map[end].second -= 1; + } - sort(p.begin(), p.end()); - int count = 0; int sum = 0; - - vector>temp; - for (int i=0; i>temp; + for (auto& [pos, kv]: Map) { - int j = i; - while (j>rets; for (int i=0; i Date: Wed, 18 May 2022 23:20:56 -0700 Subject: [PATCH 0792/2729] Update Readme.md --- .../Readme.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md index 7bd96cafc..b576fd416 100644 --- a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md +++ b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/Readme.md @@ -1,9 +1,7 @@ ### 2015.Average-Height-of-Buildings-in-Each-Segment -对于给出若干个区间、涉及到区间合并的问题,扫描线是比较自然的想法。 +本题显然是扫描线的解法。我们只关心那些建筑两边的边缘线位置。对于每处边界,要么增加一幢楼:楼的总高度和楼的总数量都会变大;要么减少一幢楼:楼的总高度和楼的总数量都会变小。所以本题在每处边界,需要考虑两个差分量:分别反映楼的总高度的变化heightDiff,和当前楼的数量的变化countDiff。 -我们只关注那些建筑两边的边缘线位置。将所有的边缘线按照位置从小到大排序之后,我们逐个遍历一遍。维护一个集合,遇到左边缘就插入h,遇到右边缘就删除h。于是,我们在每一个边缘线位置pos,都可以通过当前集合得到一个平均值avg,这意味着从pos往右直至下一个边缘线位置pos2,中间这部分区间[pos, pos2]就是一个输出恒为avg的线段。 +因为同一处位置可能是多幢楼的边界,我们先用map,将同一处位置的这两个差分量做累积。然后按照位置排序后,用积分走一遍得到当前的height和count,就可以得到每个区段的平均值。 -我们将这些琐碎的线段收集起来,合并输出相同的线段,并且剔除输出为0的线段,这剩余的这些线段就是答案。 - -另外,事实上我们不需要真正维护一个multiset。我们只关心集合的sum和count,因此用两个变量即可。 +最后记得要把相邻的、平均值相等的区间要合并。平均值为零的区间也要舍弃。 From cfdfb667a34e7aeaa9c121e92242ba43637c1cbb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 19 May 2022 01:01:50 -0700 Subject: [PATCH 0793/2729] Update 2015.Average-Height-of-Buildings-in-Each-Segment.cpp --- ...ge-Height-of-Buildings-in-Each-Segment.cpp | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp index e88dadf1a..a0c551970 100644 --- a/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp +++ b/Others/2015.Average-Height-of-Buildings-in-Each-Segment/2015.Average-Height-of-Buildings-in-Each-Segment.cpp @@ -2,39 +2,38 @@ class Solution { public: vector> averageHeightOfBuildings(vector>& buildings) { - map>Map; // pos=>{sum, count} + map>Map; // pos -> {diffHeight, diffCount} for (auto build: buildings) { - int start = build[0], end = build[1], height = build[2]; - Map[start].first += height; - Map[start].second += 1; - Map[end].first -= height; - Map[end].second -= 1; - } + int s = build[0], e = build[1], h = build[2]; + Map[s].first += h; + Map[s].second += 1; + Map[e].first -= h; + Map[e].second -= 1; + } - int sum = 0; - int count = 0; - vector>temp; + vector>seg; + int totalHeight = 0, totalCount = 0; for (auto& [pos, kv]: Map) { - int heightDiff = kv.first, countDiff = kv.second; - sum += heightDiff; - count += countDiff; - int avg = (count==0 ? 0 : sum / count); - temp.push_back({pos, avg}); - } + int diffHeight = kv.first, diffCount = kv.second; + totalHeight += diffHeight; + totalCount += diffCount; + int avg = (totalCount ==0 ? 0: totalHeight / totalCount); + seg.push_back({pos, avg}); + } vector>rets; - for (int i=0; i Date: Fri, 20 May 2022 05:04:09 -0700 Subject: [PATCH 0794/2729] Update 2158.Amount-of-New-Area-Painted-Each-Day.cpp --- ...58.Amount-of-New-Area-Painted-Each-Day.cpp | 36 +++++++++---------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/Others/2158.Amount-of-New-Area-Painted-Each-Day/2158.Amount-of-New-Area-Painted-Each-Day.cpp b/Others/2158.Amount-of-New-Area-Painted-Each-Day/2158.Amount-of-New-Area-Painted-Each-Day.cpp index 3190ac4a9..73922b6bf 100644 --- a/Others/2158.Amount-of-New-Area-Painted-Each-Day/2158.Amount-of-New-Area-Painted-Each-Day.cpp +++ b/Others/2158.Amount-of-New-Area-Painted-Each-Day/2158.Amount-of-New-Area-Painted-Each-Day.cpp @@ -1,36 +1,34 @@ -using AI3 = array; class Solution { public: vector amountPainted(vector>& paint) { - vectorarr; + map>>Map; // pos->{idx, flag} for (int i=0; i>>>array(Map.begin(), Map.end()); setSet; int n = paint.size(); - vectorrets(n); - for (int i=0; irets(n); + for (int i=0; i Date: Fri, 20 May 2022 23:00:57 -0700 Subject: [PATCH 0795/2729] Update Readme.md --- Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md b/Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md index 69b400739..ccdb904be 100644 --- a/Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md +++ b/Others/2158.Amount-of-New-Area-Painted-Each-Day/Readme.md @@ -1,6 +1,6 @@ ### 2158.Amount-of-New-Area-Painted-Each-Day -此题是扫描线一例非常特别的应用。 +此题其实类似于```218. The Skyline Problem```的扫描线解法。 通常的扫描线算法跟踪的是每个分割区间的重叠数目(比如说这一段区间有三条线段重叠,下一个区间有两条线段重叠),但本题跟踪的是每个区间的重叠信息。我们可以用于扫描线一样的算法,用一个有序集合来跟踪在每个分割区间内,有哪些线段在此重叠:如果是线段开头就加入,如果是线段结尾就删除。显然,编号最小的线段最先拥有这个区间的打印权,故把这段分割区间的长度记在这条线段上即可。 From 3a30051745f4bd76b27511bab08c4e0997dfc433 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 20 May 2022 23:33:14 -0700 Subject: [PATCH 0796/2729] Create 930.Binary-Subarrays-With-Sum_v2.cpp --- .../930.Binary-Subarrays-With-Sum_v2.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Hash/930.Binary-Subarrays-With-Sum/930.Binary-Subarrays-With-Sum_v2.cpp diff --git a/Hash/930.Binary-Subarrays-With-Sum/930.Binary-Subarrays-With-Sum_v2.cpp b/Hash/930.Binary-Subarrays-With-Sum/930.Binary-Subarrays-With-Sum_v2.cpp new file mode 100644 index 000000000..78bd1e41c --- /dev/null +++ b/Hash/930.Binary-Subarrays-With-Sum/930.Binary-Subarrays-With-Sum_v2.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int numSubarraysWithSum(vector& A, int S) + { + int n = A.size(); + vectorpostZeros(n); + int count = 0; + for (int i=n-1; i>=0; i--) + { + postZeros[i] = count; + if (A[i]==0) + count++; + else + count = 0; + } + + int j = 0, sum = 0; + int ret = 0; + for (int i=0; i Date: Fri, 20 May 2022 23:33:44 -0700 Subject: [PATCH 0797/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 60b9f15e5..a3dbab027 100644 --- a/Readme.md +++ b/Readme.md @@ -34,6 +34,7 @@ * ``Sliding window`` [532.K-diff-Pairs-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/532.K-diff-Pairs-in-an-Array) (H-) [611.Valid-Triangle-Number](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/611.Valid-Triangle-Number) (M+) +[930.Binary-Subarrays-With-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/930.Binary-Subarrays-With-Sum) (M+) [1004.Max-Consecutive-Ones-III](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1004.Max-Consecutive-Ones-III) (M) [1052.Grumpy-Bookstore-Owner](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1052.Grumpy-Bookstore-Owner) (M) [1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) From 74d918afd8d3d7f4ef9646ee7be7358c4ac0f575 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 20 May 2022 23:51:21 -0700 Subject: [PATCH 0798/2729] Update Readme.md --- Hash/930.Binary-Subarrays-With-Sum/Readme.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Hash/930.Binary-Subarrays-With-Sum/Readme.md b/Hash/930.Binary-Subarrays-With-Sum/Readme.md index 2040be321..0196f2370 100644 --- a/Hash/930.Binary-Subarrays-With-Sum/Readme.md +++ b/Hash/930.Binary-Subarrays-With-Sum/Readme.md @@ -1,6 +1,6 @@ ### 930.Binary-Subarrays-With-Sum -此题是考察对Hash+prefix的常见组合。 +#### 解法1:Hash+prefix 我们遍历每一个元素j,考察以j为结尾、满足条件的subarray,这样的起点i可以在哪里?如果满足条件的起点i有多种可能,那么答案就可以累加上这么多数量. @@ -9,4 +9,11 @@ ret += Map[prefix[j] - S] ``` +#### 解法2:Sliding Window +遍历左边界左边界。假设左边界为i,那么可以向右单调移动j直至滑窗内的元素和恰好为S。此时如果知道j右边有k个连续的0,那么就意味着以i为左边界、元素和是S的滑窗就有k+1个。 + +对于每个元素,它后面有多少个连续的0,可以提前预处理得到的。 + +因为i和j都是单调移动的,所以时间复杂度是o(N). + [Leetcode Link](https://leetcode.com/problems/binary-subarrays-with-sum) From 416f6d1e559c9aafd5b3d4db9c6ba85c3c39c859 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 May 2022 00:40:40 -0700 Subject: [PATCH 0799/2729] Update 218.The-Skyline-Problem.cpp --- .../218.The-Skyline-Problem.cpp | 44 +++++++++---------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem.cpp b/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem.cpp index 5c774b5a9..f62cd9504 100644 --- a/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem.cpp +++ b/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem.cpp @@ -1,33 +1,31 @@ class Solution { public: - vector> getSkyline(vector>& buildings) + vector> getSkyline(vector>& buildings) { - vector>edges; - for (int i=0;i>>Map; // pos->{height, flag} + for (auto building: buildings) { - edges.push_back({buildings[i][0],-buildings[i][2]}); - edges.push_back({buildings[i][1],buildings[i][2]}); + Map[building[0]].push_back({building[2], 1}); + Map[building[1]].push_back({building[2], -1}); } - sort(edges.begin(),edges.end()); - - multisetSet={0}; - vector>results; - int cur=0; - - for (int i=0; iSet; + vector>rets; + for (auto& [pos, pairs]: Map) { - if (edges[i][1]<0) - Set.insert(-edges[i][1]); - else - Set.erase(Set.lower_bound(edges[i][1])); - - int H=*Set.rbegin(); - if (cur!=H) - results.push_back({edges[i][0],H}); - cur=H; + for (auto& [height, flag]: pairs) + { + if (flag == 1) + Set.insert(height); + else + Set.erase(Set.find(height)); + } + + int H = Set.empty() ? 0: *Set.rbegin(); + if (rets.empty() || rets.back()[1]!=H) + rets.push_back({pos, H}); } - - return results; + + return rets; } }; From 05186512d124e7e7ede0412f3cca2ae81e51ff39 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 May 2022 00:41:29 -0700 Subject: [PATCH 0800/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a3dbab027..2b1a2f499 100644 --- a/Readme.md +++ b/Readme.md @@ -171,7 +171,6 @@ [363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) [352.Data-Stream-as-Disjoint-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/352.Data-Stream-as-Disjoint-Intervals) (H) [480.Sliding-Window-Median](https://github.com/wisdompeak/LeetCode/blob/master/Heap/480.Sliding-Window-Median) (H) -[218.The-Skyline-Problem](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/218.The-Skyline-Problem) (H) [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) [729.My-Calendar-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/729.My-Calendar-I) (M) [855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/855.Exam-Room) (M+) @@ -1236,6 +1235,7 @@ [1893.Check-if-All-the-Integers-in-a-Range-Are-Covered](https://github.com/wisdompeak/LeetCode/tree/master/Others/1893.Check-if-All-the-Integers-in-a-Range-Are-Covered) (E) [1943.Describe-the-Painting](https://github.com/wisdompeak/LeetCode/tree/master/Others/1943.Describe-the-Painting) (H-) [2015.Average-Height-of-Buildings-in-Each-Segment](https://github.com/wisdompeak/LeetCode/tree/master/Others/2015.Average-Height-of-Buildings-in-Each-Segment) (H-) +[218.The-Skyline-Problem](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/218.The-Skyline-Problem) (H) [2158.Amount-of-New-Area-Painted-Each-Day](https://github.com/wisdompeak/LeetCode/tree/master/Others/2158.Amount-of-New-Area-Painted-Each-Day) (H-) 2237.Count-Positions-on-Street-With-Required-Brightness (M) [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) From bb6a000efd5fb0a069d5ee0d145a46a6bdd19c7b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 May 2022 00:47:36 -0700 Subject: [PATCH 0801/2729] Update Readme.md --- Segment_Tree/218.The-Skyline-Problem/Readme.md | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Segment_Tree/218.The-Skyline-Problem/Readme.md b/Segment_Tree/218.The-Skyline-Problem/Readme.md index 549e31dac..5787ea49c 100644 --- a/Segment_Tree/218.The-Skyline-Problem/Readme.md +++ b/Segment_Tree/218.The-Skyline-Problem/Readme.md @@ -1,16 +1,12 @@ ### 218.The-Skyline-Problem -#### 解法1:有序容器 +#### 解法1:扫描线 -此题需要设置一个multiSet记录所有的当前下降沿的高度,则*prev(Set.end(),1)就是这个Set里的最大值。 +我们维护一个multiset,按照横轴的位置顺次考虑各个楼的上升沿和下降沿。遇到上升沿就往集合里加入一个H,遇到下降沿就在集合里删除一个H。这样每个时刻,集合里面的最大值,就代表了该位置(及其右边区间)的天际线高度。我们将这些```{位置,高度}```记录下来,就代表了天际线的轮廓。 -首先,将所有的edges放入一个数组,按时间顺序排序,然后顺次遍历考虑:如果是上升沿,则在Set里加入对应高度(即添加一个上升沿);如果是下降沿,则需要在Set里删除对应的高度(即退出当前的下降沿)。 +注意,如果相邻两个位置的高度一样,那么我们可以只保留第一个。 -那何时对results进行更新呢?我们在每次处理edge时,不管是加入上升边沿还是退出下降沿之后,都意味着天际线有可能变动。天际线会变成什么呢?答案是此时Set里的最大值!回想一下,Set里装的是所有当前仍未退出的下降沿,说明他们都在当前可以撑起对应的高度。那么Set里的最大值就是当前天际线的最高值。 - -所以每次查看一个edges,我们都要比较当前的高度(用cur记录)和Set里的最大值进行比较:一旦不同,就用Set里的最大值去加入results,同时也要更新cur。 - -有一个细节需要注意,在生成edges数组时,如果某一个位置同时有上升沿也有下降沿,注意要先考察上升沿,再考察下降沿。也就是要先加入一个上升沿,再退出可能的下降沿。否则类似[[0,2,3],[2,5,3]]的测试例子就会有问题。 +类似的题目有```2158.Amount-of-New-Area-Painted-Each-Day```. #### 解法2:线段树 From 322c53ce0ce5aa4a82c33d8317d707d0105960b7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 May 2022 17:07:31 -0700 Subject: [PATCH 0802/2729] Create 2237.Count-Positions-on-Street-With-Required-Brightness.cpp --- ...ons-on-Street-With-Required-Brightness.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Others/2237.Count-Positions-on-Street-With-Required-Brightness/2237.Count-Positions-on-Street-With-Required-Brightness.cpp diff --git a/Others/2237.Count-Positions-on-Street-With-Required-Brightness/2237.Count-Positions-on-Street-With-Required-Brightness.cpp b/Others/2237.Count-Positions-on-Street-With-Required-Brightness/2237.Count-Positions-on-Street-With-Required-Brightness.cpp new file mode 100644 index 000000000..ec7423263 --- /dev/null +++ b/Others/2237.Count-Positions-on-Street-With-Required-Brightness/2237.Count-Positions-on-Street-With-Required-Brightness.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int meetRequirement(int n, vector>& lights, vector& requirement) + { + vectordiff(n+1); + for (int i=0; ibright(n); + int sum = 0; + for (int i=0; i=requirement[i]) + ret++; + } + return ret; + } +}; From 98a3d37e24439956a449ca4b4e5511cb24cc5e4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 May 2022 17:07:55 -0700 Subject: [PATCH 0803/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2b1a2f499..06a354a15 100644 --- a/Readme.md +++ b/Readme.md @@ -1237,7 +1237,7 @@ [2015.Average-Height-of-Buildings-in-Each-Segment](https://github.com/wisdompeak/LeetCode/tree/master/Others/2015.Average-Height-of-Buildings-in-Each-Segment) (H-) [218.The-Skyline-Problem](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/218.The-Skyline-Problem) (H) [2158.Amount-of-New-Area-Painted-Each-Day](https://github.com/wisdompeak/LeetCode/tree/master/Others/2158.Amount-of-New-Area-Painted-Each-Day) (H-) -2237.Count-Positions-on-Street-With-Required-Brightness (M) +[2237.Count-Positions-on-Street-With-Required-Brightness](https://github.com/wisdompeak/LeetCode/tree/master/Others/2237.Count-Positions-on-Street-With-Required-Brightness) (M) [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) From 280e09c9fe2fdf92c163429c3fe68b28c8b6770e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 May 2022 17:11:59 -0700 Subject: [PATCH 0804/2729] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/2237.Count-Positions-on-Street-With-Required-Brightness/Readme.md diff --git a/Others/2237.Count-Positions-on-Street-With-Required-Brightness/Readme.md b/Others/2237.Count-Positions-on-Street-With-Required-Brightness/Readme.md new file mode 100644 index 000000000..456084618 --- /dev/null +++ b/Others/2237.Count-Positions-on-Street-With-Required-Brightness/Readme.md @@ -0,0 +1,3 @@ +### 2237.Count-Positions-on-Street-With-Required-Brightness + +扫描线算法的模板题。假设某盏灯的覆盖范围是[a,b],那么我们就设置差分数组diff[a]+=1和diff[b+1]-=1. 注意因为在b位置处我们是希望计入被灯光覆盖,所以-1的差分应该写在b+1这个地方。 From 240128f687414e76d8f873c2c079eb04fff4881a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 May 2022 17:40:44 -0700 Subject: [PATCH 0805/2729] Create 490.The-Maze.cpp --- BFS/490.The-Maze/490.The-Maze.cpp | 49 +++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 BFS/490.The-Maze/490.The-Maze.cpp diff --git a/BFS/490.The-Maze/490.The-Maze.cpp b/BFS/490.The-Maze/490.The-Maze.cpp new file mode 100644 index 000000000..accdb5d23 --- /dev/null +++ b/BFS/490.The-Maze/490.The-Maze.cpp @@ -0,0 +1,49 @@ +class Solution { + int M,N; + vector> dir = {{1,0},{-1,0},{0,1},{0,-1}}; + +public: + bool hasPath(vector>& maze, vector& start, vector& destination) + { + if (start==destination) return true; + + M = maze.size(); + N = maze[0].size(); + + auto visited=vector>(M,vector(N,0)); + + queue>q; + q.push({start[0],start[1]}); + visited[start[0]][start[1]] = 1; + + while (!q.empty()) + { + int x0 = q.front().first; + int y0 = q.front().second; + q.pop(); + + for (int k=0; k<4; k++) + { + auto [x,y] = nextPos(maze,x0,y0,k); + if (x==destination[0] && y==destination[1]) return true; + if (visited[x][y]==1) continue; + visited[x][y]=1; + q.push({x,y}); + } + } + return false; + } + + pair nextPos(vector>& maze, int x0, int y0, int k) + { + int x = x0, y = y0; + while (x>=0 && x=0 && y Date: Sat, 21 May 2022 17:42:14 -0700 Subject: [PATCH 0806/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 06a354a15..f752629cd 100644 --- a/Readme.md +++ b/Readme.md @@ -461,6 +461,7 @@ [126.Word-Ladder-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/126.Word-Ladder-II) (M+) [130.Surrounded-Regions](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/130.Surrounded-Regions) (H-) [200.Number-of-Islands](https://github.com/wisdompeak/LeetCode/tree/master/DFS/200.Number-of-Islands) (H-) +[490.The-Maze](https://github.com/wisdompeak/LeetCode/tree/master/BFS/490.The-Maze) (M) [529.Minesweeper](https://github.com/wisdompeak/LeetCode/tree/master/BFS/529.Minesweeper) (M+) [637.Average-of-Levels-in-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/BFS/637.Average-of-Levels-in-Binary-Tree) (M) [675.Cut-Off-Trees-for-Golf-Event](https://github.com/wisdompeak/LeetCode/tree/master/BFS/675.Cut-Off-Trees-for-Golf-Event) (M) From 1af2dae394e2723b1f368c30e6ba2867e21934f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 May 2022 17:45:40 -0700 Subject: [PATCH 0807/2729] Create Readme.md --- BFS/490.The-Maze/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 BFS/490.The-Maze/Readme.md diff --git a/BFS/490.The-Maze/Readme.md b/BFS/490.The-Maze/Readme.md new file mode 100644 index 000000000..c0abff1da --- /dev/null +++ b/BFS/490.The-Maze/Readme.md @@ -0,0 +1,3 @@ +### 490.The-Maze + +常规的BFS。只不过以往是“每个回合朝一个方向走一步”,现在是“每个回合朝一个方向走到底”。 From fef2ba8f432a4baf2f4b38f219edb03b43e42a99 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 09:04:16 -0700 Subject: [PATCH 0808/2729] Create 6077.Sum-of-Total-Strength-of-Wizards.cpp --- .../6077.Sum-of-Total-Strength-of-Wizards.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Others/6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp diff --git a/Others/6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp b/Others/6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp new file mode 100644 index 000000000..50efb8071 --- /dev/null +++ b/Others/6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp @@ -0,0 +1,49 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int totalStrength(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + vectorpresum(n+2, 0); + for (int i=1; i<=n; i++) + presum[i] = (presum[i-1]+(LL)nums[i]) % M; + + vectorpresum1(n+2, 0); + for (int i=1; i<=n; i++) + presum1[i] = (presum1[i-1]+(LL)nums[i]*i) % M; + + stackStack; + vectornextSmaller(n+2,n+1); + vectorprevSmaller(n+2,0); + for (int i=1; i<=n; i++) + { + while (!Stack.empty() && nums[Stack.top()]>nums[i]) + { + nextSmaller[Stack.top()] = i; + Stack.pop(); + } + if (!Stack.empty()) + prevSmaller[i] = Stack.top(); + Stack.push(i); + } + + LL ret = 0; + for (int i=1; i<=n; i++) + { + LL a = prevSmaller[i], b = nextSmaller[i]; + LL x = i-a, y = b-i; + LL first = ((presum1[i-1] - presum1[a]) - (presum[i-1] - presum[a]) * a %M + M) % M; + first = first * y % M; + LL second = ((presum[b-1] - presum[i]) * (b-1+1) - (presum1[b-1] - presum1[i]) + M ) % M; + second = second * x % M; + LL mid = (LL)nums[i] * x * y % M; + + ret = (ret +(first + second + mid) * nums[i]) % M; + } + + return ret; + } +}; From afcbc2649636256868b734018316eebe13cd2861 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 09:05:14 -0700 Subject: [PATCH 0809/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index f752629cd..43847c8c4 100644 --- a/Readme.md +++ b/Readme.md @@ -1219,6 +1219,7 @@ [1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) +[6077.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/6077.Sum-of-Total-Strength-of-Wizards) (H) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) @@ -1257,6 +1258,7 @@ [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) [2245.Maximum-Trailing-Zeros-in-a-Cornered-Path](https://github.com/wisdompeak/LeetCode/tree/master/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path) (M) +[6077.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/6077.Sum-of-Total-Strength-of-Wizards) (H) * ``2D Presum`` 1314.Matrix-Block-Sum (M) [1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold) (H-) From d7b3e14ccd2151eb8771cbcdab2ed4a6a3fb6d2b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 18:40:51 -0700 Subject: [PATCH 0810/2729] Create Readme.md --- .../Readme.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md diff --git a/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md b/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md new file mode 100644 index 000000000..b03e4a09b --- /dev/null +++ b/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md @@ -0,0 +1,25 @@ +### 6077.Sum-of-Total-Strength-of-Wizards + +根据套路,我们不会去枚举所有的subarray再找其中的weakest。相反,我们遍历每个元素将其作为weakest,再找对应的subarray。 + +假设位置在i的元素nums[i],其prevSmaller在位置a,nextSmaller在位置b。那么以nums[i]为weakest的subarray,左边界可以在a与i之间任意间隙,记做有```x = i-a```种可能;右边界可以再i与b之间的任意间隙,记做有```y = b-i```种可能。 +``` +a X X X X i X X X b +``` +也就是说,共有xy种subarray符合条件。我们需要累加所有这些subarray元素和。然后再乘以nums[i]本身,加入最终答案。 + +那么"累加所有这些subarray元素和"呢?对于上面的例子,无论subarray的右边界在哪里,nums[a+1]只会当左边界在a/a+1之间时被计入,即被统计了一次。同理,nums[a+2]会在左边界位于a/a+1之间,a+1/a+2之间时被计入,即被统计了两次。依次类推,i左边的四个元素被计入的次数是: +``` +a X X X X i X X X b + 1 2 3 4 +``` +所以他们对"累加所有这些subarray元素和"的贡献就是:```M = S * y```,其中``` S = nums[a+1]*1 + nums[a+2]*2 + nums[a+3]*3 + nums[a+4]*4 ...``` 乘以y是因为无论subarray的右边界在哪个位置,nums[i]左边的这些元素都会以一样的频次被计入subarray。 + +接下来考虑如何计算S。不难构造以index为系数的前缀和```presum2[i] = sum{nums[k]*k} for k=0,1,2,..i```,那么就有```presum2[i-1]-presum2[a] = nums[a+1]*(a+1) + nums[a+2]*(a+2) + nums[a+3]*(a+3) + nums[a+4]*(a+4) ...```。显然只要将其再减去常规的区间```sum[a+1:i]*a```,就是S了。综上即有```S = presum2[i-1]-presum2[a] - (presum[i-1] - presum[a]) * a```. + +类似地,我们希望处理右边的情况,我们同样标记i右边的是三个元素被计入的次数: +``` +a X X X X i X X X b + 3 2 1 +``` +同理,这里我们希望计算``` S = nums[i+1]*3 + nums[i+2]*2 + nums[i+3]*...```。 From cf23f972766a445e8e6de88b1d7768629589f45d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 21:52:30 -0700 Subject: [PATCH 0811/2729] Update Readme.md --- .../Readme.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md b/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md index b03e4a09b..1c39a9b3b 100644 --- a/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md +++ b/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md @@ -2,24 +2,30 @@ 根据套路,我们不会去枚举所有的subarray再找其中的weakest。相反,我们遍历每个元素将其作为weakest,再找对应的subarray。 -假设位置在i的元素nums[i],其prevSmaller在位置a,nextSmaller在位置b。那么以nums[i]为weakest的subarray,左边界可以在a与i之间任意间隙,记做有```x = i-a```种可能;右边界可以再i与b之间的任意间隙,记做有```y = b-i```种可能。 +假设位置在i的元素nums[i],其prevSmaller在位置a,nextSmaller在位置b。那么以nums[i]为weakest的subarray,左边界可以在a与i之间任意间隙,记做有```x = i-a```种可能;右边界可以在i与b之间的任意间隙,记做有```y = b-i```种可能。 ``` a X X X X i X X X b ``` -也就是说,共有xy种subarray符合条件。我们需要累加所有这些subarray元素和。然后再乘以nums[i]本身,加入最终答案。 +也就是说,共有```x*y```种subarray符合条件。我们需要累加所有这些subarray的元素和。然后再乘以nums[i]本身,加入最终答案。 -那么"累加所有这些subarray元素和"呢?对于上面的例子,无论subarray的右边界在哪里,nums[a+1]只会当左边界在a/a+1之间时被计入,即被统计了一次。同理,nums[a+2]会在左边界位于a/a+1之间,a+1/a+2之间时被计入,即被统计了两次。依次类推,i左边的四个元素被计入的次数是: +那么"累加所有这些subarray元素和"呢?对于上面的例子,无论subarray的右边界在哪里,nums[a+1]只会当左边界在a/a+1之间时被计入,即被统计了一次。同理,nums[a+2]会当左边界在位于a/a+1之间,或者a+1/a+2之间时被计入,即被统计了两次。依次类推,i左边的四个元素被计入的次数是: ``` a X X X X i X X X b 1 2 3 4 ``` -所以他们对"累加所有这些subarray元素和"的贡献就是:```M = S * y```,其中``` S = nums[a+1]*1 + nums[a+2]*2 + nums[a+3]*3 + nums[a+4]*4 ...``` 乘以y是因为无论subarray的右边界在哪个位置,nums[i]左边的这些元素都会以一样的频次被计入subarray。 +所以他们对"累加所有这些subarray元素和"的贡献就是:```M = S * y```,其中``` S = nums[a+1]*1 + nums[a+2]*2 + nums[a+3]*3 + nums[a+4]*4 ...``` 乘以y是因为无论subarray的右边界在哪个位置,nums[i]左边的这些元素都会以一样的频次被计入subarray,所以要重复y次。 -接下来考虑如何计算S。不难构造以index为系数的前缀和```presum2[i] = sum{nums[k]*k} for k=0,1,2,..i```,那么就有```presum2[i-1]-presum2[a] = nums[a+1]*(a+1) + nums[a+2]*(a+2) + nums[a+3]*(a+3) + nums[a+4]*(a+4) ...```。显然只要将其再减去常规的区间```sum[a+1:i]*a```,就是S了。综上即有```S = presum2[i-1]-presum2[a] - (presum[i-1] - presum[a]) * a```. +接下来考虑如何计算S。不难构造以index为权重的前缀和```presum2[i] = sum{nums[k]*k} for k=0,1,2,..i```,那么就有```presum2[i-1]-presum2[a] = nums[a+1]*(a+1) + nums[a+2]*(a+2) + nums[a+3]*(a+3) + nums[a+4]*(a+4) ...```。显然只要将其再减去常规的区间```sum[a+1:i]*a```,就是S了。综上即有```S = presum2[i-1]-presum2[a] - (presum[i-1] - presum[a]) * a```. 类似地,我们希望处理右边的情况,我们同样标记i右边的是三个元素被计入的次数: ``` a X X X X i X X X b 3 2 1 ``` -同理,这里我们希望计算``` S = nums[i+1]*3 + nums[i+2]*2 + nums[i+3]*...```。 +同理,这里我们希望计算``` S = nums[i+1]*3 + nums[i+2]*2 + nums[i+3]*...```。我们同样可以利用presum和presum2,具体的是```S = (presum[b-1]-presum[i])*(b+1) - (presum2[b-1]-presum2[i])```. 于是nums[i]右边的三个元素对于"累加所有这些subarray元素和"的贡献就是```S*x```. + +此外,别忘了nums[i]本身对于"累加所有这些subarray元素和"的贡献是```nums[i]*x*y```. + +所以以上三部分相加,再乘以nums[i]本身,就是以nums[i]为weakest的subarray的total strength. + +本题还有一个注意点,就是如果subarray里面如果有多个位置出现了最小值,那么哪个算weakest?为了避免重复,我们可以约定最左边出现的最小值算该subarray的weakest。所以本题中我们在预处理时,实际需要求的是prevSmallerOrEqual和nextSmaller。类似的题目见```2104.Sum-of-Subarray-Ranges```. From 668082c251415f792064ce7fe198581492721f40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 22:04:38 -0700 Subject: [PATCH 0812/2729] Update Readme.md --- Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md b/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md index 1c39a9b3b..79a422d31 100644 --- a/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md +++ b/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md @@ -22,7 +22,7 @@ a X X X X i X X X b a X X X X i X X X b 3 2 1 ``` -同理,这里我们希望计算``` S = nums[i+1]*3 + nums[i+2]*2 + nums[i+3]*...```。我们同样可以利用presum和presum2,具体的是```S = (presum[b-1]-presum[i])*(b+1) - (presum2[b-1]-presum2[i])```. 于是nums[i]右边的三个元素对于"累加所有这些subarray元素和"的贡献就是```S*x```. +同理,这里我们希望计算``` S = nums[i+1]*3 + nums[i+2]*2 + nums[i+3]*...```。我们同样可以利用presum和presum2,具体的是```S = (presum[b-1]-presum[i])*b - (presum2[b-1]-presum2[i])```. 于是nums[i]右边的三个元素对于"累加所有这些subarray元素和"的贡献就是```S*x```. 此外,别忘了nums[i]本身对于"累加所有这些subarray元素和"的贡献是```nums[i]*x*y```. From c84c8d26ec23c27125d34cb2e82551161ebbc7b4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 22:05:56 -0700 Subject: [PATCH 0813/2729] Update and rename Others/6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp to Others/2281.Sum-of-Total-Strength-of-Wizards/2281.Sum-of-Total-Strength-of-Wizards.cpp --- .../2281.Sum-of-Total-Strength-of-Wizards.cpp} | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) rename Others/{6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp => 2281.Sum-of-Total-Strength-of-Wizards/2281.Sum-of-Total-Strength-of-Wizards.cpp} (86%) diff --git a/Others/6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp b/Others/2281.Sum-of-Total-Strength-of-Wizards/2281.Sum-of-Total-Strength-of-Wizards.cpp similarity index 86% rename from Others/6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp rename to Others/2281.Sum-of-Total-Strength-of-Wizards/2281.Sum-of-Total-Strength-of-Wizards.cpp index 50efb8071..d44005662 100644 --- a/Others/6077.Sum-of-Total-Strength-of-Wizards/6077.Sum-of-Total-Strength-of-Wizards.cpp +++ b/Others/2281.Sum-of-Total-Strength-of-Wizards/2281.Sum-of-Total-Strength-of-Wizards.cpp @@ -11,9 +11,9 @@ class Solution { for (int i=1; i<=n; i++) presum[i] = (presum[i-1]+(LL)nums[i]) % M; - vectorpresum1(n+2, 0); + vectorpresum2(n+2, 0); for (int i=1; i<=n; i++) - presum1[i] = (presum1[i-1]+(LL)nums[i]*i) % M; + presum2[i] = (presum2[i-1]+(LL)nums[i]*i) % M; stackStack; vectornextSmaller(n+2,n+1); @@ -35,9 +35,9 @@ class Solution { { LL a = prevSmaller[i], b = nextSmaller[i]; LL x = i-a, y = b-i; - LL first = ((presum1[i-1] - presum1[a]) - (presum[i-1] - presum[a]) * a %M + M) % M; + LL first = ((presum2[i-1] - presum2[a]) - (presum[i-1] - presum[a]) * a %M + M) % M; first = first * y % M; - LL second = ((presum[b-1] - presum[i]) * (b-1+1) - (presum1[b-1] - presum1[i]) + M ) % M; + LL second = ((presum[b-1] - presum[i]) * (b-1+1) - (presum2[b-1] - presum2[i]) + M ) % M; second = second * x % M; LL mid = (LL)nums[i] * x * y % M; From 89d0265546a487879e9ea4bb8f60c2d1af954210 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 22:06:23 -0700 Subject: [PATCH 0814/2729] Rename Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md to Others/2281.Sum-of-Total-Strength-of-Wizards/Readme.md --- .../Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Others/{6077.Sum-of-Total-Strength-of-Wizards => 2281.Sum-of-Total-Strength-of-Wizards}/Readme.md (100%) diff --git a/Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md b/Others/2281.Sum-of-Total-Strength-of-Wizards/Readme.md similarity index 100% rename from Others/6077.Sum-of-Total-Strength-of-Wizards/Readme.md rename to Others/2281.Sum-of-Total-Strength-of-Wizards/Readme.md From 78d4974ddcb408341c930164bed7e993732cb478 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 22:16:50 -0700 Subject: [PATCH 0815/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 43847c8c4..127b68195 100644 --- a/Readme.md +++ b/Readme.md @@ -1219,7 +1219,7 @@ [1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) -[6077.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/6077.Sum-of-Total-Strength-of-Wizards) (H) +[2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 6e82c3f53d0ad2535296d218372f4d9c4d240caf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 22:19:28 -0700 Subject: [PATCH 0816/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 127b68195..074dffca3 100644 --- a/Readme.md +++ b/Readme.md @@ -1258,7 +1258,7 @@ [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) [2245.Maximum-Trailing-Zeros-in-a-Cornered-Path](https://github.com/wisdompeak/LeetCode/tree/master/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path) (M) -[6077.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/6077.Sum-of-Total-Strength-of-Wizards) (H) +[2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) * ``2D Presum`` 1314.Matrix-Block-Sum (M) [1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold) (H-) From 6b77c0ce8097faf1a0aa862bf31f98f81ef12b7c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 23:27:48 -0700 Subject: [PATCH 0817/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 074dffca3..f6897cad0 100644 --- a/Readme.md +++ b/Readme.md @@ -1217,6 +1217,7 @@ [828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) [1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) +[1856.Maximum-Subarray-Min-Product](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1856.Maximum-Subarray-Min-Product) (M+) [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) From 19a16e828eef6237f398bc2afada31a1c8870caf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 23:49:27 -0700 Subject: [PATCH 0818/2729] Create 2280.Minimum-Lines-to-Represent-a-Line-Chart.cpp --- ...inimum-Lines-to-Represent-a-Line-Chart.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Math/2280.Minimum-Lines-to-Represent-a-Line-Chart/2280.Minimum-Lines-to-Represent-a-Line-Chart.cpp diff --git a/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart/2280.Minimum-Lines-to-Represent-a-Line-Chart.cpp b/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart/2280.Minimum-Lines-to-Represent-a-Line-Chart.cpp new file mode 100644 index 000000000..5f7c27d29 --- /dev/null +++ b/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart/2280.Minimum-Lines-to-Represent-a-Line-Chart.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minimumLines(vector>& stockPrices) + { + if (stockPrices.size()==1) return 0; + sort(stockPrices.begin(), stockPrices.end()); + + int ret = 1; + int n = stockPrices.size(); + for (int i=2; i>& stockPrices, int t) + { + int x0 = stockPrices[t-2][0], y0 = stockPrices[t-2][1]; + int x1 = stockPrices[t-1][0], y1 = stockPrices[t-1][1]; + int x2 = stockPrices[t-0][0], y2 = stockPrices[t-0][1]; + + return (long long)(y2-y1)*(x1-x0)==(long long)(y1-y0)*(x2-x1); + } +}; From 7c5183fccf18581bd3b3cedf239d3e5c2a925d7e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 23:50:05 -0700 Subject: [PATCH 0819/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f6897cad0..efb79a8fc 100644 --- a/Readme.md +++ b/Readme.md @@ -997,6 +997,7 @@ [1401.Circle-and-Rectangle-Overlapping](https://github.com/wisdompeak/LeetCode/tree/master/Math/1401.Circle-and-Rectangle-Overlapping) (H) [1453.Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard](https://github.com/wisdompeak/LeetCode/tree/master/Math/1453.Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard) (H) [1610.Maximum-Number-of-Visible-Points](https://github.com/wisdompeak/LeetCode/tree/master/Math/1610.Maximum-Number-of-Visible-Points) (H) +[2280.Minimum-Lines-to-Represent-a-Line-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart) (M) * ``Random Pick`` [382.Linked-List-Random-Node](https://github.com/wisdompeak/LeetCode/tree/master/Math/382.Linked-List-Random-Node) (H) [470.Implement-Rand10()-Using-Rand7()](https://github.com/wisdompeak/LeetCode/tree/master/Math/470.Implement-Rand10--Using-Rand7) (M+) From 3b50e512d7ec56c3ad023fbfadb8e3618f3c6b74 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 May 2022 23:58:53 -0700 Subject: [PATCH 0820/2729] Create Readme.md --- .../2280.Minimum-Lines-to-Represent-a-Line-Chart/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Math/2280.Minimum-Lines-to-Represent-a-Line-Chart/Readme.md diff --git a/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart/Readme.md b/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart/Readme.md new file mode 100644 index 000000000..998b5a1d6 --- /dev/null +++ b/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart/Readme.md @@ -0,0 +1,7 @@ +### 2280.Minimum-Lines-to-Represent-a-Line-Chart + +将所有点按照横坐标排序之后,本题的核心就是判断任意相邻的三个点ABC是否共线。容易想到,我们判断线段AB和BC的斜率是否相等,即```(y3-y2)/(x3-x2)==(y2-y1)/(x2-x1)```.这里可能会有两个问题,第一个就是精度,当两个小数非常接近时,浮点数很难判断准确。第二个就是当斜率是90度时,除数为0(此题中这个问题不存在)。 + +解决方案就是将除法转换为乘法,即判断```(y3-y2)*(x2-x1)==(y2-y1)*(x3-x2)```即可。 + +相同的技巧在```2152.Minimum-Number-of-Lines-to-Cover-Points```中也用到过。 From f0fd03460697fb0e65e6697105fc6dab5716650b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 28 May 2022 16:40:03 -0700 Subject: [PATCH 0821/2729] Update Readme.md --- .../1884.Egg-Drop-With-2-Eggs-and-N-Floors/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1884.Egg-Drop-With-2-Eggs-and-N-Floors/Readme.md b/Dynamic_Programming/1884.Egg-Drop-With-2-Eggs-and-N-Floors/Readme.md index a5573e9df..34cb0713a 100644 --- a/Dynamic_Programming/1884.Egg-Drop-With-2-Eggs-and-N-Floors/Readme.md +++ b/Dynamic_Programming/1884.Egg-Drop-With-2-Eggs-and-N-Floors/Readme.md @@ -2,7 +2,7 @@ 此题是```887.Super-Egg-Drop```的简化版本。 -对于i层楼,如果只有一个鸡蛋,我们需要测几次呢?显然只能一层一层,从第1层开始尝试,最多可能一直到到第i层都不碎(注意题目允许在最高层都不碎)。所以需要n次测试,我们记做```dp[i][1]=1```. +对于i层楼,如果只有一个鸡蛋,我们需要测几次呢?显然只能一层一层,从第1层开始尝试,最多可能一直到到第i层都不碎(注意题目允许在最高层都不碎)。所以需要n次测试,我们记做```dp[i][1]=i```. 现在我们有两个鸡蛋。我们遍历第一个鸡蛋放在哪里。假设放在第j层,如果碎了,那么说明我们需要用剩下的一颗鸡蛋来确定极限层(恰好不破)在下方的j-1层的哪里,即dp[j-1][1]. 如果没有碎,说明极限层在第j层到第n层之间。此时我们可以把第j层看做相当于第0层(因为肯定不会破),所以我们需要的是在剩下的i-j层里面用两颗鸡蛋来确定极限层,即dp[i-j][2]. 考虑最坏情况,取```max{dp[j-1][1], dp[i-j][2]}``` From 439f5836dd5d4c157615150dbe5a6112c100b6bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 May 2022 18:11:06 -0700 Subject: [PATCH 0822/2729] Create 2289.Steps-to-Make-Array-Non-decreasing_v1.cpp --- ....Steps-to-Make-Array-Non-decreasing_v1.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp new file mode 100644 index 000000000..c6fca16f9 --- /dev/null +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int totalSteps(vector& nums) + { + int n = nums.size(); + list List; + unordered_map::iterator>key2iter; + for (int i=0; iq; + for (int i=1; inums[i]) + q.push(i); + + int step = 0; + while (!q.empty()) + { + int len = q.size(); + unordered_setSet; + while (len--) + { + int i = q.front(); + q.pop(); + + auto iter = key2iter[i]; + if (Set.count(i)) + Set.erase(i); + if (next(iter)!=List.end()) + Set.insert(*next(iter)); + List.erase(iter); + } + + for (int i: Set) + { + if (key2iter[i]!=List.begin() && nums[*prev(key2iter[i])] > nums[i]) + q.push(i); + } + step++; + } + + return step; + } +}; From 7b224cbc6c9afe0c051e219e815762fd4fb22da0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 May 2022 18:12:14 -0700 Subject: [PATCH 0823/2729] Update Readme.md --- Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index efb79a8fc..e578becc2 100644 --- a/Readme.md +++ b/Readme.md @@ -290,9 +290,6 @@ [2179.Count-Good-Triplets-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2179.Count-Good-Triplets-in-an-Array) (H) #### [Design](https://github.com/wisdompeak/LeetCode/tree/master/Design) -[146.LRU-Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/146.LRU-Cache) (H-) -[460.LFU Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/460.LFU-Cache) (H) -[432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [380.Insert-Delete-GetRandom-O(1)](https://github.com/wisdompeak/LeetCode/tree/master/Design/380.Insert-Delete-GetRandom-O-1/) (M+) [381.Insert-Delete-GetRandom-O1-Duplicates-allowed](https://github.com/wisdompeak/LeetCode/tree/master/Design/381.Insert-Delete-GetRandom-O1-Duplicates-allowed) (H-) [716.Max-Stack](https://github.com/wisdompeak/LeetCode/tree/master/Design/716.Max-Stack) (M+) @@ -309,6 +306,11 @@ [1622.Fancy-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Design/1622.Fancy-Sequence) (H+) [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Design/1801.Number-of-Orders-in-the-Backlog) (M+) [2166.Design-Bitset](https://github.com/wisdompeak/LeetCode/tree/master/Design/2166.Design-Bitset) (M+) +* ``Linked List`` +[146.LRU-Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/146.LRU-Cache) (H-) +[460.LFU Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/460.LFU-Cache) (H) +[432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) +[2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) From 17b045bdf4fe78c38e1190173064efe43a8164ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 10:20:22 -0700 Subject: [PATCH 0824/2729] Create 2289.Steps-to-Make-Array-Non-decreasing_v2.cpp --- ....Steps-to-Make-Array-Non-decreasing_v2.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v2.cpp diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v2.cpp b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v2.cpp new file mode 100644 index 000000000..3937b491c --- /dev/null +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v2.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int totalSteps(vector& nums) + { + int n = nums.size(); + vectornext(n); + for (int i=0; iremoved(n); + + queue>q; + for (int i=n-1; i>=1; i--) + { + if (nums[i-1]>nums[i]) + q.push({i-1, i}); + } + + int step = 0; + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + auto [l,r] = q.front(); + int r0 = r; + q.pop(); + + if (removed[l]) continue; + // if (removed[r]) continue; + + removed[r] = 1; + + int r2 = next[r]; + while (r2!=n && removed[r2]) + r2 = next[r2]; + next[r] = r2; + + if (r2!=n && nums[l]>nums[r2]) + q.push({l,r2}); + } + + step++; + } + + return step; + } +}; From aceb3b3e63834bda0f09cb6bbb6df46928ee62fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 11:27:57 -0700 Subject: [PATCH 0825/2729] Update 2289.Steps-to-Make-Array-Non-decreasing_v1.cpp --- ....Steps-to-Make-Array-Non-decreasing_v1.cpp | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp index c6fca16f9..0186a324c 100644 --- a/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp @@ -12,7 +12,7 @@ class Solution { } queueq; - for (int i=1; i=1; i--) if (nums[i-1]>nums[i]) q.push(i); @@ -20,28 +20,29 @@ class Solution { while (!q.empty()) { int len = q.size(); - unordered_setSet; + vectortemp; while (len--) { int i = q.front(); q.pop(); - auto iter = key2iter[i]; - if (Set.count(i)) - Set.erase(i); - if (next(iter)!=List.end()) - Set.insert(*next(iter)); + auto iter = key2iter[i]; + if (next(iter)!=List.end() && (temp.empty() || *next(iter)!=temp.back())) + { + temp.push_back(*next(iter)); + } + List.erase(iter); } - for (int i: Set) - { - if (key2iter[i]!=List.begin() && nums[*prev(key2iter[i])] > nums[i]) - q.push(i); + for (int idx: temp) + { + auto iter = key2iter[idx]; + if (iter!=List.begin() && nums[*prev(iter)] > nums[idx]) + q.push(idx); } step++; } - return step; } }; From 4234bcf66adc8c8c42702582b964ad612fe5de8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 12:07:16 -0700 Subject: [PATCH 0826/2729] Create Readme.md --- .../Readme.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md new file mode 100644 index 000000000..0c3a3a564 --- /dev/null +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md @@ -0,0 +1,38 @@ +### 2289.Steps-to-Make-Array-Non-decreasing + +本题的关键点是,如果某个位置i满足条件nums[i-1]>nums[i]需要被删除,那么导致的后果就是,在下一个回合,如果i后面的那个元素j(不见得是i+1,有可能i+1在这个回合已经被删除了)满足```nums[i-1]>nums[j]```的话,那么j会在“下一个回合”删除。那么如果确保j不是在这个回合就已经被删除了的呢?我们只需要倒序遍历。 + +举个例子,如下图,如果元素j被判定在本回合不会被删除,继续往前遍历,且i+1,i+2,...,j-1这些元素也在本回合删除,那么在考察元素i的时候就有next(i) = j,那么我们就可以安心地把j作为“下一个回合”待删除的对象。 +``` +i-1, i, i+1, i+2, ..., j-1, j + X X X X O +``` +以上的关键就是如何高效地维护next和prev,即如何快速某个元素后面一个/前面一个尚未被删除的元素(或者说idx)。 + +#### 解法1:暴力模拟 +和```LRU Cache```和```LFU Cache```一样,将链表和关于“元素->链表地址”的Hash结合起来用,是一个大杀器,可以保证在o(1)时间内的查找、删除。本题中,我们定义 +```cpp +list List; +unordered_map::iterator>idx2iter; +``` +链表List里面初始节点是一串编号{0,1,2,...,n-1},idx2iter则代表着链表每个节点的指针。 + +我们从后往前遍历,如果某个idx满足被删除的条件,令iter表示该idx的指针,那么就意味着next(iter)直接就是下一个节点的指针(无论两者之间已经删除了多少结果)。我们将```*next(iter)```这个后续编号放入一个candidates集合里,此时可以安心的将iter本身删除,而List的数据结构会自动将前后节点“接合”在一起。 + +我们倒序走完一遍后,剩下的candidates里面的编号,还需要再考察一遍是否满足```nums[*prev(idx2iter[idx])] > nums[idx]```,将那些符合条件的再进行下一遍的倒序遍历。 + +显然,这种结构就是层级遍历的BFS。答案就是看走了几个回合。 + +#### 解法2:高效模拟 +在解法1中我们考察的是点,所以需要依靠List和Hash来额外维护next和prev。一个更好的解法是考察一对pair。 + +我们在层级遍历BFS的过程中,加入的元素记做{l,r}表示此时一对相邻的编号且满足nums[l]>nums[r]. 那么在处理这对pair的时候,我们会标记removed[r]=1,同时根据之前的思路,我们要找到r此时的右邻元素编号next[r]。但是这里有一个问题,next[r]可能恰好在这个回合里面被删除了(因为我们是倒序遍历的),且此时我们必须找到再右邻的元素(不能放弃)。显然我们需要不断跳转来寻找: +```cpp +r2 = r; +while (r2!=n && removed[r2]) + r2 = next[r2]; +``` +递归结束后所找到的r2肯定是当前回合未被删除的,如果满足大小关系,那么[l, r2]就是下一个回合需要考察的pair。记得别忘了更新```next[r] = r2```,这样能加快今后的跳转效率。 + +此外还需要特别说明的是,虽然在这个回合里面,我们已经判定[l,r2]是下一个回合需要考察的pair,但注意到编号l的元素在本回合中尚未被遍历到(因为它是r左边的元素)。等到了下一个回合时,有可能我们发现l已经被删除了,那么此时的这个pair就作废了,跳过即可。但这没有关系,不意味着我们漏掉了r2,因为r2可能还会因为和其他的l2配对在一起。 + From c197fd7d0dfcfdfba98fb5d0b068aa25547b406a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 12:11:55 -0700 Subject: [PATCH 0827/2729] Update Readme.md --- Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md index 0c3a3a564..3b037d725 100644 --- a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md @@ -24,7 +24,7 @@ unordered_map::iterator>idx2iter; 显然,这种结构就是层级遍历的BFS。答案就是看走了几个回合。 #### 解法2:高效模拟 -在解法1中我们考察的是点,所以需要依靠List和Hash来额外维护next和prev。一个更好的解法是考察一对pair。 +在解法1中我们考察的是点,所以需要依靠List和Hash来额外维护next和prev。一个更好的解法是考察一对pair。同时用removed数组来标记节点的删除,而不用List。 我们在层级遍历BFS的过程中,加入的元素记做{l,r}表示此时一对相邻的编号且满足nums[l]>nums[r]. 那么在处理这对pair的时候,我们会标记removed[r]=1,同时根据之前的思路,我们要找到r此时的右邻元素编号next[r]。但是这里有一个问题,next[r]可能恰好在这个回合里面被删除了(因为我们是倒序遍历的),且此时我们必须找到再右邻的元素(不能放弃)。显然我们需要不断跳转来寻找: ```cpp From dde7a5555ca504cedc5cbb035677b9f06f16d0c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 13:01:51 -0700 Subject: [PATCH 0828/2729] Update 2289.Steps-to-Make-Array-Non-decreasing_v1.cpp --- .../2289.Steps-to-Make-Array-Non-decreasing_v1.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp index 0186a324c..98f90b043 100644 --- a/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v1.cpp @@ -4,11 +4,11 @@ class Solution { { int n = nums.size(); list List; - unordered_map::iterator>key2iter; + unordered_map::iterator>idx2iter; for (int i=0; iq; @@ -26,7 +26,7 @@ class Solution { int i = q.front(); q.pop(); - auto iter = key2iter[i]; + auto iter = idx2iter[i]; if (next(iter)!=List.end() && (temp.empty() || *next(iter)!=temp.back())) { temp.push_back(*next(iter)); @@ -37,7 +37,7 @@ class Solution { for (int idx: temp) { - auto iter = key2iter[idx]; + auto iter = idx2iter[idx]; if (iter!=List.begin() && nums[*prev(iter)] > nums[idx]) q.push(idx); } From 90b7ae7e7f11d5e623aa4073d9191c9624adb5ae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 19:35:01 -0700 Subject: [PATCH 0829/2729] Create 2289.Steps-to-Make-Array-Non-decreasing_v3.cpp --- ....Steps-to-Make-Array-Non-decreasing_v3.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v3.cpp diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v3.cpp b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v3.cpp new file mode 100644 index 000000000..c64bb311f --- /dev/null +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/2289.Steps-to-Make-Array-Non-decreasing_v3.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int totalSteps(vector& nums) + { + int n = nums.size(); + vectorcount(n); + int ret = 0; + stackStack; + for (int i=n-1; i>=0; i--) + { + int temp = 0; + while (!Stack.empty() && nums[i]>nums[Stack.top()]) + { + temp = max(temp+1, count[Stack.top()]); + Stack.pop(); + } + + count[i] = temp; + Stack.push(i); + ret = max(ret, count[i]); + } + return ret; + } +}; From 78f8bde0007da185f7373994ab50cd149a0e33b5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 21:37:25 -0700 Subject: [PATCH 0830/2729] Update Readme.md --- .../Readme.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md index 3b037d725..d3b3d9abc 100644 --- a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md @@ -36,3 +36,38 @@ while (r2!=n && removed[r2]) 此外还需要特别说明的是,虽然在这个回合里面,我们已经判定[l,r2]是下一个回合需要考察的pair,但注意到编号l的元素在本回合中尚未被遍历到(因为它是r左边的元素)。等到了下一个回合时,有可能我们发现l已经被删除了,那么此时的这个pair就作废了,跳过即可。但这没有关系,不意味着我们漏掉了r2,因为r2可能还会因为和其他的l2配对在一起。 +#### 解法3:单调栈 +我们从右往左遍历元素,维护一个递减的单调栈。任何一个新元素M,如果它大于栈顶的若干个元素,那么这些元素(包括之前被这些元素弹出的元素)本质上都是因为M而退栈。这个性质与本题的题意非常类似:对于M而言,它右邻的、连续的比M小的元素,都会被M所“吃掉”。 + +我们令count[i]表示元素i吃掉它所“影响”的元素(即i右邻的、连续的比i小的元素)需要多少步。我们画这样一张图模拟单调栈 +``` + q +i + p + k (..P..) + j (..K..) + (..J..) +``` +从右往左看,先入栈的是q;然后是一系列(..P..),但它们接着会因为p的入栈然弹出;然后是一系列(..K..),同样它们会因为k的入栈而弹出。再接下来是(..J..)的入栈和弹出,以及j的入栈。当考察元素i的时候,栈内从顶至底是[j,k,p,q] + +此时我们考虑如何计算count[i],即将[j, q-1]范围内的元素都吃掉需要花多少步。我们知道,最后一个被i吃掉的元素一定是p,在此之前,(..P..)已经被p吃掉,所需要的步数就是count[p];同时[j,p-1]这部分已经被i吃掉,所需要的步数我们记做f(k),因为k是这个区间里的最大值,也就是最后一个被吃掉的。所以我们就有一个重要的结论: +``` +count[i] = max(f(k)+1, count[p]) +``` +怎么解释这个公式?总的来说,p有两种被吃掉的途径。如果f(k)比较大,那么count[p]耗完之后还需要等若干个回合,等f(k)结束之后,p此时才能与i相邻,故需要再加一步将p吃掉。如果count[p]较大,那么f(k)耗完之后,p已经与i相邻了,故p被i吃掉的这个步骤可以与count[p]的最后一步(某个元素被p吃掉)合并,故仍只需要count[p]的步数。 + +那么上式里面的f(k)又从哪来呢?类似的有: +``` +f(k) = max(f(j)+1, count[k]) +``` +于是我们看出来,f()的计算是一个递归的过程。对于count[i],我们需要依次得到f(j),f(k),f(p),而j,k,p也就是在单调栈中被i弹出的元素。最终count[i]也就是f(p)。所以我们利用退栈的过程更新f +```cpp +int f = 0; +while (!Stack.empty() && nums[i]>nums[Stack.top()]) +{ + f = max(f+1, count[Stack.top()]); + Stack.pop(); +} +count[i] = f; +``` +因为最终是一个非递减序列,意味着在原序列里,任意一个元素i都需要将右邻的、连续的比i小的元素都吃掉。所以最终的答案就是所有count[i]里最大的一个值。 From 4594c729fccc5b9fdc4842c8c4e5bbf236019350 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 21:38:57 -0700 Subject: [PATCH 0831/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e578becc2..be65c8a21 100644 --- a/Readme.md +++ b/Readme.md @@ -351,6 +351,7 @@ [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) +[2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) [1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) From d7751195a8198dffbb32c0fb1ae3b3fa03b27b37 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 May 2022 21:40:18 -0700 Subject: [PATCH 0832/2729] Update Readme.md --- Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md index d3b3d9abc..d407cd549 100644 --- a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md @@ -36,6 +36,8 @@ while (r2!=n && removed[r2]) 此外还需要特别说明的是,虽然在这个回合里面,我们已经判定[l,r2]是下一个回合需要考察的pair,但注意到编号l的元素在本回合中尚未被遍历到(因为它是r左边的元素)。等到了下一个回合时,有可能我们发现l已经被删除了,那么此时的这个pair就作废了,跳过即可。但这没有关系,不意味着我们漏掉了r2,因为r2可能还会因为和其他的l2配对在一起。 +需要提醒的是,这两种模拟的算法都是o(n),因为每删除一个数字,只会用o(1)引进一个新的candidate。 + #### 解法3:单调栈 我们从右往左遍历元素,维护一个递减的单调栈。任何一个新元素M,如果它大于栈顶的若干个元素,那么这些元素(包括之前被这些元素弹出的元素)本质上都是因为M而退栈。这个性质与本题的题意非常类似:对于M而言,它右邻的、连续的比M小的元素,都会被M所“吃掉”。 From 6aea5495f6ca6e8b9414a8a6238c0e902a271840 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 May 2022 00:23:39 -0700 Subject: [PATCH 0833/2729] Update Readme.md --- Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md index d407cd549..a5d381372 100644 --- a/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md +++ b/Design/2289.Steps-to-Make-Array-Non-decreasing/Readme.md @@ -41,7 +41,7 @@ while (r2!=n && removed[r2]) #### 解法3:单调栈 我们从右往左遍历元素,维护一个递减的单调栈。任何一个新元素M,如果它大于栈顶的若干个元素,那么这些元素(包括之前被这些元素弹出的元素)本质上都是因为M而退栈。这个性质与本题的题意非常类似:对于M而言,它右邻的、连续的比M小的元素,都会被M所“吃掉”。 -我们令count[i]表示元素i吃掉它所“影响”的元素(即i右邻的、连续的比i小的元素)需要多少步。我们画这样一张图模拟单调栈 +我们令count[i]表示元素i吃掉它所“影响”的元素(即i右邻的、连续的比i小的元素)需要多少步。我们画这样一张图模拟单调栈,横轴表示先后顺序,纵轴表示大小关系。 ``` q i @@ -50,15 +50,15 @@ i j (..K..) (..J..) ``` -从右往左看,先入栈的是q;然后是一系列(..P..),但它们接着会因为p的入栈然弹出;然后是一系列(..K..),同样它们会因为k的入栈而弹出。再接下来是(..J..)的入栈和弹出,以及j的入栈。当考察元素i的时候,栈内从顶至底是[j,k,p,q] +从右往左看,先入栈的是q;然后是一系列(..P..),但它们接着会因为p的入栈而弹出;然后是一系列(..K..),同样它们会因为k的入栈而弹出。再接下来是(..J..)的入栈,随后因为j的入栈而弹出。当考察元素i的时候,栈内从顶至底是[j,k,p,q] 此时我们考虑如何计算count[i],即将[j, q-1]范围内的元素都吃掉需要花多少步。我们知道,最后一个被i吃掉的元素一定是p,在此之前,(..P..)已经被p吃掉,所需要的步数就是count[p];同时[j,p-1]这部分已经被i吃掉,所需要的步数我们记做f(k),因为k是这个区间里的最大值,也就是最后一个被吃掉的。所以我们就有一个重要的结论: ``` count[i] = max(f(k)+1, count[p]) ``` -怎么解释这个公式?总的来说,p有两种被吃掉的途径。如果f(k)比较大,那么count[p]耗完之后还需要等若干个回合,等f(k)结束之后,p此时才能与i相邻,故需要再加一步将p吃掉。如果count[p]较大,那么f(k)耗完之后,p已经与i相邻了,故p被i吃掉的这个步骤可以与count[p]的最后一步(某个元素被p吃掉)合并,故仍只需要count[p]的步数。 +怎么解释这个公式?总的来说,p有两种被吃掉的途径。如果f(k)比较大,那么count[p]耗完之后还需要等若干个回合,等f(k)结束之后,p此时才能与i相邻,故需要再加一步将p吃掉。如果count[p]较大,那么f(k)耗完之后,p已经与i相邻了,故p被i吃掉的这个步骤可以早于count[p],故总的回合数的瓶颈依然是count[p]。 -那么上式里面的f(k)又从哪来呢?类似的有: +那么上式里面的f(k)又从哪来呢?其实类似地发现: ``` f(k) = max(f(j)+1, count[k]) ``` From dc41a3c4d4d3257ca91441e26ae12534c9e67d54 Mon Sep 17 00:00:00 2001 From: Fenghe Xu Date: Wed, 1 Jun 2022 12:41:04 +0800 Subject: [PATCH 0834/2729] Create 473.Matchsticks-to-Square_v2.cpp --- .../473.Matchsticks-to-Square_v2.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 DFS/473.Matchsticks-to-Square/473.Matchsticks-to-Square_v2.cpp diff --git a/DFS/473.Matchsticks-to-Square/473.Matchsticks-to-Square_v2.cpp b/DFS/473.Matchsticks-to-Square/473.Matchsticks-to-Square_v2.cpp new file mode 100644 index 000000000..b7e13b405 --- /dev/null +++ b/DFS/473.Matchsticks-to-Square/473.Matchsticks-to-Square_v2.cpp @@ -0,0 +1,38 @@ +class Solution { + bool divide2(vector& sticks, int target) { + int n = sticks.size(); + for(int state = 0; state < (1<>i)&1) cur += sticks[i]; + } + if(cur == target) return true; + } + return false; + } +public: + bool makesquare(vector& matchsticks) { + int total = accumulate(matchsticks.begin(), matchsticks.end(), 0); + if(total % 4 != 0) return false; + + int n = matchsticks.size(); + + for(int state = 0; state < (1<>i)&1) cur += matchsticks[i]; + } + if(cur == total / 2) { + vector v1, v2; + for(int i = 0; i < n; ++i) { + if((state>>i)&1) v1.push_back(matchsticks[i]); + else v2.push_back(matchsticks[i]); + } + + if(divide2(v1, total / 4) && divide2(v2, total / 4)) return true; + } + } + + return false; + } +}; From 60dd7927b5329e28e16451307b3de680c0f63eb6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jun 2022 23:13:57 -0700 Subject: [PATCH 0835/2729] Create 2290.Minimum-Obstacle-Removal-to-Reach-Corner.cpp --- ...nimum-Obstacle-Removal-to-Reach-Corner.cpp | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/2290.Minimum-Obstacle-Removal-to-Reach-Corner.cpp diff --git a/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/2290.Minimum-Obstacle-Removal-to-Reach-Corner.cpp b/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/2290.Minimum-Obstacle-Removal-to-Reach-Corner.cpp new file mode 100644 index 000000000..10b6f1bb8 --- /dev/null +++ b/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/2290.Minimum-Obstacle-Removal-to-Reach-Corner.cpp @@ -0,0 +1,88 @@ +class Solution { + vector>dir = {{1,0},{-1,0},{0,1},{0,-1}}; +public: + int minimumObstacles(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + if (m==1 && n==1) return 0; + vector>visited(m, vector(n,0)); + + queue>q; + q.push({0,0}); + visited[0][0] = 1; + + int step = 0; + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + auto [x, y] = q.front(); + q.pop(); + + for (auto [dx, dy]: dir) + { + int i = x+dx; + int j = y+dy; + + if (i<0||i>=m||j<0||j>=n) continue; + if (visited[i][j]==1) continue; + if (grid[i][j] == 1) + { + visited[i][j] = 1; + q.push({i,j}); + } + else + { + for (auto [ii, jj]: travel(grid, visited, i, j)) + { + if (ii==m-1 && jj==n-1) + return step; + q.push({ii,jj}); + } + } + } + } + step++; + } + return 0; + } + + vector>travel(vector>& grid, vector>& visited, int x0, int y0) + { + int m = grid.size(); + int n = grid[0].size(); + + if (x0==m-1 && y0==n-1) + return {{x0, y0}}; + + queue>q; + q.push({x0,y0}); + visited[x0][y0] = 1; + + vector>rets; + while (!q.empty()) + { + auto [x, y] = q.front(); + q.pop(); + + for (auto [dx, dy] : dir) + { + int i = x+dx; + int j = y+dy; + if (i<0||i>=m||j<0||j>=n) continue; + if (visited[i][j]==1) continue; + visited[i][j] = 1; + if (i==m-1 && j==n-1) + rets.push_back({i,j}); + else if (grid[i][j]==1) + rets.push_back({i,j}); + else + q.push({i,j}); + } + } + + return rets; + } +}; From 2677ece1fee0aeb54a5c1efa66d7c7128e9f4d81 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 2 Jun 2022 00:56:54 -0700 Subject: [PATCH 0836/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index be65c8a21..9944d615a 100644 --- a/Readme.md +++ b/Readme.md @@ -487,6 +487,7 @@ [2045.Second-Minimum-Time-to-Reach-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2045.Second-Minimum-Time-to-Reach-Destination) (M+) [2101.Detonate-the-Maximum-Bombs](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2101.Detonate-the-Maximum-Bombs) (M+) [2258.Escape-the-Spreading-Fire](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2258.Escape-the-Spreading-Fire) (H+) +[2290.Minimum-Obstacle-Removal-to-Reach-Corner](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner) (M+) * ``Multi State`` [847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) [864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) From ce47ebc33f466cb16ca8bbb3f919495b1ef24703 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 2 Jun 2022 01:23:13 -0700 Subject: [PATCH 0837/2729] Create Readme.md --- BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/Readme.md diff --git a/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/Readme.md b/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/Readme.md new file mode 100644 index 000000000..8c97b2875 --- /dev/null +++ b/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner/Readme.md @@ -0,0 +1,5 @@ +### 2290.Minimum-Obstacle-Removal-to-Reach-Corner + +本题的本质就是从起点到终点,采用层级BFS,最少需要穿越几个回合的障碍。而障碍与障碍之间的空气,可以忽略不计。也就是说,某个障碍与空气相邻的话,下一个回合可以通过空气到达其他的障碍。 + +在实现过程中,除了常规的层级BFS之外,我们还需要有一个travelAir的函数。travelAir以某个空格子为起点,遍历所有能“隔空”访问的障碍物。这些障碍物需要加入下一回合BFS的队列中去。 From 9c45c6411034429d2c289ebdd66271b22c361795 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 3 Jun 2022 23:33:31 -0700 Subject: [PATCH 0838/2729] Create 698.Partition-to-K-Equal-Sum-Subsets_v2.cpp --- ...98.Partition-to-K-Equal-Sum-Subsets_v2.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v2.cpp diff --git a/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v2.cpp b/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v2.cpp new file mode 100644 index 000000000..66733f92c --- /dev/null +++ b/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool canPartitionKSubsets(vector& nums, int k) + { + int n = nums.size(); + int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum%k!=0) return false; + int target = sum / k; + + vectordp(1<>i)&1) && (dp[state]+nums[i] <= target)) + dp[state + (1< Date: Fri, 3 Jun 2022 23:33:43 -0700 Subject: [PATCH 0839/2729] Rename 698.Partition-to-K-Equal-Sum-Subsets.cpp to 698.Partition-to-K-Equal-Sum-Subsets_v1.cpp --- ...um-Subsets.cpp => 698.Partition-to-K-Equal-Sum-Subsets_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DFS/698.Partition-to-K-Equal-Sum-Subsets/{698.Partition-to-K-Equal-Sum-Subsets.cpp => 698.Partition-to-K-Equal-Sum-Subsets_v1.cpp} (100%) diff --git a/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets.cpp b/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v1.cpp similarity index 100% rename from DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets.cpp rename to DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v1.cpp From 0a73a820e17a7e4618ca74774a104aaa68acf11a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 3 Jun 2022 23:53:37 -0700 Subject: [PATCH 0840/2729] Update Readme.md --- DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md b/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md index c03b00350..70a464126 100644 --- a/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md +++ b/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md @@ -1,5 +1,6 @@ ### 698.Partition-to-K-Equal-Sum-Subsets +#### 解法1:搜索 此题据说是NP-hard,没有什么特别高明的算法,就是老老实实地DFS,尝试将所有元素挨个尝试放入k个分类里,直至找到满足条件的分类。 设计如下的递归函数:```DFS(nums, curPos, curGroup, curSum)```. @@ -27,5 +28,15 @@ for (int i=curPos; i Date: Fri, 3 Jun 2022 23:54:17 -0700 Subject: [PATCH 0841/2729] Update Readme.md --- DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md b/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md index 70a464126..da33cb80d 100644 --- a/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md +++ b/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md @@ -37,6 +37,6 @@ for (int i=curPos; i Date: Fri, 3 Jun 2022 23:54:49 -0700 Subject: [PATCH 0842/2729] Update 698.Partition-to-K-Equal-Sum-Subsets_v2.cpp --- .../698.Partition-to-K-Equal-Sum-Subsets_v2.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v2.cpp b/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v2.cpp index 66733f92c..b3c90ccd8 100644 --- a/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v2.cpp +++ b/DFS/698.Partition-to-K-Equal-Sum-Subsets/698.Partition-to-K-Equal-Sum-Subsets_v2.cpp @@ -19,6 +19,7 @@ class Solution { } } - return dp[(1< Date: Fri, 3 Jun 2022 23:55:12 -0700 Subject: [PATCH 0843/2729] Update Readme.md --- DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md b/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md index da33cb80d..6be5ed84e 100644 --- a/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md +++ b/DFS/698.Partition-to-K-Equal-Sum-Subsets/Readme.md @@ -39,4 +39,6 @@ for (int i=curPos; i Date: Sun, 5 Jun 2022 17:59:41 -0700 Subject: [PATCH 0844/2729] Update BIT.cpp --- Template/Binary_Index_Tree/BIT.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Template/Binary_Index_Tree/BIT.cpp b/Template/Binary_Index_Tree/BIT.cpp index 98f5421a0..576d03984 100644 --- a/Template/Binary_Index_Tree/BIT.cpp +++ b/Template/Binary_Index_Tree/BIT.cpp @@ -4,8 +4,8 @@ class BIT{ vectorbitArr; // Note: all arrays are 1-index vectornums; long long M = 1e9+7; - - BIT(int N) + + void init(int N) { this->N = N; bitArr.resize(N+1); @@ -18,7 +18,7 @@ class BIT{ while (idx <= N) { bitArr[idx]+=delta; - bitArr[idx] %= M; + // bitArr[idx] %= M; idx+=idx&(-idx); } } @@ -28,7 +28,7 @@ class BIT{ long long result = 0; while (idx){ result += bitArr[idx]; - result %= M; + // result %= M; idx-=idx&(-idx); } return result; @@ -41,12 +41,13 @@ class BIT{ }; int main() -{ + { int N = 100000; - BIT bit(N); + BIT bit; + bit.init(N); vectornums(N); // cin>> nums .... - + for (int i=1; i Date: Sun, 5 Jun 2022 19:04:48 -0700 Subject: [PATCH 0845/2729] Update 210.Course-Schedule-II.cpp when index is small, array might be faster than unordered_map --- BFS/210.Course-Schedule-II/210.Course-Schedule-II.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BFS/210.Course-Schedule-II/210.Course-Schedule-II.cpp b/BFS/210.Course-Schedule-II/210.Course-Schedule-II.cpp index 70e244298..6c49299f9 100644 --- a/BFS/210.Course-Schedule-II/210.Course-Schedule-II.cpp +++ b/BFS/210.Course-Schedule-II/210.Course-Schedule-II.cpp @@ -3,8 +3,8 @@ class Solution { vector findOrder(int numCourses, vector>& prerequisites) { int n = numCourses; - unordered_map>nextCourses(n); - unordered_mapdegree(n); + vector>nextCourses(n); + vectordegree(n, 0); for (auto edge: prerequisites) { From 3de10b8399eae914f0c5e464802b2731d406bbbb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 21:38:22 -0700 Subject: [PATCH 0846/2729] Create range_max.cpp --- Template/SegmentTree/range_max.cpp | 99 ++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Template/SegmentTree/range_max.cpp diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp new file mode 100644 index 000000000..6b084e3a6 --- /dev/null +++ b/Template/SegmentTree/range_max.cpp @@ -0,0 +1,99 @@ +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the max height of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) + { + if (b < start || a > end ) // no intersection + return; + + if (a <= start && end <=b) + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) + { + if (b < start || a > end ) + { + return 0; // write your own logic + } + if (a <= start && end <=b) + { + return info; // write your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); + return ret; + } + + return info; + } + +}; + +int main() +{ + SegTreeNode* root = new SegTreeNode(0, length-1); + + for (auto& update: updates) + { + int start = update[0], end = update[1], val = update[2]; + root->updateRange(start, end ,val); // set the range [start, end] with val + } + + vectorrets(length); + for (int i=0; iqueryRange(i, i); // get single node val + return rets; +} From c922f7badec9b1e66fdb5710f728d90e011fd81a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 21:42:18 -0700 Subject: [PATCH 0847/2729] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 6b084e3a6..919ad89af 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -4,10 +4,10 @@ class SegTreeNode SegTreeNode* left = NULL; SegTreeNode* right = NULL; int start, end; - int info; // the max height of the range + int info; // the maximum value of the range bool tag; - SegTreeNode(int a, int b, int val) // init for range [a,b] + SegTreeNode(int a, int b, int val) // init for range [a,b] with val { tag = 0; start = a, end = b; @@ -21,7 +21,7 @@ class SegTreeNode { left = new SegTreeNode(a, mid, val); right = new SegTreeNode(mid+1, b, val); - info = max(left->info, right->info); // write your own logic + info = max(left->info, right->info); // check with your own logic } } @@ -37,12 +37,11 @@ class SegTreeNode } } - void updateRange(int a, int b, int val) + void updateRange(int a, int b, int val) // set range [a,b] with val { - if (b < start || a > end ) // no intersection - return; - - if (a <= start && end <=b) + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] { info = val; tag = 1; @@ -58,26 +57,26 @@ class SegTreeNode } } - int queryRange(int a, int b) + int queryRange(int a, int b) // query the maximum value within range [a,b] { if (b < start || a > end ) { - return 0; // write your own logic + return 0; // check with your own logic } if (a <= start && end <=b) { - return info; // write your own logic + return info; // check with your own logic } if (left) { pushDown(); int ret = max(left->queryRange(a, b), right->queryRange(a, b)); - info = max(left->info, right->info); + info = max(left->info, right->info); // check with your own logic return ret; } - return info; + return info; // should not reach here } }; From 0c2f74d20089bb932c9893679244b3d3e594d625 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 21:46:14 -0700 Subject: [PATCH 0848/2729] Update 699.Falling-Squares_SegmentTree_LazyTag.cpp --- ...99.Falling-Squares_SegmentTree_LazyTag.cpp | 132 +++++++++--------- 1 file changed, 69 insertions(+), 63 deletions(-) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegmentTree_LazyTag.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegmentTree_LazyTag.cpp index 0e33f2a38..5a4297587 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegmentTree_LazyTag.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegmentTree_LazyTag.cpp @@ -1,80 +1,87 @@ -class Solution { - class SegTreeNode - { - public: - SegTreeNode* left; - SegTreeNode* right; - int start, end; - int info; // the max height of the range - bool tag; - SegTreeNode(int a, int b):start(a),end(b),info(0),tag(0),left(NULL),right(NULL){} - }; - - void init(SegTreeNode* node, int a, int b) // init for range [a,b] - { +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; if (a==b) { - node->info = 0; + info = val; return; - } + } int mid = (a+b)/2; - if (node->left==NULL) + if (left==NULL) { - node->left = new SegTreeNode(a, mid); - node->right = new SegTreeNode(mid+1, b); - } - init(node->left, a, mid); - init(node->right, mid+1, b); - - node->info = 0; // write your own logic - } + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } - void updateRange(SegTreeNode* node, int a, int b, int val) + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val { - if (b < node->start || a > node->end ) // no intersection - return; - if (a <= node->start && node->end <=b) + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] { - node->info = val; - node->tag = 1; + info = val; + tag = 1; return; } - - pushDown(node); - updateRange(node->left, a, b, val); - updateRange(node->right, a, b, val); - - node->info = max(node->left->info, node->right->info); // write your own logic + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } } - int queryRange(SegTreeNode* node, int a, int b) + int queryRange(int a, int b) // query the maximum value within range [a,b] { - if (b < node->start || a > node->end ) + if (b < start || a > end ) { - return 0; // write your own logic + return 0; // check with your own logic } - if (a <= node->start && b>=node->end) + if (a <= start && end <=b) { - return node->info; // write your own logic - } - pushDown(node); - node->info = max(queryRange(node->left, a, b), queryRange(node->right, a, b)); // write your own logic - return node->info; - } - - void pushDown(SegTreeNode* node) - { - if (node->tag==true) + return info; // check with your own logic + } + + if (left) { - node->left->info = node->info; - node->right->info = node->info; - node->left->tag = 1; - node->right->tag = 1; - node->tag = 0; - } + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here } - - + +}; + +class Solution { public: vector fallingSquares(vector>& positions) { @@ -93,8 +100,7 @@ class Solution { } int n = pos2idx.size(); - SegTreeNode* root = new SegTreeNode(0, n-1); - init(root, 0, n-1); + SegTreeNode* root = new SegTreeNode(0, n-1, 0); int maxH = 0; vectorrets; @@ -102,8 +108,8 @@ class Solution { { int a = pos2idx[rect[0]]; int b = pos2idx[rect[0]+rect[1]]; - int h = queryRange(root, a, b-1); // [a,b) - updateRange(root, a, b-1, h + rect[1]); + int h = root->queryRange(a, b-1); // [a,b) + root->updateRange(a, b-1, h + rect[1]); maxH = max(maxH, h + rect[1]); rets.push_back(maxH); } From a57433c72e7e31f81c77568bc199beadbd642b41 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 21:47:04 -0700 Subject: [PATCH 0849/2729] Rename 699.Falling-Squares_SegmentTree_LazyTag.cpp to 699.Falling-Squares_SegTree_v2.cpp --- ...SegmentTree_LazyTag.cpp => 699.Falling-Squares_SegTree_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/699.Falling-Squares/{699.Falling-Squares_SegmentTree_LazyTag.cpp => 699.Falling-Squares_SegTree_v2.cpp} (100%) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegmentTree_LazyTag.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp similarity index 100% rename from Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegmentTree_LazyTag.cpp rename to Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp From 91fd1973552349b79b53e3acc19441bce217af31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 21:47:32 -0700 Subject: [PATCH 0850/2729] Update and rename 699.Falling-Squares_segTree.cpp to 699.Falling-Squares_SegTree_v1.cpp --- ...g-Squares_segTree.cpp => 699.Falling-Squares_SegTree_v1.cpp} | 2 ++ 1 file changed, 2 insertions(+) rename Segment_Tree/699.Falling-Squares/{699.Falling-Squares_segTree.cpp => 699.Falling-Squares_SegTree_v1.cpp} (98%) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_segTree.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp similarity index 98% rename from Segment_Tree/699.Falling-Squares/699.Falling-Squares_segTree.cpp rename to Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp index ad65408b7..8a470ef40 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_segTree.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp @@ -1,3 +1,5 @@ +// 支持动态开点 + class Solution { class SegTree { From 3cbb303d33fe3689b2a84bebef4ee300a03c9d30 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 21:59:34 -0700 Subject: [PATCH 0851/2729] Update 699.Falling-Squares_SegTree_v1.cpp --- .../699.Falling-Squares_SegTree_v1.cpp | 113 +++++++++--------- 1 file changed, 57 insertions(+), 56 deletions(-) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp index 8a470ef40..7aa698df2 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp @@ -1,73 +1,74 @@ -// 支持动态开点 +// 动态开点 -class Solution { - class SegTree +class SegTree +{ + public: + int start,end,status; + SegTree* left; + SegTree* right; + SegTree(int a,int b,int s):start(a),end(b),status(s),left(NULL),right(NULL){} + + void remove(SegTree* &node) + { + if (node==NULL) return; + remove(node->left); + remove(node->right); + delete node; + node=NULL; + return; + } + + void setStatus(int a, int b, int s) { - public: - int start,end,status; - SegTree* left; - SegTree* right; - SegTree(int a,int b,int s):start(a),end(b),status(s),left(NULL),right(NULL){} - - void remove(SegTree* &node) + if (a<=start && b>=end) { - if (node==NULL) return; - remove(node->left); - remove(node->right); - delete node; - node=NULL; + remove(left); + remove(right); + status = s; return; } - - void setStatus(int a, int b, int s) - { - if (a<=start && b>=end) - { - remove(left); - remove(right); - status = s; - return; - } - if (a>=end || b<=start) - return; - if (left==NULL) - { - int mid = (end-start)/2+start; - left = new SegTree(start,mid,status); - right = new SegTree(mid,end,status); - } - left->setStatus(a,b,s); - right->setStatus(a,b,s); - status = max(left->status,right->status); + if (a>=end || b<=start) return; - } - - int getStatus(int a, int b) + if (left==NULL) { - if (a<=start && b>=end) - return status; - if (a>=end || b<=start) - return 0; - if (left==NULL) - return status; - int L = left->getStatus(a,b); - int R = right->getStatus(a,b); - return max(L,R); - } - }; + int mid = (end-start)/2+start; + left = new SegTree(start,mid,status); + right = new SegTree(mid,end,status); + } + left->setStatus(a,b,s); + right->setStatus(a,b,s); + status = max(left->status,right->status); + return; + } + + int getStatus(int a, int b) + { + if (a<=start && b>=end) + return status; + if (a>=end || b<=start) + return 0; + if (left==NULL) + return status; + int L = left->getStatus(a,b); + int R = right->getStatus(a,b); + return max(L,R); + } +}; + +class Solution { public: - vector fallingSquares(vector>& positions) + vector fallingSquares(vector>& positions) { - SegTree root = SegTree(0,1e9,0); + SegTree* root = new SegTree(0,1e9,0); vectorresult; int curMax = 0; for (auto p:positions) { - int cur = root.getStatus(p.first,p.first+p.second); - curMax = max(curMax, cur+p.second); - root.setStatus(p.first,p.first+p.second, cur+p.second); + int cur = root->getStatus(p[0], p[0]+p[1]); + curMax = max(curMax, cur+p[1]); + root->setStatus(p[0], p[0]+p[1], cur+p[1]); result.push_back(curMax); } - return result; + return result; } }; From f25b0b168802d4f07c1f8a5770ac8de528df2acc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 21:59:47 -0700 Subject: [PATCH 0852/2729] Update 699.Falling-Squares_SegTree_v1.cpp --- .../699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp index 7aa698df2..b7baf53a0 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v1.cpp @@ -1,4 +1,4 @@ -// 动态开点 +// 线段树可动态开点 class SegTree { From e277cf196eb57d36a8bcbeda5ae7fac7cbe12b26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:00:16 -0700 Subject: [PATCH 0853/2729] Update 699.Falling-Squares_SegTree_v2.cpp --- .../699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp index 5a4297587..6f0cbb4ba 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp @@ -1,3 +1,5 @@ +// 线段树大小在初始化时固定。支持Lazy Tag(延迟标记) + class SegTreeNode { public: From c5eade98536c40849ce3827a785bf53c8bd267b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:00:37 -0700 Subject: [PATCH 0854/2729] Rename 699.Falling-Squares.cpp to 699.Falling-Squares_Heap_v1.cpp --- .../{699.Falling-Squares.cpp => 699.Falling-Squares_Heap_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/699.Falling-Squares/{699.Falling-Squares.cpp => 699.Falling-Squares_Heap_v1.cpp} (100%) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp similarity index 100% rename from Segment_Tree/699.Falling-Squares/699.Falling-Squares.cpp rename to Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp From b14ca1ad5cee0ba44da07e2ce4df00e0a0a47e83 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:00:49 -0700 Subject: [PATCH 0855/2729] Rename 699.Falling-Squares-v2.cpp to 699.Falling-Squares_Heap_v2.cpp --- ...699.Falling-Squares-v2.cpp => 699.Falling-Squares_Heap_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/699.Falling-Squares/{699.Falling-Squares-v2.cpp => 699.Falling-Squares_Heap_v2.cpp} (100%) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares-v2.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp similarity index 100% rename from Segment_Tree/699.Falling-Squares/699.Falling-Squares-v2.cpp rename to Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp From 384f39fd19a2b1eb9e277166beb7c8ec22188c35 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:05:19 -0700 Subject: [PATCH 0856/2729] Update and rename 218.The-Skyline-Problem_segTree.cpp to 218.The-Skyline-Problem_SegTree_v1.cpp --- .../218.The-Skyline-Problem_SegTree_v1.cpp | 81 +++++++++++++++++++ .../218.The-Skyline-Problem_segTree.cpp | 78 ------------------ 2 files changed, 81 insertions(+), 78 deletions(-) create mode 100644 Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegTree_v1.cpp delete mode 100644 Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_segTree.cpp diff --git a/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegTree_v1.cpp b/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegTree_v1.cpp new file mode 100644 index 000000000..63c87774c --- /dev/null +++ b/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegTree_v1.cpp @@ -0,0 +1,81 @@ +// 支持动态开点 + +class SegTree +{ + public: + int start,end,status; + SegTree* left; + SegTree* right; + SegTree(int a, int b, int s):start(a),end(b),status(s),left(NULL),right(NULL){} + + void remove(SegTree* &node) + { + if (node==NULL) return; + remove(node->left); + remove(node->right); + delete node; + node = NULL; + return; + } + + void setStatus(int a, int b, int s) + { + if (a>=end || b<=start) + return; + if (a<=start && b>=end && s>=status) + { + remove(left); + remove(right); + status = s; + return; + } + if (a<=start && b>=end && ssetStatus(a,b,s); + right->setStatus(a,b,s); + status = max(left->status,right->status); + } +}; + +class Solution { +public: + vector>results; + vector> getSkyline(vector>& buildings) + { + if (buildings.size()==0) return {}; + + SegTree* root = new SegTree(0,INT_MAX,0); + for (auto q:buildings) + root->setStatus(q[0],q[1],q[2]); + + DFS(root); + if (results.back()[1]!=0) results.push_back({INT_MAX,0}); + + vector>filteredResults; + for (auto p: results) + { + if (filteredResults.size()!=0 && p[1]==filteredResults.back()[1]) + continue; + filteredResults.push_back({p[0],p[1]}); + } + if (filteredResults.size()!=0 && filteredResults[0][1]==0) filteredResults.erase(filteredResults.begin()); + return filteredResults; + } + + void DFS(SegTree* node) + { + if (node->left==NULL) + results.push_back({node->start,node->status}); + else + { + DFS(node->left); + DFS(node->right); + } + } +}; diff --git a/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_segTree.cpp b/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_segTree.cpp deleted file mode 100644 index ced18e620..000000000 --- a/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_segTree.cpp +++ /dev/null @@ -1,78 +0,0 @@ -class Solution { - class SegTree - { - public: - int start,end,status; - SegTree* left; - SegTree* right; - SegTree(int a, int b, int s):start(a),end(b),status(s),left(NULL),right(NULL){} - - void remove(SegTree* &node) - { - if (node==NULL) return; - remove(node->left); - remove(node->right); - delete node; - node = NULL; - return; - } - - void setStatus(int a, int b, int s) - { - if (a>=end || b<=start) - return; - if (a<=start && b>=end && s>=status) - { - remove(left); - remove(right); - status = s; - return; - } - if (a<=start && b>=end && ssetStatus(a,b,s); - right->setStatus(a,b,s); - status = max(left->status,right->status); - } - }; -public: - vector>results; - vector> getSkyline(vector>& buildings) - { - if (buildings.size()==0) return {}; - - SegTree* root = new SegTree(0,INT_MAX,0); - for (auto q:buildings) - root->setStatus(q[0],q[1],q[2]); - - DFS(root); - if (results.back().second!=0) results.push_back({INT_MAX,0}); - - vector>filteredResults; - for (auto p: results) - { - if (filteredResults.size()!=0 && p.second==filteredResults.back().second) - continue; - filteredResults.push_back({p.first,p.second}); - } - if (filteredResults.size()!=0 && filteredResults[0].second==0) filteredResults.erase(filteredResults.begin()); - return filteredResults; - } - - void DFS(SegTree* node) - { - if (node->left==NULL) - results.push_back({node->start,node->status}); - else - { - DFS(node->left); - DFS(node->right); - } - } -}; From 2d2b21586129df63ddc87862cc6905b556589492 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:08:22 -0700 Subject: [PATCH 0857/2729] Update and rename 218.The-Skyline-Problem_SegmentTree_lazyTag.cpp to 218.The-Skyline-Problem_SegTree_v2.cpp --- .../218.The-Skyline-Problem_SegTree_v2.cpp | 141 ++++++++++++++++++ ...he-Skyline-Problem_SegmentTree_lazyTag.cpp | 124 --------------- 2 files changed, 141 insertions(+), 124 deletions(-) create mode 100644 Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegTree_v2.cpp delete mode 100644 Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegmentTree_lazyTag.cpp diff --git a/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegTree_v2.cpp b/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegTree_v2.cpp new file mode 100644 index 000000000..2327a837c --- /dev/null +++ b/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegTree_v2.cpp @@ -0,0 +1,141 @@ +// 线段树大小在初始化时固定。支持Lazy Tag(延迟标记) + +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MIN; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + +class Solution { + vector>height; // {idx, h} +public: + vector> getSkyline(vector>& buildings) + { + setSet; + for (auto & building: buildings) + { + Set.insert(building[0]); + Set.insert(building[1]); + } + int id = 0; + unordered_mappos2idx; + unordered_mapidx2pos; + for (auto x:Set) + { + pos2idx[x] = id; + idx2pos[id] = x; + id++; + } + + int n = pos2idx.size(); + SegTreeNode* root = new SegTreeNode(0, n-1, 0); + + sort(buildings.begin(), buildings.end(), [](vector&a, vector&b){return a[2]updateRange(pos2idx[building[0]], pos2idx[building[1]]-1, building[2]); + } + + DFS(root); + + vector>rets; + for (int i=0; istart==node->end || node->tag==1) + { + height.push_back({node->start, node->info}); + return; + } + DFS(node->left); + DFS(node->right); + } + +}; diff --git a/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegmentTree_lazyTag.cpp b/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegmentTree_lazyTag.cpp deleted file mode 100644 index 861a04078..000000000 --- a/Segment_Tree/218.The-Skyline-Problem/218.The-Skyline-Problem_SegmentTree_lazyTag.cpp +++ /dev/null @@ -1,124 +0,0 @@ -class Solution { - class SegTreeNode - { - public: - SegTreeNode* left; - SegTreeNode* right; - int start, end; - int info; - int tag; - SegTreeNode(int a, int b):start(a),end(b),info(0),tag(0),left(NULL),right(NULL){} - }; - - void init(SegTreeNode* node, int a, int b) // init for range [a,b] - { - if (a==b) - { - node->info = 0; - return; - } - int mid = (a+b)/2; - if (node->left==NULL) - { - node->left = new SegTreeNode(a, mid); - node->right = new SegTreeNode(mid+1, b); - } - init(node->left, a, mid); - init(node->right, mid+1, b); - - node->info = 0; // write your own logic - } - - void updateRange(SegTreeNode* node, int a, int b, int val) - { - if (b < node->start || a > node->end ) - return; - if (node->start == node->end) - { - node->info = max(node->info, val); - return; - } - if (a <= node->start && node->end <=b && val >= node->info) - { - // write your own logic - node->info = val; - node->tag = 1; - return; - } - - pushDown(node); - node->info = max(node->info, val); - - updateRange(node->left, a, b, val); - updateRange(node->right, a, b, val); - } - - - void pushDown(SegTreeNode* node) - { - if (node->tag!=0) - { - node->left->info = node->info; - node->right->info = node->info; - node->left->tag = 1; - node->right->tag = 1; - node->tag = 0; - } - } - - vector>height; // {idx, h} -public: - vector> getSkyline(vector>& buildings) - { - setSet; - for (auto & building: buildings) - { - Set.insert(building[0]); - Set.insert(building[1]); - } - int id = 0; - unordered_mappos2idx; - unordered_mapidx2pos; - for (auto x:Set) - { - pos2idx[x] = id; - idx2pos[id] = x; - id++; - } - - int n = pos2idx.size(); - SegTreeNode* root = new SegTreeNode(0, n-1); - init(root, 0, n-1); - - sort(buildings.begin(), buildings.end(), [](vector&a, vector&b){return a[2]>rets; - for (int i=0; istart==node->end || node->tag==1) - { - height.push_back({node->start, node->info}); - return; - } - DFS(node->left); - DFS(node->right); - } - -}; From 7b78f707560f4b10618f477a8ffdca8cbc365434 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:08:59 -0700 Subject: [PATCH 0858/2729] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 919ad89af..2bf955870 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -61,7 +61,7 @@ class SegTreeNode { if (b < start || a > end ) { - return 0; // check with your own logic + return INT_MIN; // check with your own logic } if (a <= start && end <=b) { From e349c5eebc6c7d353edf7a305f833155853e9f76 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:10:10 -0700 Subject: [PATCH 0859/2729] Update 699.Falling-Squares_SegTree_v2.cpp --- .../699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp index 6f0cbb4ba..9b43d96b8 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_SegTree_v2.cpp @@ -63,7 +63,7 @@ class SegTreeNode { if (b < start || a > end ) { - return 0; // check with your own logic + return INT_MIN; // check with your own logic } if (a <= start && end <=b) { From d8bf11bd6433bb11d6d7d3c3bfb0d30893b22dca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:19:45 -0700 Subject: [PATCH 0860/2729] Create range_sum.cpp --- Template/SegmentTree/range_sum.cpp | 99 ++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Template/SegmentTree/range_sum.cpp diff --git a/Template/SegmentTree/range_sum.cpp b/Template/SegmentTree/range_sum.cpp new file mode 100644 index 000000000..4eebd6dd5 --- /dev/null +++ b/Template/SegmentTree/range_sum.cpp @@ -0,0 +1,99 @@ +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val * (end-start+1); + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +int main() +{ + SegTreeNode* root = new SegTreeNode(0, length-1); + + for (auto& update: updates) + { + int start = update[0], end = update[1], val = update[2]; + root->updateRange(start, end ,val); // set the range [start, end] with val + } + + for (auto& query: queries) + { + int start = query[0], end = query[1]; + ret[i] = root->updateRange(start, end); // get the range sum over [start, end] + } +} From ec66da36d4b9eb03f7b4453dc865fda5f34fec09 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:20:24 -0700 Subject: [PATCH 0861/2729] Delete SegmentTree_Basic.cpp --- Template/SegmentTree/SegmentTree_Basic.cpp | 80 ---------------------- 1 file changed, 80 deletions(-) delete mode 100644 Template/SegmentTree/SegmentTree_Basic.cpp diff --git a/Template/SegmentTree/SegmentTree_Basic.cpp b/Template/SegmentTree/SegmentTree_Basic.cpp deleted file mode 100644 index b04fcffe8..000000000 --- a/Template/SegmentTree/SegmentTree_Basic.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// LeetCode 307. Range Sum Query - Mutable - -class NumArray { - class SegTreeNode - { - public: - SegTreeNode* left; - SegTreeNode* right; - int start, end; - int info; - SegTreeNode(int a, int b):start(a),end(b),info(0),left(NULL),right(NULL){} - }; - - void init(SegTreeNode* node, int a, int b) // init for range [a,b] - { - if (a==b) - { - node->info = nums[a]; - return; - } - int mid = (a+b)/2; - if (node->left==NULL) - { - node->left = new SegTreeNode(a, mid); - node->right = new SegTreeNode(mid+1, b); - } - init(node->left, a, mid); - init(node->right, mid+1, b); - - node->info = node->left->info + node->right->info; // write your own logic - } - - void updateSingle(SegTreeNode* node, int id, int val) - { - if (id < node->start || id > node->end ) return; - if (node->start == node->end) - { - node->info = val; - return; - } - updateSingle(node->left, id, val); - updateSingle(node->right, id, val); - node->info = node->left->info + node->right->info; // write your own logic - } - - int queryRange(SegTreeNode* node, int a, int b) - { - if (b < node->start || a > node->end ) - { - return 0; // write your own logic - } - if (a <= node->start && b>=node->end) - { - return node->info; // write your own logic - } - return queryRange(node->left, a, b) + queryRange(node->right, a, b); // write your own logic - } - - vector nums; - SegTreeNode* root; - -public: - NumArray(vector nums) - { - this->nums = nums; - root = new SegTreeNode(0, nums.size()-1); - init(root, 0, nums.size()-1); - } - - void update(int i, int val) - { - updateSingle(root, i, val); - } - - int sumRange(int i, int j) - { - return queryRange(root, i, j); - } -}; - From e806c19a0ae668204ed3e5cfa99781466d5bb2a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:20:30 -0700 Subject: [PATCH 0862/2729] Delete SegmentTree_LazyTag.cpp --- Template/SegmentTree/SegmentTree_LazyTag.cpp | 101 ------------------- 1 file changed, 101 deletions(-) delete mode 100644 Template/SegmentTree/SegmentTree_LazyTag.cpp diff --git a/Template/SegmentTree/SegmentTree_LazyTag.cpp b/Template/SegmentTree/SegmentTree_LazyTag.cpp deleted file mode 100644 index add214c04..000000000 --- a/Template/SegmentTree/SegmentTree_LazyTag.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// LeetCode 370. Range Addition - -class Solution { - class SegTreeNode - { - public: - SegTreeNode* left; - SegTreeNode* right; - int start, end; - int info; - int tag; - SegTreeNode(int a, int b):start(a),end(b),info(0),tag(0),left(NULL),right(NULL){} - }; - - void init(SegTreeNode* node, int a, int b) // init for range [a,b] - { - if (a==b) - { - node->info = 0; - return; - } - int mid = (a+b)/2; - if (node->left==NULL) - { - node->left = new SegTreeNode(a, mid); - node->right = new SegTreeNode(mid+1, b); - } - init(node->left, a, mid); - init(node->right, mid+1, b); - - node->info = node->left->info + node->right->info; // write your own logic - } - - void updateRangeBy(SegTreeNode* node, int a, int b, int val) - { - if (b < node->start || a > node->end ) return; - if (a <= node->start && node->end <=b) - { - // write your own logic - node->info += val * len(node); - node->tag += val; - return; - } - - pushDown(node); - updateRangeBy(node->left, a, b, val); - updateRangeBy(node->right, a, b, val); - - node->info = node->left->info + node->right->info; // write your own logic - } - - int len(SegTreeNode* node) - { - return node->end - node->start + 1; - } - - void pushDown(SegTreeNode* node) - { - if (node->tag!=0) - { - node->left->info += len(node->left) * node->tag; - node->right->info += len(node->right) * node->tag; - node->left->tag += node->tag; - node->right->tag += node->tag; - node->tag = 0; - } - } - - int queryRange(SegTreeNode* node, int a, int b) - { - if (b < node->start || a > node->end ) - { - return 0; // write your own logic - } - if (a <= node->start && b>=node->end) - { - return node->info; // write your own logic - } - pushDown(node); - return queryRange(node->left, a, b) + queryRange(node->right, a, b); // write your own logic - } - - SegTreeNode* root; - -public: - vector getModifiedArray(int length, vector>& updates) - { - SegTreeNode* root = new SegTreeNode(0, length-1); - - init(root, 0, length-1); - - for (auto& update: updates) - { - updateRangeBy(root, update[0], update[1], update[2]); - } - vectorrets(length); - for (int i=0; i Date: Sun, 5 Jun 2022 22:33:28 -0700 Subject: [PATCH 0863/2729] Update 370.Range-Addition_SegmentTree_lazyTag.cpp --- ...370.Range-Addition_SegmentTree_lazyTag.cpp | 136 +++++++++--------- 1 file changed, 71 insertions(+), 65 deletions(-) diff --git a/Segment_Tree/370.Range-Addition/370.Range-Addition_SegmentTree_lazyTag.cpp b/Segment_Tree/370.Range-Addition/370.Range-Addition_SegmentTree_lazyTag.cpp index d26b0c13d..14e9e8d19 100644 --- a/Segment_Tree/370.Range-Addition/370.Range-Addition_SegmentTree_lazyTag.cpp +++ b/Segment_Tree/370.Range-Addition/370.Range-Addition_SegmentTree_lazyTag.cpp @@ -1,98 +1,104 @@ -class Solution { - class SegTreeNode - { - public: - SegTreeNode* left; - SegTreeNode* right; - int start, end; - int info; - int tag; - SegTreeNode(int a, int b):start(a),end(b),info(0),tag(0),left(NULL),right(NULL){} - }; - - void init(SegTreeNode* node, int a, int b) // init for range [a,b] - { +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + LL delta; + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + delta = 0; + start = a, end = b; if (a==b) { - node->info = 0; + info = val; return; - } + } int mid = (a+b)/2; - if (node->left==NULL) + if (left==NULL) { - node->left = new SegTreeNode(a, mid); - node->right = new SegTreeNode(mid+1, b); - } - init(node->left, a, mid); - init(node->right, mid+1, b); - - node->info = 0; // write your own logic - } + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } - void updateRange(SegTreeNode* node, int a, int b, int val) + void pushDown() { - if (b < node->start || a > node->end ) - return; - if (a <= node->start && b>=node->end) + if (tag==1 && left) { - node->info += val * (node->end-node->start+1); - node->tag += val; - return; - } - - pushdown(node); // erase lazy tag and propagate down - updateRange(node->left, a, b, val); - updateRange(node->right, a, b, val); - } + left->delta += delta; + right->delta += delta; + left->tag = 1; + right->tag = 1; + tag = 0; + delta = 0; + } + } - void pushdown(SegTreeNode* node) - { - if (node->tag != 0) + void updateRangeBy(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] { - node->left->tag += node->tag; - node->right->tag += node->tag; - node->left->info += node->tag * (node->left->end-node->left->start+1); - node->right->info += node->tag * (node->right->end-node->right->start+1); - node->tag = 0; + delta += val; + tag = 1; + return; } + + if (left) + { + pushDown(); + left->updateRangeBy(a, b, val); + right->updateRangeBy(a, b, val); + info = left->info + right->info; // write your own logic + } } - int querySingle(SegTreeNode* node, int id) + LL queryRange(int a, int b) // query the maximum value within range [a,b] { - if (id < node->start || id > node->end ) + if (b < start || a > end ) { - return INT_MAX; // write your own logic + return 0; // check with your own logic } - if (node->start==id && node->end==id) + if (a <= start && end <=b) { - return node->info; + return info + delta*(end-start+1); // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; } - pushdown(node); - int a = querySingle(node->left, id); - int b = querySingle(node->right, id); - if (a!=INT_MAX) return a; - else if (b!=INT_MAX) return b; - else return INT_MAX; - } - - - + return info; // should not reach here + } +}; + +class Solution { public: vector getModifiedArray(int length, vector>& updates) { - SegTreeNode* root = new SegTreeNode(0, length-1); - init(root, 0, length-1); + SegTreeNode* root = new SegTreeNode(0, length-1, 0); for (auto update: updates) { - updateRange(root, update[0], update[1], update[2]); + root->updateRangeBy(update[0], update[1], update[2]); } vectorrets(length); for (int i=0; iqueryRange(i, i); } return rets; From 4a3ea52b7bffe3eed039b16f8c0786f701951982 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:33:44 -0700 Subject: [PATCH 0864/2729] Rename 370.Range-Addition_SegmentTree_lazyTag.cpp to 370.Range-Addition_SegTree_v2.cpp --- ..._SegmentTree_lazyTag.cpp => 370.Range-Addition_SegTree_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/370.Range-Addition/{370.Range-Addition_SegmentTree_lazyTag.cpp => 370.Range-Addition_SegTree_v2.cpp} (100%) diff --git a/Segment_Tree/370.Range-Addition/370.Range-Addition_SegmentTree_lazyTag.cpp b/Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree_v2.cpp similarity index 100% rename from Segment_Tree/370.Range-Addition/370.Range-Addition_SegmentTree_lazyTag.cpp rename to Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree_v2.cpp From 45a4754906a02d48007c0a452f53d513afecc7b7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:34:38 -0700 Subject: [PATCH 0865/2729] Update Readme.md --- Segment_Tree/370.Range-Addition/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Segment_Tree/370.Range-Addition/Readme.md b/Segment_Tree/370.Range-Addition/Readme.md index c8dbe7097..2ad786890 100644 --- a/Segment_Tree/370.Range-Addition/Readme.md +++ b/Segment_Tree/370.Range-Addition/Readme.md @@ -1,9 +1,9 @@ ### 370.Range-Addition -#### 解法1: +#### 解法1:差分数组 此题比较简单的解法是用差分数组```diff```。```diff[i]```表示```nums[i]```比```nums[i-1]```大多少。这样如果已知```nums[i-1]```,那么就有```diff[i]=nums[i-1]+diff[i]```。本题中的三元参数```update(i,j,k)```恰好就是给出了这样的差分数组的信息:```diff[i]+=k, diff[j+1]-=k```. -#### 解法2: +#### 解法2:线段树 本题和307很相似,也可以用线段树来实现。最大的区别就是本题中需要实现的是区间更新。在线段树的basic版本中(LC307),我们实现的都是单点更新,用单点更新来实现区间更细,效率肯定很低。 本题实现的是线段树的进阶版本,使用lazy tag来实现区间更新的延迟推广。具体的说,我们想要将区间[a:b]增加1时,不一定需要立即下沉到每个叶子节点将其info增1。如果我们没有对[a:b]中的任何一个叶子节点做查询的话,意味着不需要任何下沉操作。我们只增加[a:b]对应的节点的info,但同时标记该节点的tag为1。如果以后某个时刻,我们需要下沉访问某个下层区间或者叶子节点,那么在下沉的过程中必然会重新经过[a:b]对应的node,此时我们顺便将tag信息读入并在访问下层区间或叶子节点时,将它们的info加上这个“延迟加载”的1就行。 From aa41220d60c9de700ac5198e37f1b4f48e8c1b3d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:35:03 -0700 Subject: [PATCH 0866/2729] Rename 370.Range-Addition.cpp to 370.Range-Addition_DiffArray.cpp --- .../{370.Range-Addition.cpp => 370.Range-Addition_DiffArray.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/370.Range-Addition/{370.Range-Addition.cpp => 370.Range-Addition_DiffArray.cpp} (100%) diff --git a/Segment_Tree/370.Range-Addition/370.Range-Addition.cpp b/Segment_Tree/370.Range-Addition/370.Range-Addition_DiffArray.cpp similarity index 100% rename from Segment_Tree/370.Range-Addition/370.Range-Addition.cpp rename to Segment_Tree/370.Range-Addition/370.Range-Addition_DiffArray.cpp From 99675442af6c3ef01499345559d92a14d5a48ec9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:35:12 -0700 Subject: [PATCH 0867/2729] Delete 370.Range-Addition_segTree.cpp --- .../370.Range-Addition_segTree.cpp | 50 ------------------- 1 file changed, 50 deletions(-) delete mode 100644 Segment_Tree/370.Range-Addition/370.Range-Addition_segTree.cpp diff --git a/Segment_Tree/370.Range-Addition/370.Range-Addition_segTree.cpp b/Segment_Tree/370.Range-Addition/370.Range-Addition_segTree.cpp deleted file mode 100644 index 8849e611c..000000000 --- a/Segment_Tree/370.Range-Addition/370.Range-Addition_segTree.cpp +++ /dev/null @@ -1,50 +0,0 @@ -class Solution { - class SegTree - { - public: - int start,end,status; - SegTree* left; - SegTree* right; - SegTree(int a, int b, int s):start(a),end(b),status(s),left(NULL),right(NULL){} - - void setStatus(int a, int b, int s) - { - if (a<=start && b>=end && left==NULL) // bottom node condition 1; - { - status += s; - return; - } - if (a>=end || b<=start) // bottom node condition 2; - return; - int mid = start+(end-start)/2; - if (left==NULL) // no children? create them - { - left = new SegTree(start,mid,status); - right = new SegTree(mid,end,status); - } // recursion - left->setStatus(a,b,s); - right->setStatus(a,b,s); - } - }; -public: - vector getModifiedArray(int length, vector>& updates) - { - SegTree* root = new SegTree(0,length,0); - for (auto x:updates) - root->setStatus(x[0],x[1]+1,x[2]); - vectorresults(length); - DFS(root,results); - return results; - } - void DFS(SegTree* node, vector&results) - { - if (node->left!=NULL) - { - DFS(node->left,results); - DFS(node->right,results); - return; - } - for (int i=node->start; iend; i++) - results[i] = node->status; - } -}; From 3fb99e68fc594b827594963e609a75c502432094 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:35:23 -0700 Subject: [PATCH 0868/2729] Rename 370.Range-Addition_SegTree_v2.cpp to 370.Range-Addition_SegTree.cpp --- ...nge-Addition_SegTree_v2.cpp => 370.Range-Addition_SegTree.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/370.Range-Addition/{370.Range-Addition_SegTree_v2.cpp => 370.Range-Addition_SegTree.cpp} (100%) diff --git a/Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree_v2.cpp b/Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree.cpp similarity index 100% rename from Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree_v2.cpp rename to Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree.cpp From c2fb4131365019447bae3e67089017d87455e8a3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:35:45 -0700 Subject: [PATCH 0869/2729] Update 370.Range-Addition_SegTree.cpp --- Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree.cpp b/Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree.cpp index 14e9e8d19..aedfcc976 100644 --- a/Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree.cpp +++ b/Segment_Tree/370.Range-Addition/370.Range-Addition_SegTree.cpp @@ -41,7 +41,7 @@ class SegTreeNode } } - void updateRangeBy(int a, int b, int val) // set range [a,b] with val + void updateRangeBy(int a, int b, int val) // increase range [a,b] by val { if (b < start || a > end ) // not covered by [a,b] at all return; From 3caca8a52d630e1467284fa6586d53f32390a89a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:36:16 -0700 Subject: [PATCH 0870/2729] Create range_sum_increase_by.cpp --- .../SegmentTree/range_sum_increase_by.cpp | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Template/SegmentTree/range_sum_increase_by.cpp diff --git a/Template/SegmentTree/range_sum_increase_by.cpp b/Template/SegmentTree/range_sum_increase_by.cpp new file mode 100644 index 000000000..578a1f61f --- /dev/null +++ b/Template/SegmentTree/range_sum_increase_by.cpp @@ -0,0 +1,85 @@ +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + LL delta; + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->delta += delta; + right->delta += delta; + left->tag = 1; + right->tag = 1; + tag = 0; + delta = 0; + } + } + + void updateRangeBy(int a, int b, int val) // increase range [a,b] by val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + delta += val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRangeBy(a, b, val); + right->updateRangeBy(a, b, val); + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info + delta*(end-start+1); // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; From 0a04cc0a450d7d7bcdf8d55dc7f668b8f318b4ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:41:15 -0700 Subject: [PATCH 0871/2729] Update Readme.md --- Readme.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 9944d615a..a02f8c91e 100644 --- a/Readme.md +++ b/Readme.md @@ -271,12 +271,10 @@ [1902](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order), #### [Segment Tree](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/) -* ``Basics`` [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (H-) [1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1649.Create-Sorted-Array-through-Instructions](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions) (H-) [1157.Online-Majority-Element-In-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1157.Online-Majority-Element-In-Subarray) (H) -* ``Lazy Tag`` [370.Range-Addition](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/370.Range-Addition) (H) [218.The-Skyline-Problem](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/218.The-Skyline-Problem) (H+) [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) @@ -1229,6 +1227,7 @@ * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) +[370.Range-Addition](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/370.Range-Addition) (H-) [056.Merge-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Others/056.Merge-Intervals) (M) [057.Insert-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Others/057.Insert-Interval) (M) [732.My-Calendar-III](https://github.com/wisdompeak/LeetCode/tree/master/Others/732.My-Calendar-III) (M) From 3fe5b5450cbf301aaa706264c215c25a6dbce455 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:44:16 -0700 Subject: [PATCH 0872/2729] Create range_module.cpp --- Template/SegmentTree/range_module.cpp | 90 +++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Template/SegmentTree/range_module.cpp diff --git a/Template/SegmentTree/range_module.cpp b/Template/SegmentTree/range_module.cpp new file mode 100644 index 000000000..98b214af6 --- /dev/null +++ b/Template/SegmentTree/range_module.cpp @@ -0,0 +1,90 @@ +// 支持动态增减节点 + +class SegTree +{ + public: + int start, end; + bool status; + SegTree* left; + SegTree* right; + SegTree(int a, int b, bool T):start(a),end(b),status(T),left(NULL),right(NULL){} + + void remove(SegTree* &node) + { + if (node==NULL) return; + remove(node->left); + remove(node->right); + delete node; + node = NULL; + return; + } + + void setStatus(int a, int b, bool T) + { + if (a<=start && b>=end) // bottom condition 1: [a,b)>[start,end) + { + remove(left); + remove(right); + status = T; + return; + } + if (a>=end || b<=start) // bottom condition 2: [a,b) do not intersect with [start,end) + return; + int mid = start+(end-start)/2; + if (left==NULL) // no children? create them! + { + left = new SegTree(start,mid,status); + right = new SegTree(mid,end,status); + } + left->setStatus(a,b,T); + right->setStatus(a,b,T); + status =left->status && right->status; + } + + bool getStatus(int a, int b) + { + if (a<=start && b>=end) // bottom condition 1: [a,b)>[start,end) + return status; + if (a>=end || b<=start) // bottom condition 2: [a,b) do not intersect with [start,end) + return true; + if (left==NULL) + return status; + int mid = start+(end-start)/2; + bool L = left->getStatus(a,b); + bool R = right->getStatus(a,b); + return L&&R; + } +}; + +class RangeModule { +public: + + SegTree root = SegTree(0,1e9,false); + + RangeModule() + { + } + + void addRange(int left, int right) + { + root.setStatus(left,right,true); + } + + bool queryRange(int left, int right) + { + return root.getStatus(left,right); + } + + void removeRange(int left, int right) + { + root.setStatus(left,right,false); + } +}; + +/** + * Your RangeModule object will be instantiated and called as such: + * RangeModule obj = new RangeModule(); + * obj.addRange(left,right); + * bool param_2 = obj.queryRange(left,right); + * obj.removeRange(left,right); + */ From 225b84577a5f9d9741b78afa892763f0002d0cfd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:44:24 -0700 Subject: [PATCH 0873/2729] Delete SegmentTree_LazyTag_Discretization.cpp --- .../SegmentTree_LazyTag_Discretization.cpp | 113 ------------------ 1 file changed, 113 deletions(-) delete mode 100644 Template/SegmentTree/SegmentTree_LazyTag_Discretization.cpp diff --git a/Template/SegmentTree/SegmentTree_LazyTag_Discretization.cpp b/Template/SegmentTree/SegmentTree_LazyTag_Discretization.cpp deleted file mode 100644 index 6fc580be6..000000000 --- a/Template/SegmentTree/SegmentTree_LazyTag_Discretization.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// LeetCode 699. Falling Squares - -class Solution { - class SegTreeNode - { - public: - SegTreeNode* left; - SegTreeNode* right; - int start, end; - int info; // the max height of the range - bool tag; - SegTreeNode(int a, int b):start(a),end(b),info(0),tag(0),left(NULL),right(NULL){} - }; - - void init(SegTreeNode* node, int a, int b) // init for range [a,b] - { - if (a==b) - { - node->info = 0; - return; - } - int mid = (a+b)/2; - if (node->left==NULL) - { - node->left = new SegTreeNode(a, mid); - node->right = new SegTreeNode(mid+1, b); - } - init(node->left, a, mid); - init(node->right, mid+1, b); - - node->info = 0; // write your own logic - } - - void updateRange(SegTreeNode* node, int a, int b, int val) - { - if (b < node->start || a > node->end ) // no intersection - return; - if (a <= node->start && node->end <=b) - { - node->info = val; - node->tag = 1; - return; - } - - pushDown(node); - updateRange(node->left, a, b, val); - updateRange(node->right, a, b, val); - - node->info = max(node->left->info, node->right->info); // write your own logic - } - - int queryRange(SegTreeNode* node, int a, int b) - { - if (b < node->start || a > node->end ) - { - return 0; // write your own logic - } - if (a <= node->start && b>=node->end) - { - return node->info; // write your own logic - } - pushDown(node); - return max(queryRange(node->left, a, b), queryRange(node->right, a, b)); // write your own logic - } - - void pushDown(SegTreeNode* node) - { - if (node->tag==true) - { - node->left->info = node->info; - node->right->info = node->info; - node->left->tag = 1; - node->right->tag = 1; - node->tag = 0; - } - } - - -public: - vector fallingSquares(vector>& positions) - { - setSet; - for (auto & rect: positions) - { - Set.insert(rect[0]); - Set.insert(rect[0]+rect[1]); - } - unordered_mappos2idx; - int idx = 0; - for (auto x: Set) - { - pos2idx[x] = idx; - idx++; - } - int n = pos2idx.size(); - - SegTreeNode* root = new SegTreeNode(0, n-1); - init(root, 0, n-1); - - int maxH = 0; - vectorrets; - for (auto & rect: positions) - { - int a = pos2idx[rect[0]]; - int b = pos2idx[rect[0]+rect[1]]; - int h = queryRange(root, a, b-1); // [a,b) - updateRange(root, a, b-1, h + rect[1]); - maxH = max(maxH, h + rect[1]); - rets.push_back(maxH); - } - return rets; - } -}; From 67d0c05c6deb6a7c979a252ac364c2939e61ef5e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:55:19 -0700 Subject: [PATCH 0874/2729] Create 2286.Booking-Concert-Tickets-in-Groups.cpp --- ...2286.Booking-Concert-Tickets-in-Groups.cpp | 239 ++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 Segment_Tree/2286.Booking-Concert-Tickets-in-Groups.cpp diff --git a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups.cpp b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups.cpp new file mode 100644 index 000000000..d3f2b7a33 --- /dev/null +++ b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups.cpp @@ -0,0 +1,239 @@ +using LL = long long; + +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the max height of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) + { + if (b < start || a > end ) // no intersection + return; + + if (a <= start && end <=b) + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) + { + if (b < start || a > end ) + { + return INT_MIN; // write your own logic + } + if (a <= start && end <=b) + { + return info; // write your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); + return ret; + } + + return info; + } + +}; + + +class SegTreeNode2 +{ + public: + SegTreeNode2* left = NULL; + SegTreeNode2* right = NULL; + int start, end; + LL info; // the sum value over the range + bool tag; + + SegTreeNode2(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode2(a, mid, val); + right = new SegTreeNode2(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val * (end-start+1); + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + +class BookMyShow { + int n,m; + vectorleft; + int p = 0; + SegTreeNode* root; + SegTreeNode2* root2; + + +public: + BookMyShow(int n, int m) { + this->n = n; + this->m = m; + left.resize(n); + for (int i=0; i gather(int k, int maxRow) + { + int l = 0, r = maxRow; + while (lqueryRange(0, mid) >= k ) + r = mid; + else + l = mid+1; + } + + if (root->queryRange(0, l) < k ) + return {}; + + left[l] -= k; + root->updateRange(l, l, left[l]); + root2->updateRange(l, l, left[l]); + + return {l,m-(left[l]+k)}; + } + + bool scatter(int k, int maxRow) + { + if (root2->queryRange(0, maxRow) < k) + return false; + + while (k>0) + { + int t = min(k, left[p]); + left[p] -= t; + root->updateRange(p, p, left[p]); + root2->updateRange(p, p, left[p]); + k -= t; + if (left[p]==0) p++; + } + + return true; + } +}; + +/** + * Your BookMyShow object will be instantiated and called as such: + * BookMyShow* obj = new BookMyShow(n, m); + * vector param_1 = obj->gather(k,maxRow); + * bool param_2 = obj->scatter(k,maxRow); + */ From c0c253ea668c4c3fd554252a80508d48cb5f8781 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:56:20 -0700 Subject: [PATCH 0875/2729] Rename Segment_Tree/2286.Booking-Concert-Tickets-in-Groups.cpp to Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp --- .../2286.Booking-Concert-Tickets-in-Groups.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/{ => 2286.Booking-Concert-Tickets-in-Groups}/2286.Booking-Concert-Tickets-in-Groups.cpp (100%) diff --git a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups.cpp b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp similarity index 100% rename from Segment_Tree/2286.Booking-Concert-Tickets-in-Groups.cpp rename to Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp From 8a3543b9c15f8c588ec336b9a43009b718e42ded Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 22:56:54 -0700 Subject: [PATCH 0876/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a02f8c91e..8ff41002a 100644 --- a/Readme.md +++ b/Readme.md @@ -278,8 +278,8 @@ [370.Range-Addition](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/370.Range-Addition) (H) [218.The-Skyline-Problem](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/218.The-Skyline-Problem) (H+) [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) -* ``Others`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) +[2286.Booking-Concert-Tickets-in-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups) (H-) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 2bd117e7ccd6d012aa4e87cd17d337db4f328a67 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 23:12:00 -0700 Subject: [PATCH 0877/2729] Update 2286.Booking-Concert-Tickets-in-Groups.cpp --- ...2286.Booking-Concert-Tickets-in-Groups.cpp | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp index d3f2b7a33..daec800cc 100644 --- a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp +++ b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp @@ -170,7 +170,7 @@ class SegTreeNode2 class BookMyShow { int n,m; - vectorleft; + vectorseats; int p = 0; SegTreeNode* root; SegTreeNode2* root2; @@ -180,10 +180,10 @@ class BookMyShow { BookMyShow(int n, int m) { this->n = n; this->m = m; - left.resize(n); + seats.resize(n); for (int i=0; iqueryRange(0, l) < k ) return {}; - left[l] -= k; - root->updateRange(l, l, left[l]); - root2->updateRange(l, l, left[l]); + seats[l] -= k; + root->updateRange(l, l, seats[l]); + root2->updateRange(l, l, seats[l]); - return {l,m-(left[l]+k)}; + return {l,m-(seats[l]+k)}; } bool scatter(int k, int maxRow) @@ -219,12 +219,12 @@ class BookMyShow { while (k>0) { - int t = min(k, left[p]); - left[p] -= t; - root->updateRange(p, p, left[p]); - root2->updateRange(p, p, left[p]); + int t = min(k, seats[p]); + seats[p] -= t; + root->updateRange(p, p, seats[p]); + root2->updateRange(p, p, seats[p]); k -= t; - if (left[p]==0) p++; + if (seats[p]==0) p++; } return true; From d931aab76e26fe33c106a6fcd4ad5b98aaedaeab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 23:19:31 -0700 Subject: [PATCH 0878/2729] Create Readme.md --- .../2286.Booking-Concert-Tickets-in-Groups/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/Readme.md diff --git a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/Readme.md b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/Readme.md new file mode 100644 index 000000000..5059c6ae3 --- /dev/null +++ b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/Readme.md @@ -0,0 +1,9 @@ +### 2286.Booking-Concert-Tickets-in-Groups + +根据题意,我们需要给维护一个数组seats,代表每一行剩余的座椅数目。 + +如果遇到的是scatter,那么我们就从前往后查看每一行,有任何剩余的座位就都分配出去。如果某一行的座位都已经被scatter分配完了,那么这意味着该行及其之前的行都没有空座了,今后可以忽略。所以我们需要一个指针p,来指向当前仍有作为剩余的最小行号。但是这里有一个问题,如果对于某个scatter query,我们试图一行一行地去查询和分配座位后,发现无法满足要求(所有分配的座位必须在指定的maxRow之前)。于是我们需要有一个函数,支持查看[0,maxRow]这个区间内还剩多少个座位。如果查询得知剩余座位不够,就可以直接返回false。如果查询得知剩余座位足够,我们再逐行更新```seats[p]```,将分配完所有座位的行号都置零。显然,这是区间求和,这需要一个选段树或者BIT的数据结构。 + +如果遇到的是gather,那么我们就需要找到最小的行号i,满足```seats[i]>=k```.那么如何高效地实现这个功能呢?也是用线段树。我们需要一个函数,支持查询[0,row]这个区间内的最大值。我们可以通过二分法,快速查到满足条件的最小的row。那么我们就可以更新```seats[row]-=k```. + +所以,我们需要利用两种线段树的模板,分别实现查询rangeSum和rangeMax的功能。当然,也要支持节点数值的动态修改。 From 4ca41433ae81eadd1ec299d5fe397771f8731716 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Jun 2022 23:56:21 -0700 Subject: [PATCH 0879/2729] Update range_sum.cpp --- Template/SegmentTree/range_sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_sum.cpp b/Template/SegmentTree/range_sum.cpp index 4eebd6dd5..7e7ad95fe 100644 --- a/Template/SegmentTree/range_sum.cpp +++ b/Template/SegmentTree/range_sum.cpp @@ -58,7 +58,7 @@ class SegTreeNode } } - LL queryRange(int a, int b) // query the maximum value within range [a,b] + LL queryRange(int a, int b) // query the sum over range [a,b] { if (b < start || a > end ) { From bb78a4570f31829421bc528d9cc61b8aff28cb05 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 8 Jun 2022 15:56:46 -0700 Subject: [PATCH 0880/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8ff41002a..6c5c036d4 100644 --- a/Readme.md +++ b/Readme.md @@ -189,7 +189,7 @@ [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) -[2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/new/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) +[2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) [2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) From 44c7d5345b1c030f469164cbeb646210a8d61d31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Jun 2022 08:53:46 -0700 Subject: [PATCH 0881/2729] Create 2296.Design-a-Text-Editor_v1.cpp --- .../2296.Design-a-Text-Editor_v1.cpp | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v1.cpp diff --git a/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v1.cpp b/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v1.cpp new file mode 100644 index 000000000..cf6ae12be --- /dev/null +++ b/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v1.cpp @@ -0,0 +1,83 @@ +class TextEditor { + listt; + list::iterator iter; +public: + TextEditor() { + t.push_back('#'); + iter = t.begin(); + } + + void addText(string text) + { + for (auto ch: text) + { + t.insert(iter, ch); + } + } + + int deleteText(int k) + { + int ret = 0; + while (iter!=t.begin() && k>0) + { + auto iter2 = prev(iter); + t.erase(iter2); + k--; + ret++; + } + return ret; + } + + string cursorLeft(int k) + { + while (iter!=t.begin() && k>0) + { + iter = prev(iter); + k--; + } + int p = 10; + while (iter!=t.begin() && p>0) + { + iter = prev(iter); + p--; + } + string ret; + for (int i=0; i<10-p; i++) + { + ret.push_back(*iter); + iter = next(iter); + } + return ret; + } + + string cursorRight(int k) + { + while (*iter!='#' && k>0) + { + iter = next(iter); + k--; + } + int p = 10; + while (iter!=t.begin() && p>0) + { + iter = prev(iter); + p--; + } + string ret; + for (int i=0; i<10-p; i++) + { + ret.push_back(*iter); + iter = next(iter); + } + return ret; + } +}; + +/** + * Your TextEditor object will be instantiated and called as such: + * TextEditor* obj = new TextEditor(); + * obj->addText(text); + * int param_2 = obj->deleteText(k); + * string param_3 = obj->cursorLeft(k); + * string param_4 = obj->cursorRight(k); + */ From 8789f5ea4351e2e64576a8873ea994cb0bc7a008 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Jun 2022 08:54:10 -0700 Subject: [PATCH 0882/2729] Create 2296.Design-a-Text-Editor_v2.cpp --- .../2296.Design-a-Text-Editor_v2.cpp | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v2.cpp diff --git a/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v2.cpp b/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v2.cpp new file mode 100644 index 000000000..a9291983c --- /dev/null +++ b/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v2.cpp @@ -0,0 +1,76 @@ +class TextEditor { + stackst1; + stackst2; +public: + TextEditor() { + + } + + void addText(string text) + { + for (auto ch: text) + st1.push(ch); + } + + int deleteText(int k) + { + int ret = min(k, (int)st1.size()); + for (int i=0; iaddText(text); + * int param_2 = obj->deleteText(k); + * string param_3 = obj->cursorLeft(k); + * string param_4 = obj->cursorRight(k); + */ From cdd0d75cf3cabd4d6bdeff33f4602110ff1e4315 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Jun 2022 08:54:47 -0700 Subject: [PATCH 0883/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 6c5c036d4..8af49f275 100644 --- a/Readme.md +++ b/Readme.md @@ -309,6 +309,7 @@ [460.LFU Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/460.LFU-Cache) (H) [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) +[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) @@ -326,6 +327,7 @@ [1209.Remove-All-Adjacent-Duplicates-in-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1209.Remove-All-Adjacent-Duplicates-in-String-II) (M+) [1586.Binary-Search-Tree-Iterator-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1586.Binary-Search-Tree-Iterator-II) (H) [2197.Replace-Non-Coprime-Numbers-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2197.Replace-Non-Coprime-Numbers-in-Array) (H-) +[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) * ``monotonic stack`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) From 16691e147565417803d958b25433e03a5d6ba7eb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 Jun 2022 17:57:36 -0700 Subject: [PATCH 0884/2729] Create 2291.Maximum-Profit-From-Trading-Stocks.cpp --- .../2291.Maximum-Profit-From-Trading-Stocks.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks/2291.Maximum-Profit-From-Trading-Stocks.cpp diff --git a/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks/2291.Maximum-Profit-From-Trading-Stocks.cpp b/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks/2291.Maximum-Profit-From-Trading-Stocks.cpp new file mode 100644 index 000000000..5e4d26c35 --- /dev/null +++ b/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks/2291.Maximum-Profit-From-Trading-Stocks.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int maximumProfit(vector& present, vector& future, int budget) + { + int n = present.size(); + + vectordp(1001); + for (int i=0; i=present[i]; j--) + { + dp[j] = max(dp[j], dp[j-present[i]]+future[i]-present[i]); + } + + return dp[budget]; + } +}; From 1ca95cd91979b442ecfdd85464fbba55fe362620 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 Jun 2022 17:58:05 -0700 Subject: [PATCH 0885/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8af49f275..47f31a094 100644 --- a/Readme.md +++ b/Readme.md @@ -680,6 +680,7 @@ [1049.Last-Stone-Weight-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1049.Last-Stone-Weight-II) (H-) [1449.Form-Largest-Integer-With-Digits-That-Add-up-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1449.Form-Largest-Integer-With-Digits-That-Add-up-to-Target) (H-) [1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements) (M+) +[2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From b8466d9a7369329ee827b312114a71f9b1116870 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 Jun 2022 18:01:33 -0700 Subject: [PATCH 0886/2729] Create Readme.md --- .../2291.Maximum-Profit-From-Trading-Stocks/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks/Readme.md diff --git a/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks/Readme.md b/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks/Readme.md new file mode 100644 index 000000000..e5a744797 --- /dev/null +++ b/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks/Readme.md @@ -0,0 +1,3 @@ +### 2291.Maximum-Profit-From-Trading-Stocks + +非常直观的01背包问题。挨个遍历物品。考察对于给定某budget情况下,加入这个物品是否能带来更大的收益,即```dp[budget] = max(dp[budget], dp[budget-cost[i]] + profit[i])``` From 1a1b035f037926e84e6cfff0dc62bba7548a87fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 Jun 2022 18:25:26 -0700 Subject: [PATCH 0887/2729] Update Readme.md --- Readme.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Readme.md b/Readme.md index 47f31a094..93813a9f1 100644 --- a/Readme.md +++ b/Readme.md @@ -737,7 +737,6 @@ * ``状态压缩DP`` [465.Optimal-Account-Balancing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/465.Optimal-Account-Balancing) (H) [691.Stickers-to-Spell-Word](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/691.Stickers-to-Spell-Word) (H) -[943.Find-the-Shortest-Superstring](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/943.Find-the-Shortest-Superstring) (H+) [1125.Smallest-Sufficient-Team](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1125.Smallest-Sufficient-Team) (H) [1349.Maximum-Students-Taking-Exam](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1349.Maximum-Students-Taking-Exam) (H) [1411.Number-of-Ways-to-Paint-N×3-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1411.Number-of-Ways-to-Paint-N%C3%973-Grid) (M) @@ -755,11 +754,13 @@ [1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks) (M+) [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) * ``带权二分图`` -[1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) -[1595.Minimum-Cost-to-Connect-Two-Groups-of-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points) (H) -[1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) -[1947.Maximum-Compatibility-Score-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1947.Maximum-Compatibility-Score-Sum) (H) -[2172.Maximum-AND-Sum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array) (H) + [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) + [1595.Minimum-Cost-to-Connect-Two-Groups-of-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points) (H) + [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) + [1947.Maximum-Compatibility-Score-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1947.Maximum-Compatibility-Score-Sum) (H) + [2172.Maximum-AND-Sum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array) (H) + * ``TSP`` + [943.Find-the-Shortest-Superstring](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/943.Find-the-Shortest-Superstring) (H+) * ``Catalan`` [096.Unique-Binary-Search-Trees](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/096.Unique-Binary-Search-Trees) (M+) [1259.Handshakes-That-Don't-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1259.Handshakes-That-Don't-Cross) (M+) From 50cf5fc2d244e9087bbcb03f2f983a7becd7a843 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 Jun 2022 22:42:16 -0700 Subject: [PATCH 0888/2729] Update 2296.Design-a-Text-Editor_v1.cpp --- .../2296.Design-a-Text-Editor_v1.cpp | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v1.cpp b/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v1.cpp index cf6ae12be..84e0a47db 100644 --- a/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v1.cpp +++ b/Design/2296.Design-a-Text-Editor/2296.Design-a-Text-Editor_v1.cpp @@ -3,16 +3,13 @@ class TextEditor { list::iterator iter; public: TextEditor() { - t.push_back('#'); iter = t.begin(); } void addText(string text) { for (auto ch: text) - { t.insert(iter, ch); - } } int deleteText(int k) @@ -24,7 +21,7 @@ class TextEditor { t.erase(iter2); k--; ret++; - } + } return ret; } @@ -35,36 +32,36 @@ class TextEditor { iter = prev(iter); k--; } - int p = 10; - while (iter!=t.begin() && p>0) + int p = 0; + while (iter!=t.begin() && p<10) { iter = prev(iter); - p--; + p++; } string ret; - for (int i=0; i<10-p; i++) + for (int i=0; i0) + while (iter!=t.end() && k>0) { iter = next(iter); k--; } - int p = 10; - while (iter!=t.begin() && p>0) + int p = 0; + while (iter!=t.begin() && p<10) { iter = prev(iter); - p--; + p++; } string ret; - for (int i=0; i<10-p; i++) + for (int i=0; i Date: Fri, 10 Jun 2022 22:56:08 -0700 Subject: [PATCH 0889/2729] Create Readme.md --- Design/2296.Design-a-Text-Editor/Readme.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Design/2296.Design-a-Text-Editor/Readme.md diff --git a/Design/2296.Design-a-Text-Editor/Readme.md b/Design/2296.Design-a-Text-Editor/Readme.md new file mode 100644 index 000000000..a0e60b326 --- /dev/null +++ b/Design/2296.Design-a-Text-Editor/Readme.md @@ -0,0 +1,16 @@ +### 2296.Design-a-Text-Editor + +#### 解法1:链表 +本题需要有一种线性的数据结构,能有一个灵活的指针,可以o(1)地删除指向的内部元素,并且依然可以o(1)的时间左移右移。显然这就是链表。 + +C++里面自带链表结构: +```cpp +listList; +``` +该链表的迭代器就是指针 +···cpp +list::iterator iter; +··· + +#### 解法2:两个栈 +我们以指针为界,左边的部分放入一个栈,右边的部分放入一个栈。删除就意味着将弹出左边栈的顶部元素即可。打印的话,因为不超过10个字符,所以从栈顶拿出10个字符暂存下来再放回去就可以了。 From 28250524958ffec74089c7c84fc3070e6454dd65 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 Jun 2022 22:56:22 -0700 Subject: [PATCH 0890/2729] Update Readme.md --- Design/2296.Design-a-Text-Editor/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Design/2296.Design-a-Text-Editor/Readme.md b/Design/2296.Design-a-Text-Editor/Readme.md index a0e60b326..bdbdf666a 100644 --- a/Design/2296.Design-a-Text-Editor/Readme.md +++ b/Design/2296.Design-a-Text-Editor/Readme.md @@ -8,9 +8,9 @@ C++里面自带链表结构: listList; ``` 该链表的迭代器就是指针 -···cpp +```cpp list::iterator iter; -··· +``` #### 解法2:两个栈 我们以指针为界,左边的部分放入一个栈,右边的部分放入一个栈。删除就意味着将弹出左边栈的顶部元素即可。打印的话,因为不超过10个字符,所以从栈顶拿出10个字符暂存下来再放回去就可以了。 From 1816cbb6bae47edfe6f048411e6b8ea3ec0b1493 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 Jun 2022 23:29:24 -0700 Subject: [PATCH 0891/2729] Update Readme.md --- Design/2296.Design-a-Text-Editor/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Design/2296.Design-a-Text-Editor/Readme.md b/Design/2296.Design-a-Text-Editor/Readme.md index bdbdf666a..c34b28062 100644 --- a/Design/2296.Design-a-Text-Editor/Readme.md +++ b/Design/2296.Design-a-Text-Editor/Readme.md @@ -1,7 +1,7 @@ ### 2296.Design-a-Text-Editor #### 解法1:链表 -本题需要有一种线性的数据结构,能有一个灵活的指针,可以o(1)地删除指向的内部元素,并且依然可以o(1)的时间左移右移。显然这就是链表。 +本题需要有一种线性的数据结构,能有一个灵活的指针,可以o(1)地删除和添加指向的内部元素,并且依然可以o(1)的时间左移右移。显然这就是链表。 C++里面自带链表结构: ```cpp From 8d60b437390e58837b789af3afb54459fddbe6fc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 00:25:35 -0700 Subject: [PATCH 0892/2729] Create 2247.Maximum-Cost-of-Trip-With-K-Highways.cpp --- ...7.Maximum-Cost-of-Trip-With-K-Highways.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways/2247.Maximum-Cost-of-Trip-With-K-Highways.cpp diff --git a/Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways/2247.Maximum-Cost-of-Trip-With-K-Highways.cpp b/Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways/2247.Maximum-Cost-of-Trip-With-K-Highways.cpp new file mode 100644 index 000000000..64a81808c --- /dev/null +++ b/Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways/2247.Maximum-Cost-of-Trip-With-K-Highways.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int maximumCost(int n, vector>& highways, int k) + { + vector>>next(n); + for (auto highway: highways) + { + int a = highway[0], b = highway[1], t = highway[2]; + next[a].push_back({b,t}); + next[b].push_back({a,t}); + } + + int ret = -1; + vector>dp(1<(n, INT_MIN)); + for (int i=0; i>last)&1)==0) continue; + for (auto nxt: next[last]) + { + auto [j, t] = nxt; + if ((state>>j)&1) continue; + dp[state+(1< Date: Sat, 11 Jun 2022 00:26:57 -0700 Subject: [PATCH 0893/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 93813a9f1..cf54fcceb 100644 --- a/Readme.md +++ b/Readme.md @@ -761,6 +761,7 @@ [2172.Maximum-AND-Sum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array) (H) * ``TSP`` [943.Find-the-Shortest-Superstring](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/943.Find-the-Shortest-Superstring) (H+) + [2247.Maximum-Cost-of-Trip-With-K-Highways](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways) (H) * ``Catalan`` [096.Unique-Binary-Search-Trees](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/096.Unique-Binary-Search-Trees) (M+) [1259.Handshakes-That-Don't-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1259.Handshakes-That-Don't-Cross) (M+) From c07794e4ae9d65bbf6a1a5ec45cec79e472a2e43 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 00:33:05 -0700 Subject: [PATCH 0894/2729] Create Readme.md --- .../2247.Maximum-Cost-of-Trip-With-K-Highways/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways/Readme.md diff --git a/Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways/Readme.md b/Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways/Readme.md new file mode 100644 index 000000000..b32e68aa5 --- /dev/null +++ b/Dynamic_Programming/2247.Maximum-Cost-of-Trip-With-K-Highways/Readme.md @@ -0,0 +1,9 @@ +### 2247.Maximum-Cost-of-Trip-With-K-Highways + +本题是说要找出一条最长的路径,恰能包含k+1个节点(起始点可以自由选择)。要求节点不能重复经过(自然边也不会重复经过)。 + +这是一个经典的旅行商问题(TSP)。解法和```943.Find-the-Shortest-Superstring```一样。考虑到节点总数不超过15个,我们可以用二进制数state表示经过的节点的集合。令dp[state][last]表示走过了state所代表的节点集合、并且最后一站是节点last的情况下,所能得到的最优解。假设last与j相邻,且j不在state中,则有状态转移方程 +```cpp +dp[state + (1< Date: Sat, 11 Jun 2022 12:18:12 -0700 Subject: [PATCH 0895/2729] Create 2301.Match-Substring-After-Replacement.cpp --- ...2301.Match-Substring-After-Replacement.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Dynamic_Programming/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement.cpp diff --git a/Dynamic_Programming/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement.cpp b/Dynamic_Programming/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement.cpp new file mode 100644 index 000000000..ef8ed6dc7 --- /dev/null +++ b/Dynamic_Programming/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement.cpp @@ -0,0 +1,35 @@ +class Solution { + bool dp[5001][5001]; + bool table[256][256]; + unordered_map>Map; +public: + bool matchReplacement(string s, string sub, vector>& mappings) + { + int m = s.size(); + int n = sub.size(); + s = "#"+s; + sub = "#"+sub; + + for (auto x: mappings) + { + table[x[0]][x[1]] = 1; + } + + for (int i=0; i<=m; i++) + dp[i][0] = true; + + for (int i=1; i<=m; i++) + for (int j=1; j<=n; j++) + { + if (dp[i-1][j-1]==0) continue; + + if (s[i]==sub[j] || table[sub[j]][s[i]]) + dp[i][j] = dp[i-1][j-1]; + + if (j==n && dp[i][j]==true) + return true; + } + return false; + + } +}; From d45c8b550940a018a33d311bdecd9b7696c92fd4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 12:18:42 -0700 Subject: [PATCH 0896/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index cf54fcceb..aef27a575 100644 --- a/Readme.md +++ b/Readme.md @@ -734,6 +734,7 @@ [1312.Minimum-Insertion-Steps-to-Make-a-String-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1312.Minimum-Insertion-Steps-to-Make-a-String-Palindrome) (M+) [1458.Max-Dot-Product-of-Two-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1458.Max-Dot-Product-of-Two-Subsequences) (M) [1771.Maximize-Palindrome-Length-From-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1771.Maximize-Palindrome-Length-From-Subsequences) (H) +[2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2301.Match-Substring-After-Replacement) (M+) * ``状态压缩DP`` [465.Optimal-Account-Balancing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/465.Optimal-Account-Balancing) (H) [691.Stickers-to-Spell-Word](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/691.Stickers-to-Spell-Word) (H) From 39d80e85321c382000e3f02cbee3284237710a30 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 12:28:27 -0700 Subject: [PATCH 0897/2729] Delete 2301.Match-Substring-After-Replacement.cpp --- ...2301.Match-Substring-After-Replacement.cpp | 35 ------------------- 1 file changed, 35 deletions(-) delete mode 100644 Dynamic_Programming/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement.cpp diff --git a/Dynamic_Programming/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement.cpp b/Dynamic_Programming/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement.cpp deleted file mode 100644 index ef8ed6dc7..000000000 --- a/Dynamic_Programming/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement.cpp +++ /dev/null @@ -1,35 +0,0 @@ -class Solution { - bool dp[5001][5001]; - bool table[256][256]; - unordered_map>Map; -public: - bool matchReplacement(string s, string sub, vector>& mappings) - { - int m = s.size(); - int n = sub.size(); - s = "#"+s; - sub = "#"+sub; - - for (auto x: mappings) - { - table[x[0]][x[1]] = 1; - } - - for (int i=0; i<=m; i++) - dp[i][0] = true; - - for (int i=1; i<=m; i++) - for (int j=1; j<=n; j++) - { - if (dp[i-1][j-1]==0) continue; - - if (s[i]==sub[j] || table[sub[j]][s[i]]) - dp[i][j] = dp[i-1][j-1]; - - if (j==n && dp[i][j]==true) - return true; - } - return false; - - } -}; From 3e5a9650fc8b7ea046db1c83e2e7171d25262c41 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 15:29:06 -0700 Subject: [PATCH 0898/2729] Create 2301.Match-Substring-After-Replacement_KMP.cpp --- ....Match-Substring-After-Replacement_KMP.cpp | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp diff --git a/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp b/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp new file mode 100644 index 000000000..52c8348e7 --- /dev/null +++ b/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp @@ -0,0 +1,72 @@ +class Solution { + bool table[256][256]; +public: + bool matchReplacement(string s, string sub, vector>& mappings) + { + int m = s.size(); + + for (auto x: mappings) + { + table[x[0]][x[1]] = 1; + } + + return strStr(s, sub)!=-1; + } + + bool equal(char a, char b) + { + return (a==b || table[b][a]); + } + + int strStr(string haystack, string needle) + { + string s = haystack; + string p = needle; + int n = s.size(); + int m = p.size(); + + if (m==0) return 0; + if (n==0) return -1; + + vectordp(n,0); + dp[0] = equal(s[0], p[0]); + if (m==1 && dp[0]==1) + return 0; + + vectorsuffix = preprocess(p); + + for (int i=1; i0 && !equal(s[i], p[j])) + j = suffix[j-1]; + dp[i] = j + equal(s[i], p[j]); + + if (dp[i]==p.size()) + return i - p.size() + 1; + } + + return -1; + + } + + vector preprocess(string s) + { + int n = s.size(); + vectordp(n); + dp[0] = 0; + + for (int i=1; i=1 && !equal(s[j],s[i])) + { + j = dp[j-1]; + } + dp[i] = j + equal(s[j], s[i]); + } + + return dp; + } +}; From bac9e06e3e39d5973294c413999b4b9a521ab8ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 15:30:02 -0700 Subject: [PATCH 0899/2729] Create 2301.Match-Substring-After-Replacement_Brute.cpp --- ...atch-Substring-After-Replacement_Brute.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_Brute.cpp diff --git a/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_Brute.cpp b/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_Brute.cpp new file mode 100644 index 000000000..ed30a7934 --- /dev/null +++ b/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_Brute.cpp @@ -0,0 +1,30 @@ +class Solution { + bool table[256][256]; +public: + bool matchReplacement(string s, string sub, vector>& mappings) + { + int m = s.size(); + + for (auto x: mappings) + { + table[x[0]][x[1]] = 1; + } + + for (int i=0; i Date: Sat, 11 Jun 2022 15:30:30 -0700 Subject: [PATCH 0900/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index aef27a575..11ff53c83 100644 --- a/Readme.md +++ b/Readme.md @@ -734,7 +734,6 @@ [1312.Minimum-Insertion-Steps-to-Make-a-String-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1312.Minimum-Insertion-Steps-to-Make-a-String-Palindrome) (M+) [1458.Max-Dot-Product-of-Two-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1458.Max-Dot-Product-of-Two-Subsequences) (M) [1771.Maximize-Palindrome-Length-From-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1771.Maximize-Palindrome-Length-From-Subsequences) (H) -[2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2301.Match-Substring-After-Replacement) (M+) * ``状态压缩DP`` [465.Optimal-Account-Balancing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/465.Optimal-Account-Balancing) (H) [691.Stickers-to-Spell-Word](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/691.Stickers-to-Spell-Word) (H) @@ -856,6 +855,7 @@ [1367.Linked-List-in-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/String/1367.Linked-List-in-Binary-Tree) (H) 1397.Find All Good Strings (TBD) [1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array) (H) +[2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/String/2301.Match-Substring-After-Replacement) (H-) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From cd2262ce4e266a95ec26750cc93fc60a7e8e27c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 15:41:39 -0700 Subject: [PATCH 0901/2729] Create Readme.md --- String/2301.Match-Substring-After-Replacement/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 String/2301.Match-Substring-After-Replacement/Readme.md diff --git a/String/2301.Match-Substring-After-Replacement/Readme.md b/String/2301.Match-Substring-After-Replacement/Readme.md new file mode 100644 index 000000000..50da0a046 --- /dev/null +++ b/String/2301.Match-Substring-After-Replacement/Readme.md @@ -0,0 +1,7 @@ +### 2301.Match-Substring-After-Replacement + +#### 解法1:暴力 +本题暴力查验字符串匹配,时间是o(N^2),有AC的可能。 + +#### 解法2:KMP +本题的本质其实就是在一个字符串中查找匹配的子串。最直观的高效解法就是KMP。我们只需要略微修改KMP算法中关于“两个字符相等”的定义。定义一个新的```equal(char a, char b)```. 当两个字符相等,或者sub的字符可以映射到s的字符中时,就返回true。这样KMP就可以直接用于此题。 From 421a39d84ebd3d2515cfc293cdc8d5051dbab19e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 16:42:48 -0700 Subject: [PATCH 0902/2729] Update 028.Implement-strStr-KMP.cpp --- String/028.Implement-strStr/028.Implement-strStr-KMP.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp b/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp index e381ee686..2bc5ab088 100644 --- a/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp +++ b/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp @@ -11,16 +11,16 @@ class Solution { vector suf = preprocess(needle); vectordp(n,0); - dp[0] = (needle[0]==haystack[0]); + dp[0] = (haystack[0]==needle[0]); if (m==1 && dp[0]==1) return 0; for (int i=1; i0 && needle[j]!=haystack[i]) + while (j>0 && haystack[i]!=needle[j]) j = suf[j-1]; - dp[i] = j + (needle[j]==haystack[i]); + dp[i] = j + (haystack[i]!=needle[j]); if (dp[i]==needle.size()) return i-needle.size()+1; } From 2dbafb8c6a29d7d2b44e334f7c43c6a26b094e07 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 17:00:42 -0700 Subject: [PATCH 0903/2729] Update 028.Implement-strStr-KMP.cpp --- String/028.Implement-strStr/028.Implement-strStr-KMP.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp b/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp index 2bc5ab088..39ba57963 100644 --- a/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp +++ b/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp @@ -20,7 +20,7 @@ class Solution { int j = dp[i-1]; while (j>0 && haystack[i]!=needle[j]) j = suf[j-1]; - dp[i] = j + (haystack[i]!=needle[j]); + dp[i] = j + (haystack[i]==needle[j]); if (dp[i]==needle.size()) return i-needle.size()+1; } From 170bf9b859f24133a59976b5c5349b02854f354f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 17:18:44 -0700 Subject: [PATCH 0904/2729] Create 2302.Count-Subarrays-With-Score-Less-Than-K.cpp --- ...Count-Subarrays-With-Score-Less-Than-K.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Others/2302.Count-Subarrays-With-Score-Less-Than-K/2302.Count-Subarrays-With-Score-Less-Than-K.cpp diff --git a/Others/2302.Count-Subarrays-With-Score-Less-Than-K/2302.Count-Subarrays-With-Score-Less-Than-K.cpp b/Others/2302.Count-Subarrays-With-Score-Less-Than-K/2302.Count-Subarrays-With-Score-Less-Than-K.cpp new file mode 100644 index 000000000..6320f46ac --- /dev/null +++ b/Others/2302.Count-Subarrays-With-Score-Less-Than-K/2302.Count-Subarrays-With-Score-Less-Than-K.cpp @@ -0,0 +1,30 @@ +using LL = long long; +class Solution { +public: + long long countSubarrays(vector& nums, long long k) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + presum[0] = nums[0]; + for (int i=1; i<=n; i++) + presum[i] = presum[i-1]+nums[i]; + + LL ret = 0; + for (int i=1; i<=n; i++) + { + if (nums[i] >= k) continue; + LL left = 1, right = i; + while (left < right) + { + int mid = right-(right-left)/2; + if ((presum[i]-presum[i-mid])*(mid) < k) + left = mid; + else + right = mid-1; + } + ret += left; + } + return ret; + } +}; From 01cf68e39f18fa8bf92eed43cb9b7529b57bb0f4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 17:19:10 -0700 Subject: [PATCH 0905/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 11ff53c83..9ba85d0fb 100644 --- a/Readme.md +++ b/Readme.md @@ -1230,6 +1230,7 @@ [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) +[2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 033d2370efe18ef2a26623372c782d452617b20c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 17:35:50 -0700 Subject: [PATCH 0906/2729] Create Readme.md --- Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md diff --git a/Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md b/Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md new file mode 100644 index 000000000..038d2f3e9 --- /dev/null +++ b/Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md @@ -0,0 +1,5 @@ +### 2302.Count-Subarrays-With-Score-Less-Than-K + +根据```Count Subarrays by Element```的套路,我们不会用o(N^2)遍历数组。我们会尝试用o(N)遍历每个元素,考察它对应了哪些数组。 + +因为这道题里的subarray并没有任何代表其特征的最大值、最小值之类的,所以我们可以考虑将每种subarray的最后一个元素作为代表。具体的说,如果nums[i]是符合条件的subarray的最后一个元素,那么这个subarray的起点可以在哪里?显然,长度越长,起点越靠前,权重和就越大,直至可能超过k。利用单调性,我们就能用二分搜索来确定该subarray的最大长度,即对应了有多少个符合条件的subarray。 From d2417825e4363fb42a5a370fb8669f2d7fe5d653 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 17:36:11 -0700 Subject: [PATCH 0907/2729] Update Readme.md --- Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md b/Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md index 038d2f3e9..b4fe19759 100644 --- a/Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md +++ b/Others/2302.Count-Subarrays-With-Score-Less-Than-K/Readme.md @@ -1,5 +1,5 @@ ### 2302.Count-Subarrays-With-Score-Less-Than-K -根据```Count Subarrays by Element```的套路,我们不会用o(N^2)遍历数组。我们会尝试用o(N)遍历每个元素,考察它对应了哪些数组。 +根据```Count Subarrays by Element```的套路,我们不会用o(N^2)遍历数组。我们会尝试用o(N)遍历每个元素,考察它unique地对应了哪些数组。 因为这道题里的subarray并没有任何代表其特征的最大值、最小值之类的,所以我们可以考虑将每种subarray的最后一个元素作为代表。具体的说,如果nums[i]是符合条件的subarray的最后一个元素,那么这个subarray的起点可以在哪里?显然,长度越长,起点越靠前,权重和就越大,直至可能超过k。利用单调性,我们就能用二分搜索来确定该subarray的最大长度,即对应了有多少个符合条件的subarray。 From 851cfe381e433d2e248efd47448694a090c2d649 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Jun 2022 17:40:46 -0700 Subject: [PATCH 0908/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9ba85d0fb..bbc6990ef 100644 --- a/Readme.md +++ b/Readme.md @@ -1222,7 +1222,7 @@ * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) -* ``Aggregate Subarray by element`` +* ``Count Subarray by Element`` [828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) [1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1498.Number-of-Subsequences-That-Satisfy-the-Given-Sum-Condition) (H-) From 4399e23b87390b6460d16a8d9648143a6d1c98c8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 00:42:05 -0700 Subject: [PATCH 0909/2729] Create 2306.Naming-a-Company.cpp --- .../2306.Naming-a-Company.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Greedy/2306.Naming-a-Company/2306.Naming-a-Company.cpp diff --git a/Greedy/2306.Naming-a-Company/2306.Naming-a-Company.cpp b/Greedy/2306.Naming-a-Company/2306.Naming-a-Company.cpp new file mode 100644 index 000000000..181739b70 --- /dev/null +++ b/Greedy/2306.Naming-a-Company/2306.Naming-a-Company.cpp @@ -0,0 +1,25 @@ +using LL = long long; +class Solution { +public: + long long distinctNames(vector& ideas) + { + vector>head2str(26); + for (string& idea: ideas) + head2str[idea[0]-'a'].insert(idea.substr(1)); + + LL ret = 0; + for (int i=0; i<26; i++) + for (int j=i+1; j<26; j++) + { + int dup = 0; + for (string x: head2str[i]) + if (head2str[j].find(x)!=head2str[j].end()) + dup++; + LL a = head2str[i].size() - dup; + LL b = head2str[j].size() - dup; + ret += a*b*2; + } + + return ret; + } +}; From 6dd8991a08da927b9dc43588ac6079c3cba66991 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 00:42:35 -0700 Subject: [PATCH 0910/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bbc6990ef..e8e83482e 100644 --- a/Readme.md +++ b/Readme.md @@ -1095,6 +1095,7 @@ [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) +[2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 41c78b875a9536d53283b8d4587ffd1a89590413 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 01:16:32 -0700 Subject: [PATCH 0911/2729] Create Readme.md --- Greedy/2306.Naming-a-Company/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2306.Naming-a-Company/Readme.md diff --git a/Greedy/2306.Naming-a-Company/Readme.md b/Greedy/2306.Naming-a-Company/Readme.md new file mode 100644 index 000000000..2eb5a1429 --- /dev/null +++ b/Greedy/2306.Naming-a-Company/Readme.md @@ -0,0 +1,9 @@ +### 2306.Naming-a-Company + +我们令{a}表示以字母a为首字母的后缀字符串的集合。同理有{b},{c}, ... + +根据题意,我们会将任意一个名字分成两部分看待:aA。前者是首字母,后者是除首字母外的后缀字符串。我们考虑任意两个名字aA和bB是否能配对呢?根据规则,aA + bB => aB + bA。 + +为了符合条件,aB不能出现在原始字符串中。也就是说,B不能出现在{a}里。类似的,bA不能出现在元素字符串中,即A不能出现在{b}里。所以想要aA和bB配对成功,{a}集合与{b}集合里面的相同元素都不能出现。而将这些元素从两个集合中都拿走后,{a}与{b}的元素就可以任意选取,都能保证 aA + bB => aB + bA 符合规则。 + +综上,我们用二层循环,考察不同的首字母组合,假设分别是x和y,且{x}有m个元素,{y}有n个元素,两个集合的共同元素是k个。那么就有```(m-k)*(n-k)*2```种符合规则的配对。最终将26x26层循环得到的结果相加。 From 96b1600466863efdb7625e407e8676a8414a0abf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 01:51:46 -0700 Subject: [PATCH 0912/2729] Update 2301.Match-Substring-After-Replacement_KMP.cpp --- ....Match-Substring-After-Replacement_KMP.cpp | 73 +++++++++---------- 1 file changed, 35 insertions(+), 38 deletions(-) diff --git a/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp b/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp index 52c8348e7..b97918b32 100644 --- a/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp +++ b/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp @@ -1,72 +1,69 @@ class Solution { - bool table[256][256]; + // unordered_map>>Map; // 't'-> {'7','8'} + bool table[128][128]; + public: + bool match(char x, char y) + { + return (x==y || table[y][x]); + } + bool matchReplacement(string s, string sub, vector>& mappings) { - int m = s.size(); - for (auto x: mappings) - { table[x[0]][x[1]] = 1; - } - return strStr(s, sub)!=-1; + return strStr(s, sub)!= -1; } - - bool equal(char a, char b) - { - return (a==b || table[b][a]); - } - + int strStr(string haystack, string needle) { - string s = haystack; - string p = needle; - int n = s.size(); - int m = p.size(); - + int n = haystack.size(); + int m = needle.size(); if (m==0) return 0; - if (n==0) return -1; + if (n==0) return -1; + + vector suf = preprocess(needle); vectordp(n,0); - dp[0] = equal(s[0], p[0]); + dp[0] = match(haystack[0], needle[0]); if (m==1 && dp[0]==1) return 0; - - vectorsuffix = preprocess(p); - + for (int i=1; i0 && !equal(s[i], p[j])) - j = suffix[j-1]; - dp[i] = j + equal(s[i], p[j]); - - if (dp[i]==p.size()) - return i - p.size() + 1; + while (j>0 && !match(haystack[i], needle[j])) + j = suf[j-1]; + dp[i] = j + match(haystack[i], needle[j]); + if (dp[i]==needle.size()) + return i-needle.size()+1; } - return -1; - } - vector preprocess(string s) + bool equal2(char x, char y) { - int n = s.size(); - vectordp(n); - dp[0] = 0; + if (x==y) return true; + for (int i=0; i<128; i++) + if (table[x][i]==table[y][i]) + return true; + return false; + } + vector preprocess(string s) + { + int n = s.size(); + vectordp(n,0); for (int i=1; i=1 && !equal(s[j],s[i])) + while (j>=1 && !equal2(s[j],s[i])) { j = dp[j-1]; } - dp[i] = j + equal(s[j], s[i]); + dp[i] = j + equal2(s[j],s[i]); } - return dp; } }; From 8001bc69c15ed5543fb578cfc837f786f9c5b7c8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 02:15:31 -0700 Subject: [PATCH 0913/2729] Update 2301.Match-Substring-After-Replacement_KMP.cpp --- .../2301.Match-Substring-After-Replacement_KMP.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp b/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp index b97918b32..988f77bf5 100644 --- a/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp +++ b/String/2301.Match-Substring-After-Replacement/2301.Match-Substring-After-Replacement_KMP.cpp @@ -3,7 +3,7 @@ class Solution { bool table[128][128]; public: - bool match(char x, char y) + bool equal(char x, char y) { return (x==y || table[y][x]); } @@ -26,16 +26,16 @@ class Solution { vector suf = preprocess(needle); vectordp(n,0); - dp[0] = match(haystack[0], needle[0]); + dp[0] = equal(haystack[0], needle[0]); if (m==1 && dp[0]==1) return 0; for (int i=1; i0 && !match(haystack[i], needle[j])) + while (j>0 && !equal(haystack[i], needle[j])) j = suf[j-1]; - dp[i] = j + match(haystack[i], needle[j]); + dp[i] = j + equal(haystack[i], needle[j]); if (dp[i]==needle.size()) return i-needle.size()+1; } From 8ab1883e7963faf3a701c2ede86f33a35047a577 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 02:16:46 -0700 Subject: [PATCH 0914/2729] Update Readme.md --- String/2301.Match-Substring-After-Replacement/Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/String/2301.Match-Substring-After-Replacement/Readme.md b/String/2301.Match-Substring-After-Replacement/Readme.md index 50da0a046..8fb5b111f 100644 --- a/String/2301.Match-Substring-After-Replacement/Readme.md +++ b/String/2301.Match-Substring-After-Replacement/Readme.md @@ -4,4 +4,8 @@ 本题暴力查验字符串匹配,时间是o(N^2),有AC的可能。 #### 解法2:KMP -本题的本质其实就是在一个字符串中查找匹配的子串。最直观的高效解法就是KMP。我们只需要略微修改KMP算法中关于“两个字符相等”的定义。定义一个新的```equal(char a, char b)```. 当两个字符相等,或者sub的字符可以映射到s的字符中时,就返回true。这样KMP就可以直接用于此题。 +本题的本质其实就是在一个字符串中查找匹配的子串。最直观的高效解法就是KMP。我们只需要略微修改KMP算法中关于“两个字符相等”的定义。 + +在KMP的主函数中,定义一个新的```equal(char a, char b)```. 当两个字符相等,或者sub的字符可以映射到s的字符中时,就返回true。 + +在KMP的preprocessing函数中,定义一个新的```equal2(char a, char b)```. 当两个字符相等,或者这两个字符都可以映射到同一个字符时,就返回true。 From c8a49b6ef6a59b185d004ccccba2c94114b6a920 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 16:38:17 -0700 Subject: [PATCH 0915/2729] Create 2305.Fair-Distribution-of-Cookies_v1.cpp --- .../2305.Fair-Distribution-of-Cookies_v1.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v1.cpp diff --git a/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v1.cpp b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v1.cpp new file mode 100644 index 000000000..fb48bad53 --- /dev/null +++ b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v1.cpp @@ -0,0 +1,29 @@ +class Solution { + int ret = INT_MAX; + int plan[8]; +public: + int distributeCookies(vector& cookies, int k) + { + dfs(cookies, k, 0, 0); + return ret; + } + + void dfs(vector& cookies, int k, int idx, int count) + { + if (idx==cookies.size()) + { + int mx = 0; + for (int i=0; i Date: Sun, 12 Jun 2022 16:38:38 -0700 Subject: [PATCH 0916/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index e8e83482e..3d70073d8 100644 --- a/Readme.md +++ b/Readme.md @@ -432,7 +432,6 @@ [959.Regions-Cut-By-Slashes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/959.Regions-Cut-By-Slashes) (M+) [1306.Jump-Game-III](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1306.Jump-Game-III) (M) [1718.Construct-the-Lexicographically-Largest-Valid-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1718.Construct-the-Lexicographically-Largest-Valid-Sequence) (H-) -[1723.Find-Minimum-Time-to-Finish-All-Jobs](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1723.Find-Minimum-Time-to-Finish-All-Jobs) (H-) [1766.Tree-of-Coprimes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1766.Tree-of-Coprimes) (H-) [2014.Longest-Subsequence-Repeated-k-Times](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2014.Longest-Subsequence-Repeated-k-Times) (H) [2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) @@ -447,6 +446,8 @@ [1307.Verbal-Arithmetic-Puzzle](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1307.Verbal-Arithmetic-Puzzle) (H) [1593.Split-a-String-Into-the-Max-Number-of-Unique-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1593.Split-a-String-Into-the-Max-Number-of-Unique-Substrings) (M) [1681.Minimum-Incompatibility](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1681.Minimum-Incompatibility) (H) +[1723.Find-Minimum-Time-to-Finish-All-Jobs](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1723.Find-Minimum-Time-to-Finish-All-Jobs) (H-) +[2305.Fair-Distribution-of-Cookies](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2305.Fair-Distribution-of-Cookies) (H-) * ``memorization`` [329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix) (M) [638.Shopping-Offers](https://github.com/wisdompeak/LeetCode/tree/master/DFS/638.Shopping-Offers) (M+) From ca84944c2acb468cbdc19bd63c7a9292d114d9d2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 17:05:28 -0700 Subject: [PATCH 0917/2729] Create 2305.Fair-Distribution-of-Cookies_v2.cpp --- .../2305.Fair-Distribution-of-Cookies_v2.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp diff --git a/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp new file mode 100644 index 000000000..513e8c912 --- /dev/null +++ b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp @@ -0,0 +1,44 @@ +class Solution { + int plan[8]; +public: + int distributeCookies(vector& cookies, int k) + { + sort(cookies.rbegin(), cookies.rend()); + + int left = 1, right = INT_MAX; + while (left < right) + { + for (int i=0; i& cookies, int limit, int k, int idx) + { + if (idx == cookies.size()) return true; + + int flag = 0; + for (int i=0; i limit) continue; + if (plan[i]==0) + { + if (flag==1) continue; + flag = 1; + } + + plan[i] += cookies[idx]; + if (dfs(cookies, limit, k, idx+1)) + return true; + plan[i] -= cookies[idx]; + } + return false; + } +}; From f9d645211d5d263aeb1f476c097b63fc0525f361 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 17:39:01 -0700 Subject: [PATCH 0918/2729] Update 2305.Fair-Distribution-of-Cookies_v2.cpp --- .../2305.Fair-Distribution-of-Cookies_v2.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp index 513e8c912..66b32448a 100644 --- a/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp +++ b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v2.cpp @@ -20,24 +20,24 @@ class Solution { return left; } - bool dfs(vector& cookies, int limit, int k, int idx) + bool dfs(vector& cookies, int limit, int k, int curCookie) { - if (idx == cookies.size()) return true; + if (curCookie == cookies.size()) return true; int flag = 0; for (int i=0; i limit) continue; + if (plan[i]+cookies[curCookie] > limit) continue; if (plan[i]==0) { if (flag==1) continue; flag = 1; } - plan[i] += cookies[idx]; - if (dfs(cookies, limit, k, idx+1)) + plan[i] += cookies[curCookie]; + if (dfs(cookies, limit, k, curCookie+1)) return true; - plan[i] -= cookies[idx]; + plan[i] -= cookies[curCookie]; } return false; } From fea92233afb28326bb996a30084f0ec642c7618a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 17:43:35 -0700 Subject: [PATCH 0919/2729] Create 2305.Fair-Distribution-of-Cookies_v3.cpp --- .../2305.Fair-Distribution-of-Cookies_v3.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v3.cpp diff --git a/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v3.cpp b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v3.cpp new file mode 100644 index 000000000..f8740e76b --- /dev/null +++ b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v3.cpp @@ -0,0 +1,52 @@ +class Solution { + int plan[8]; +public: + int distributeCookies(vector& cookies, int k) + { + sort(cookies.rbegin(), cookies.rend()); + int n = cookies.size(); + + int left = 1, right = INT_MAX; + while (left < right) + { + for (int i=0; i& cookies, int limit, int k, int curPerson, int state) + { + if (curPerson == k) + { + return state == 0; + } + + for (int subset=state; subset>0; subset=(subset-1)&state) + { + int sum = getSum(cookies, subset); + if (sum > limit) continue; + if (dfs(cookies, limit, k, curPerson+1, state-subset)) + return true; + }; + + return false; + } + + int getSum(vector& cookies, int state) + { + int ret = 0; + for (int i=0; i>i)&1) + ret += cookies[i]; + } + return ret; + } +}; From d1c6f833c540033b34ddcbe5f96b476a7d342f5b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Jun 2022 17:47:28 -0700 Subject: [PATCH 0920/2729] Update 2305.Fair-Distribution-of-Cookies_v1.cpp --- .../2305.Fair-Distribution-of-Cookies_v1.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v1.cpp b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v1.cpp index fb48bad53..10cb2bbc1 100644 --- a/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v1.cpp +++ b/DFS/2305.Fair-Distribution-of-Cookies/2305.Fair-Distribution-of-Cookies_v1.cpp @@ -4,13 +4,13 @@ class Solution { public: int distributeCookies(vector& cookies, int k) { - dfs(cookies, k, 0, 0); + dfs(cookies, k, 0); return ret; } - void dfs(vector& cookies, int k, int idx, int count) + void dfs(vector& cookies, int k, int curCookie) { - if (idx==cookies.size()) + if (curCookie == cookies.size()) { int mx = 0; for (int i=0; i Date: Sun, 12 Jun 2022 17:59:07 -0700 Subject: [PATCH 0921/2729] Create Readme.md --- DFS/2305.Fair-Distribution-of-Cookies/Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 DFS/2305.Fair-Distribution-of-Cookies/Readme.md diff --git a/DFS/2305.Fair-Distribution-of-Cookies/Readme.md b/DFS/2305.Fair-Distribution-of-Cookies/Readme.md new file mode 100644 index 000000000..7d4fe9c47 --- /dev/null +++ b/DFS/2305.Fair-Distribution-of-Cookies/Readme.md @@ -0,0 +1,17 @@ +### 2305.Fair-Distribution-of-Cookies + +#### 解法1:常规dfs,遍历cookie +通过DFS遍历所有的分配方案。dfs的每一层处理一块cookie,分支考察分配给每个人的方案。总的时间复杂度就是o(k^N). + +#### 解法2:二分+dfs,遍历cookie +我们先二分搜索猜测一个答案t,然后用dfs来寻找是否存在一种分配方案,使得每个人能分到的饼干数量不超过t。最终二分逼近的答案就是所求的最优解。 + +dfs的原理同解法1. 此时,我们可以有很多剪枝策略: +1. 发现任何一个人的饼干总数已经大于t,就返回false +2. 将cookies从大到小排列,尽早排除那些容易溢出的分支。 +3. 如果某块饼干打算分发给某个没有得到饼干的人,那么就不需要平行地尝试分给其他没有得到饼干的人。 + +#### 解法3:二分+dfs,遍历人 +dfs的原理正好相反:每一层处理一个人,对于该人的饼干选配方案就是当前剩余饼干的子集。显然我们可以通过遍历子集的技巧,进行dfs的分支搜索。 + +同样,如果遍历子集时,发现某种分配方案会导致个人的饼干总数已经大于t,就终止这个探索。 From 837f69eebb7cd2b5d77264e4c276b80eb3bda4ac Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 14 Jun 2022 23:44:28 -0700 Subject: [PATCH 0922/2729] Update Readme.md --- String/2301.Match-Substring-After-Replacement/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/String/2301.Match-Substring-After-Replacement/Readme.md b/String/2301.Match-Substring-After-Replacement/Readme.md index 8fb5b111f..9a0b59f7b 100644 --- a/String/2301.Match-Substring-After-Replacement/Readme.md +++ b/String/2301.Match-Substring-After-Replacement/Readme.md @@ -9,3 +9,5 @@ 在KMP的主函数中,定义一个新的```equal(char a, char b)```. 当两个字符相等,或者sub的字符可以映射到s的字符中时,就返回true。 在KMP的preprocessing函数中,定义一个新的```equal2(char a, char b)```. 当两个字符相等,或者这两个字符都可以映射到同一个字符时,就返回true。 + +更新:这道题不存在正确的KMP解法,敬请注意。 From 4db46da20a5372e185943b741076bd11465feeb3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Jun 2022 15:21:07 -0700 Subject: [PATCH 0923/2729] Update 978.Longest-Turbulent-Subarray.cpp --- .../978.Longest-Turbulent-Subarray.cpp | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Others/978.Longest-Turbulent-Subarray/978.Longest-Turbulent-Subarray.cpp b/Others/978.Longest-Turbulent-Subarray/978.Longest-Turbulent-Subarray.cpp index 6887c93bc..a2c3238b9 100644 --- a/Others/978.Longest-Turbulent-Subarray/978.Longest-Turbulent-Subarray.cpp +++ b/Others/978.Longest-Turbulent-Subarray/978.Longest-Turbulent-Subarray.cpp @@ -11,23 +11,23 @@ class Solution { else if (A[i] Date: Fri, 17 Jun 2022 15:30:09 -0700 Subject: [PATCH 0924/2729] Create Readme.md --- Others/978.Longest-Turbulent-Subarray/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/978.Longest-Turbulent-Subarray/Readme.md diff --git a/Others/978.Longest-Turbulent-Subarray/Readme.md b/Others/978.Longest-Turbulent-Subarray/Readme.md new file mode 100644 index 000000000..1c2d3abec --- /dev/null +++ b/Others/978.Longest-Turbulent-Subarray/Readme.md @@ -0,0 +1,5 @@ +### 978.Longest-Turbulent-Subarray + +将原始数组的相邻两个元素做差,如果为正就标记1,如果为负就标记-1,如果相等就标记0. 那么我们就能得到一个长度为n-1的序列q。显然,我们需要找q中最长的一段subarray,并且元素是1和-1间隔的。一个等价的判断就是q中的相邻元素的乘积是-1. + +假设我们从i开始作为起点,那么subarray能变长的条件就是```q[i]*q[i+1]==-1```,这样我们就递增i,直至可以找到最后一个满足条件的位置i',那么q[i:i']就是一段最长的+/-1相间的序列。注意,q是差分元素,所以实际在nums里,subarray长度就是```i'-i+2```. From 21c5983222ffa2f7d922f23a6311a23c3039c6c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Jun 2022 23:38:05 -0700 Subject: [PATCH 0925/2729] Update 642.Design-Search-Autocomplete-System.cpp --- .../642.Design-Search-Autocomplete-System.cpp | 110 ++++++++++-------- 1 file changed, 64 insertions(+), 46 deletions(-) diff --git a/Design/642.Design-Search-Autocomplete-System/642.Design-Search-Autocomplete-System.cpp b/Design/642.Design-Search-Autocomplete-System/642.Design-Search-Autocomplete-System.cpp index 9422ade6c..3c9f542d5 100644 --- a/Design/642.Design-Search-Autocomplete-System/642.Design-Search-Autocomplete-System.cpp +++ b/Design/642.Design-Search-Autocomplete-System/642.Design-Search-Autocomplete-System.cpp @@ -1,70 +1,88 @@ -class AutocompleteSystem { - unordered_mapMap; - string data; - - struct cmp +class TrieNode +{ + public: + TrieNode* next[128]; + set>top; + TrieNode() { - bool operator()(paira, pairb) - { - if (a.second==b.second) - return a.firstb.second; - } - }; + for (int i=0; i<128; i++) + next[i] = NULL; + } +}; + +class AutocompleteSystem { + TrieNode* root; + string inputStr; + TrieNode* cur; + int flag = 1; public: - AutocompleteSystem(vector sentences, vector times) + AutocompleteSystem(vector& sentences, vector& times) { + root = new TrieNode(); + cur = root; for (int i=0; inext[k] == NULL) + node->next[k] = new TrieNode(); + node = node->next[k]; + + int f = 0; + for (auto iter = node->top.begin(); iter!=node->top.end(); iter=next(iter)) + { + if (iter->second == sentence) + f = iter->first; + } + if (f!=0) node->top.erase({f, sentence}); + node->top.insert(make_pair(f+freq, sentence)); + + add(node, sentence, i+1, freq); } vector input(char c) { + inputStr.push_back(c); + if (c=='#') { - Map[data]++; - data.clear(); + inputStr.pop_back(); + add(root, inputStr, 0, -1); + inputStr = ""; + cur = root; + flag = 1; return {}; } - - data.push_back(c); - priority_queue,vector>,cmp>pq; - - for (auto x:Map) + else if (flag==0) { - string a=x.first; - if (match(data,a)) - { - pq.push({a,Map[a]}); - if (pq.size()>3) pq.pop(); - } + return {}; } - - vectorresults; - while (!pq.empty()) + else if (cur->next[c]==NULL) { - results.push_back(pq.top().first); - pq.pop(); + flag = 0; + return {}; } - reverse(results.begin(),results.end()); - return results; - } - - bool match(string a, string b) - { - for (int i=0; inext[c]; + vectorrets; + for (auto iter = cur->top.begin(); iter!=cur->top.end(); iter=next(iter)) { - if (i>=b.size() || a[i]!=b[i]) - return false; + rets.push_back(iter->second); + if (rets.size()==3) break; } - return true; + return rets; + } + }; /** * Your AutocompleteSystem object will be instantiated and called as such: - * AutocompleteSystem obj = new AutocompleteSystem(sentences, times); - * vector param_1 = obj.input(c); + * AutocompleteSystem* obj = new AutocompleteSystem(sentences, times); + * vector param_1 = obj->input(c); */ From 8f5c9fb67691032efcf103ffb6bc7f7470975e36 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Jun 2022 23:38:38 -0700 Subject: [PATCH 0926/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3d70073d8..18a57557c 100644 --- a/Readme.md +++ b/Readme.md @@ -385,7 +385,6 @@ #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) -[642.Design-Search-Autocomplete-System](https://github.com/wisdompeak/LeetCode/tree/master/Design/642.Design-Search-Autocomplete-System) (M+) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [871.Minimum-Number-of-Refueling-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/871.Minimum-Number-of-Refueling-Stops) (H-) [1057.Campus-Bikes](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1057.Campus-Bikes) (H-) @@ -538,6 +537,7 @@ [1804.Implement-Trie-II-(Prefix-Tree)](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1804.Implement-Trie-II-(Prefix-Tree)) (M+) [211.Add-and-Search-Word](https://github.com/wisdompeak/LeetCode/tree/master/Trie/211.Add-and-Search-Word) (H-) [472.Concatenated-Words](https://github.com/wisdompeak/LeetCode/tree/master/Trie/472.Concatenated-Words) (H-) +[642.Design-Search-Autocomplete-System](https://github.com/wisdompeak/LeetCode/tree/master/Design/642.Design-Search-Autocomplete-System) (H-) [648.Replace-Words](https://github.com/wisdompeak/LeetCode/tree/master/Trie/648.Replace-Words) (H) [588.Design-In-Memory-File-System](https://github.com/wisdompeak/LeetCode/tree/master/Trie/588.Design-In-Memory-File-System) (H-) [677.Map-Sum-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Trie/677.Map-Sum-Pairs) (M) From 57e78dda4bc0bfc20faeab2bf9e695999dbff353 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 08:34:43 -0700 Subject: [PATCH 0927/2729] Create 2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp --- ...Subsequence-Less-Than-or-Equal-to-K_v1.cpp | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp diff --git a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp new file mode 100644 index 000000000..52a52d7c5 --- /dev/null +++ b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp @@ -0,0 +1,65 @@ +class Solution { +public: + int longestSubsequence(string s, int k) + { + string t; + while (k>0) + { + if (k%2==0) + t.push_back('0'); + else + t.push_back('1'); + k/=2; + } + reverse(t.begin(), t.end()); + + int m = s.size(); + int n = t.size(); + + if (m=0; i--) + { + if (s[i]=='0') continue; + if (check(s,i,t, 0)) + { + ret = max(ret, countZeros(s, i) + n); + break; + } + } + + return ret ; + } + + int countZeros(string&s, int k) + { + int count = 0; + for (int i=0; i= (int)t.size() - j; + } + else + { + while (i Date: Sun, 19 Jun 2022 08:35:09 -0700 Subject: [PATCH 0928/2729] Create 2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v2.cpp --- ...Subsequence-Less-Than-or-Equal-to-K_v2.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v2.cpp diff --git a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v2.cpp b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v2.cpp new file mode 100644 index 000000000..ee2d8b60e --- /dev/null +++ b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v2.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int longestSubsequence(string s, int k) + { + string t; + while (k>0) + { + if (k%2==0) + t.push_back('0'); + else + t.push_back('1'); + k/=2; + } + reverse(t.begin(), t.end()); + + int m = s.size(); + int n = t.size(); + + if (m Date: Sun, 19 Jun 2022 09:32:55 -0700 Subject: [PATCH 0929/2729] Update 2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp --- ...311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp index 52a52d7c5..959b1aea0 100644 --- a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp +++ b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp @@ -23,7 +23,6 @@ class Solution { for (int i=m-1; i>=0; i--) { - if (s[i]=='0') continue; if (check(s,i,t, 0)) { ret = max(ret, countZeros(s, i) + n); From 99fca9d05ecaa0a7ba0e6cad97c3b5e5c46d884c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 09:49:14 -0700 Subject: [PATCH 0930/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/Readme.md diff --git a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/Readme.md b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/Readme.md new file mode 100644 index 000000000..7ff900893 --- /dev/null +++ b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/Readme.md @@ -0,0 +1,21 @@ +### 2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K + +#### 解法1: +我们将k同样也转化为二进制的字符串,标记为t。我们令s的长度是m,t的长度为n。注意,因为k是个整形,n的长度不会超过32. + +接下来考虑题目中说的“最长”是什么意思。通常情况下,长度小于n的二进制数一定小于k,长度大于n的二进制数一定会大于k,“最长”不就是n吗?本题的关键点在于leading zeros。所以,我们希望尽可能地在期望的subsequence前面堆积0,这就意味着我们希望将subsequence放在s里尽量靠后的位置。 + +所以我们本题的做法就是:在s里从后往前依次寻找一个起点位置i,判断是否存在一个从i开始的subsequence,使其小于等于t,有的话就再加上s[0:i-1]里的所有0的个数,就是期望的总长度。最后,我们在所有的i的选择里面挑一个答案最长的。 + +那么指定了起点i,如何判断是否存在一个subsequence小于等于t呢?用递归的方法贪心地扫描即可。如果t[j]是0,那么s[i]必须是0,于是移动i直至找到0,与之match,双指针再自增1。如果t[j]是1,那么如果s[i]是0,直接OK;如果s[j]是1,那么与之match,双指针都自增1. + +这种方法的时间复杂度是o(32n) + +#### 解法2: +在解法1的基础上,事实上我们不需要遍历所有起点位置,只需要考察一个位置i=m-n,也就是只需要考察最后一个长度为n的substring即可。这是为什么呢? + +先考虑basic plan:只看最后n-1长度的substring(必然小于t),再加上[0:m-n]之间的所有的0. 这显然是一个合法的解。 + +再考虑如果以i=m-n为起点、长度为n的substring,如果大于t的话(显然s的第i位必然是1),那么说明什么?说明缺0。我们必须将i往前移,目的是为了能够引入0,这样才可能将之后的subsequence的大小降下来。但是一旦真的能引入一个0进入subsequence,那么代价就是损失了一个leading zero。那么收益呢?收益就是将subsequence的匹配度从n-1提升到n而已,并没有优势。 + +所以本题非常简单,在考察完basic plan之后,只需要查看取最后长度n的substring是否为另一个plan即可。 From 655136c857ceda40936ec0efaa46a78263f1beb9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 09:50:26 -0700 Subject: [PATCH 0931/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 18a57557c..507f61ec9 100644 --- a/Readme.md +++ b/Readme.md @@ -1097,6 +1097,7 @@ [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) [2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) +[2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K) (H-) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 36cd4a4f7f10f9073821d998dfca188c6466cd54 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 14:54:18 -0700 Subject: [PATCH 0932/2729] Create 2312.Selling-Pieces-of-Wood.cpp --- .../2312.Selling-Pieces-of-Wood.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Dynamic_Programming/2312.Selling-Pieces-of-Wood/2312.Selling-Pieces-of-Wood.cpp diff --git a/Dynamic_Programming/2312.Selling-Pieces-of-Wood/2312.Selling-Pieces-of-Wood.cpp b/Dynamic_Programming/2312.Selling-Pieces-of-Wood/2312.Selling-Pieces-of-Wood.cpp new file mode 100644 index 000000000..b7630b5e0 --- /dev/null +++ b/Dynamic_Programming/2312.Selling-Pieces-of-Wood/2312.Selling-Pieces-of-Wood.cpp @@ -0,0 +1,22 @@ +using LL = long long; +class Solution { + LL dp[201][201]; +public: + long long sellingWood(int m, int n, vector>& prices) + { + for (auto x: prices) + dp[x[0]][x[1]] = x[2]; + + for (int i=1; i<=m; i++) + for (int j=1; j<=n; j++) + { + for (int k=1; k Date: Sun, 19 Jun 2022 14:55:04 -0700 Subject: [PATCH 0933/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 507f61ec9..544aa1f74 100644 --- a/Readme.md +++ b/Readme.md @@ -615,6 +615,7 @@ [2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H) [2189.Number-of-Ways-to-Build-House-of-Cards](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards) (H-) [2218.Maximum-Value-of-K-Coins-From-Piles](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles) (H-) +[2312.Selling-Pieces-of-Wood](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2312.Selling-Pieces-of-Wood) (M+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 0cb69579f3fc43d23b2e3ec63ef3f168e5a6535e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 15:02:29 -0700 Subject: [PATCH 0934/2729] Create Readme.md --- Dynamic_Programming/2312.Selling-Pieces-of-Wood/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2312.Selling-Pieces-of-Wood/Readme.md diff --git a/Dynamic_Programming/2312.Selling-Pieces-of-Wood/Readme.md b/Dynamic_Programming/2312.Selling-Pieces-of-Wood/Readme.md new file mode 100644 index 000000000..33933c3e9 --- /dev/null +++ b/Dynamic_Programming/2312.Selling-Pieces-of-Wood/Readme.md @@ -0,0 +1,7 @@ +### 2312.Selling-Pieces-of-Wood + +令dp[i][j]表示高度为i、宽度为j的矩形所能得到的最大收益。因为任何一刀必须贯穿整块木板,并且两块木板可以继续各自独立地做进一步操作。显然这就是状态的转移。 + +假设这一刀是竖切,那么假设左半部分的宽度是k,那么就分成了大小为[i,k]和[i,j-k]的两部分。类似的,如果这一刀是横切,假设上半部分的高度是k,那么就分成了大小为[k,j]和[i-k,j]的两部分。所以我们只要从小到大遍历高和宽,就可以求出所有的dp[i][j]. + +边界条件是某些特定的高和宽恰好对应了prices里面的形状,那么他们的dp值除了可以通过上述分割的转移方程进行推导,也可以从prices里面得到。两者取大即可。 From 54e342b567dbe382e8bf8d3e51d478954533f4fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 15:17:31 -0700 Subject: [PATCH 0935/2729] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/Readme.md b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/Readme.md index 7ff900893..53e7ea86d 100644 --- a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/Readme.md +++ b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/Readme.md @@ -9,7 +9,7 @@ 那么指定了起点i,如何判断是否存在一个subsequence小于等于t呢?用递归的方法贪心地扫描即可。如果t[j]是0,那么s[i]必须是0,于是移动i直至找到0,与之match,双指针再自增1。如果t[j]是1,那么如果s[i]是0,直接OK;如果s[j]是1,那么与之match,双指针都自增1. -这种方法的时间复杂度是o(32n) +这种方法的时间复杂度是o(N^2) #### 解法2: 在解法1的基础上,事实上我们不需要遍历所有起点位置,只需要考察一个位置i=m-n,也就是只需要考察最后一个长度为n的substring即可。这是为什么呢? @@ -18,4 +18,4 @@ 再考虑如果以i=m-n为起点、长度为n的substring,如果大于t的话(显然s的第i位必然是1),那么说明什么?说明缺0。我们必须将i往前移,目的是为了能够引入0,这样才可能将之后的subsequence的大小降下来。但是一旦真的能引入一个0进入subsequence,那么代价就是损失了一个leading zero。那么收益呢?收益就是将subsequence的匹配度从n-1提升到n而已,并没有优势。 -所以本题非常简单,在考察完basic plan之后,只需要查看取最后长度n的substring是否为另一个plan即可。 +所以本题非常简单,在考察完basic plan之后,只需要查看取最后长度n的substring是否为另一个plan即可。时间复杂度是o(N). From 94b682662591a9d603a83e9a2775752a4f1ae030 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 15:51:40 -0700 Subject: [PATCH 0936/2729] Create 2222.Number-of-Ways-to-Select-Buildings.cpp --- ...222.Number-of-Ways-to-Select-Buildings.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/2222.Number-of-Ways-to-Select-Buildings.cpp diff --git a/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/2222.Number-of-Ways-to-Select-Buildings.cpp b/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/2222.Number-of-Ways-to-Select-Buildings.cpp new file mode 100644 index 000000000..e5530eee9 --- /dev/null +++ b/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/2222.Number-of-Ways-to-Select-Buildings.cpp @@ -0,0 +1,27 @@ +using LL = long long; +class Solution { + LL dp[100005][4][2]; +public: + long long numberOfWays(string s) + { + int n = s.size(); + s = "#"+s; + + dp[0][0][0] = 1; + dp[0][0][1] = 1; + + LL ret = 0; + + for (int i=1; i<=n; i++) + for (int j=0; j<=3; j++) + for (int k=0; k<2; k++) + { + dp[i][j][k] = dp[i-1][j][k]; + + if (j>=1 && k==(s[i]-'0')) + dp[i][j][k] += dp[i-1][j-1][1-k]; + } + + return dp[n][3][0] + dp[n][3][1]; + } +}; From fbf5e9a256050c6bb004ef8e49123523caa6547b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 15:52:05 -0700 Subject: [PATCH 0937/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 544aa1f74..8cc5e9830 100644 --- a/Readme.md +++ b/Readme.md @@ -615,6 +615,7 @@ [2140.Solving-Questions-With-Brainpower](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2140.Solving-Questions-With-Brainpower) (H) [2189.Number-of-Ways-to-Build-House-of-Cards](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2189.Number-of-Ways-to-Build-House-of-Cards) (H-) [2218.Maximum-Value-of-K-Coins-From-Piles](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles) (H-) +[2222.Number-of-Ways-to-Select-Buildings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings) (M+) [2312.Selling-Pieces-of-Wood](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2312.Selling-Pieces-of-Wood) (M+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) From 99304f3a08a2e9dde3f10fe0b7e21370ec464049 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 15:59:56 -0700 Subject: [PATCH 0938/2729] Create Readme.md --- .../2222.Number-of-Ways-to-Select-Buildings/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/Readme.md diff --git a/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/Readme.md b/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/Readme.md new file mode 100644 index 000000000..235aa6dec --- /dev/null +++ b/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/Readme.md @@ -0,0 +1,9 @@ +### 2222.Number-of-Ways-to-Select-Buildings + +我们在考虑第i个建筑是否被选中时,需要考虑的因素有:我们已经选中了多少?上一个选中的和当前这个是否是同一个类型? + +想清楚这些,我们就可以设计状态:dp[i][j][k]表示考虑完第i幢建筑时,如果已经选中了j个,并且最近一个被选中的建筑类别是k时,总共有多少种方案。 + +状态转移时需要分两种情况:如果我们不选第i个建筑,那么自然dp[i][j][k] = dp[i-1][j][k]。如果我们选中第i个建筑,那么需要保证第i个建筑与类别k是匹配的,于是这就取决于之前解决过的一个问题:在前i-1个建筑里,选择j-1个,并且最近一个选中的建筑类别是1-k,这样的方案有多少。依据dp[i-1][j][1-k],再选中第i个建筑,就是dp[i][j][k]。 + +最终答案是dp[n][3][0]+dp[n][3][1]. From 7d629b371c7f354a54f76414474398d47a65b883 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 16:04:49 -0700 Subject: [PATCH 0939/2729] Update 2222.Number-of-Ways-to-Select-Buildings.cpp --- .../2222.Number-of-Ways-to-Select-Buildings.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/2222.Number-of-Ways-to-Select-Buildings.cpp b/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/2222.Number-of-Ways-to-Select-Buildings.cpp index e5530eee9..6a4ec2b21 100644 --- a/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/2222.Number-of-Ways-to-Select-Buildings.cpp +++ b/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings/2222.Number-of-Ways-to-Select-Buildings.cpp @@ -9,9 +9,7 @@ class Solution { dp[0][0][0] = 1; dp[0][0][1] = 1; - - LL ret = 0; - + for (int i=1; i<=n; i++) for (int j=0; j<=3; j++) for (int k=0; k<2; k++) From f3ef226f39dc3052c6f72ccf61552205be5efdc4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Jun 2022 16:50:18 -0700 Subject: [PATCH 0940/2729] Update Readme.md --- .../Readme.md | 30 ++++--------------- 1 file changed, 5 insertions(+), 25 deletions(-) diff --git a/Design/642.Design-Search-Autocomplete-System/Readme.md b/Design/642.Design-Search-Autocomplete-System/Readme.md index acbc38e71..7d02029e9 100644 --- a/Design/642.Design-Search-Autocomplete-System/Readme.md +++ b/Design/642.Design-Search-Autocomplete-System/Readme.md @@ -1,30 +1,10 @@ ### 642.Design-Search-Autocomplete-System -如果不用trie来做的话,可以比较简单地用priority_queue来实现对所有候选语句的排序,选择最终未被弹出的三个字符串。 +我们将所有的句子都构建入一棵字典树。对于每个节点(字母),我们都维护一个```句子-频次```的统计。也就是说,注入句子S时,我们将沿途经过的节点都标记上```freq[S]+=1```. -核心代码非常简单: -``` - struct cmp - { - bool operator()(paira, pairb) - { - if (a.second==b.second) - return a.firstb.second; - } - }; - priority_queue,vector>,cmp>pq; - for (auto x:Map) - { - string a=x.first; - if (match(data,a)) - { - pq.push({a,Map[a]}); - if (pq.size()>3) pq.pop(); - } - } -``` +当依次读入input时,我们维护从root往下走的指针,移动至该单词对应的节点,读取它的freq取出前三名即可。freq需要使用一个自动排序的数据结构。 +记得当input遇到#时,要将之前input的完整句子,从root开始再次构建入这棵字典树。 -[Leetcode Link](https://leetcode.com/problems/design-search-autocomplete-system) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/design-search-autocomplete-system) From 4eb13b0feb3507db2a5f530e70262aba16c8a3ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Jun 2022 12:27:48 -0700 Subject: [PATCH 0941/2729] Create 2282.Number-of-People-That-Can-Be-Seen-in-a-Grid.cpp --- ...r-of-People-That-Can-Be-Seen-in-a-Grid.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid.cpp diff --git a/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid.cpp b/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid.cpp new file mode 100644 index 000000000..6d38951d8 --- /dev/null +++ b/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + vector> seePeople(vector>& heights) + { + int m = heights.size(), n = heights[0].size(); + vector>rets(m, vector(n,0)); + + for (int i=0; istk; + for (int j=0; j= heights[i][stk.top()]) + { + rets[i][stk.top()]++; + lastRemove = heights[i][stk.top()]; + stk.pop(); + } + if (!stk.empty() && lastRemove != heights[i][j]) + { + rets[i][stk.top()]++; + } + stk.push(j); + } + + } + + for (int j=0; jstk; + for (int i=0; i= heights[stk.top()][j]) + { + rets[stk.top()][j]++; + lastRemove = heights[stk.top()][j]; + stk.pop(); + } + if (!stk.empty() && lastRemove != heights[i][j]) + { + rets[stk.top()][j]++; + } + stk.push(i); + } + } + + return rets; + + } +}; From 6b0c7c45c4c67f39acabf96aea6e06861b7bc2af Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Jun 2022 12:29:39 -0700 Subject: [PATCH 0942/2729] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8cc5e9830..b344e0e9f 100644 --- a/Readme.md +++ b/Readme.md @@ -328,7 +328,7 @@ [1586.Binary-Search-Tree-Iterator-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1586.Binary-Search-Tree-Iterator-II) (H) [2197.Replace-Non-Coprime-Numbers-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2197.Replace-Non-Coprime-Numbers-in-Array) (H-) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) -* ``monotonic stack`` +* ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) @@ -351,6 +351,8 @@ [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) +* ``monotonic stack: other usages`` +[2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) From c847d6b5e71e77baf5e7db8fa1209e542d945eca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Jun 2022 12:32:35 -0700 Subject: [PATCH 0943/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b344e0e9f..76675ce95 100644 --- a/Readme.md +++ b/Readme.md @@ -348,10 +348,10 @@ [1063.Number-of-Valid-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1063.Number-of-Valid-Subarrays) (M+) [1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) -[1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) * ``monotonic stack: other usages`` +[1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) * ``form smallest sequence`` From 384092173f657902ac77b61f3e45e1f37c46e427 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Jun 2022 12:33:33 -0700 Subject: [PATCH 0944/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 76675ce95..ef22ace3b 100644 --- a/Readme.md +++ b/Readme.md @@ -343,14 +343,14 @@ [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) [1856.Maximum-Subarray-Min-Product](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1856.Maximum-Subarray-Min-Product) (M+) [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) -[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1019.Next-Greater-Node-In-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1019.Next-Greater-Node-In-Linked-List) (M) [1063.Number-of-Valid-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1063.Number-of-Valid-Subarrays) (M+) [1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) -[1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) * ``monotonic stack: other usages`` +[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) +[1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) From 85c02dde4f45c2b86f8a2cd0ca26e224e17f70cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Jun 2022 15:41:38 -0700 Subject: [PATCH 0945/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md diff --git a/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md b/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md new file mode 100644 index 000000000..7b9964bac --- /dev/null +++ b/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md @@ -0,0 +1,7 @@ +### 2282.Number-of-People-That-Can-Be-Seen-in-a-Grid + +此题是1944的升级版,区别在于本题允许存在相同的元素。 + +基本思路是一致的。我们从左往右维护一个严格单调递减的栈。如果有新元素nums[i]大于等于栈顶元素,意味着这个栈顶元素今后的视线都会被nums[i]遮住再也看不到其他。所以将栈顶元素的计数器加1之后,就可以将这个栈顶元素移除了。 + +当该退栈的元素都拿走之后,此时的栈顶元素(如果存在)必然大于nums[i],理论上需要将这个栈顶元素的计时器也加1. 但是这里有一个特例,比如```3,1,1```。第二个1会把第一个1弹出再入栈,但是注意3虽然大于第二个1,可它是看不到第二个1的。因此,如果新元素nums[i]如果从栈顶刚弹出了与自己相同的元素,那么它就不能再被此时栈顶的大元素的计数器所加1(虽然大于nums[i]). From 19ce837871b35c41efa9c0188c32a0af2132933e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 17:00:10 -0700 Subject: [PATCH 0946/2729] Create 2322.Minimum-Score-After-Removals-on-a-Tree.cpp --- ...Minimum-Score-After-Removals-on-a-Tree.cpp | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Tree/2322.Minimum-Score-After-Removals-on-a-Tree/2322.Minimum-Score-After-Removals-on-a-Tree.cpp diff --git a/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/2322.Minimum-Score-After-Removals-on-a-Tree.cpp b/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/2322.Minimum-Score-After-Removals-on-a-Tree.cpp new file mode 100644 index 000000000..4126a6f0a --- /dev/null +++ b/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/2322.Minimum-Score-After-Removals-on-a-Tree.cpp @@ -0,0 +1,86 @@ +class Solution { + unordered_set next[1000]; + vectornums; + vectorvisited; + int n; +public: + int minimumScore(vector& nums, vector>& edges) + { + this->nums = nums; + this->n = nums.size(); + visited.resize(n); + for (auto edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].insert(b); + next[b].insert(a); + } + + int ret = INT_MAX; + for (int i=0; i Date: Sun, 26 Jun 2022 17:00:42 -0700 Subject: [PATCH 0947/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ef22ace3b..320cea927 100644 --- a/Readme.md +++ b/Readme.md @@ -231,6 +231,7 @@ [1666.Change-the-Root-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1666.Change-the-Root-of-a-Binary-Tree) (H-) [1932.Merge-BSTs-to-Create-Single-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1932.Merge-BSTs-to-Create-Single-BST) (H) [2003.Smallest-Missing-Genetic-Value-in-Each-Subtree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2003.Smallest-Missing-Genetic-Value-in-Each-Subtree) (H) +[2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) From 092df5a160c40f67bc00fa2032cd9361e5fce323 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 17:14:17 -0700 Subject: [PATCH 0948/2729] Update 2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp --- ...1.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp index 959b1aea0..23777ab2d 100644 --- a/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp +++ b/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K_v1.cpp @@ -18,8 +18,7 @@ class Solution { if (m=0; i--) { From 07fb2b5a190d453bbcb1c57c73c575f9931da716 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 17:21:29 -0700 Subject: [PATCH 0949/2729] Update Readme.md --- Math/1017.Convert-to-Base--2/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Math/1017.Convert-to-Base--2/Readme.md b/Math/1017.Convert-to-Base--2/Readme.md index 3ebdc9708..c9bd4ac28 100644 --- a/Math/1017.Convert-to-Base--2/Readme.md +++ b/Math/1017.Convert-to-Base--2/Readme.md @@ -2,11 +2,11 @@ 本质上和求N的任何K进制的转化一样的做法。求得余数```r=N%K```作为当前最低位的数字,然后将```N=(N-r)/K```作为下一个循环的初始值直至为零。把所有的数字拼接起来倒序输出就是K进制的结果。 -特别注意,余数r必须是正数,也就是说无法除尽的时候,采用的是向下取整。比如说5/(-3),依据严格的数学定义,商是-2,余数是1. +特别注意,余数r必须是正数,也就是说无法除尽的时候,采用的是向下取整。比如说(-5)/(-3),依据严格的数学定义,商是2,余数是1. -但是,当除数是负数的时候,不同语言的运算规则会不一样。在C++/Java里面,整数的除法都是向零取整。比如说5/(-3),结果商是-1,余数是-2.这个余数因为是负数,是无法用来作为进制转换结果的。解决方案是:将商加上一,余数加上abs(K)。这样就转变成了向下取整的结果,余数也变成了正数。在这个例子中,结果商就是-1,余数是1. +但是,当除数是负数的时候,不同语言的运算规则会不一样。在C++/Java里面,整数的除法都是向零取整。比如说(-5)/(-3),结果商是1,余数是-2.这个余数因为是负数,是无法用来作为进制转换结果的。解决方案是:将商加上一,余数加上abs(K)。这样就转变成了向下取整的结果,余数也变成了正数。在这个例子中,结果商就是2,余数是1. 事实上,在wiki里面已经明确写明了negative base calculation的方法:https://en.wikipedia.org/wiki/Negative_base#Calculation -[Leetcode Link](https://leetcode.com/problems/convert-to-base--2) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/convert-to-base--2) From e74d781697e1f8f581cbd8f107b46f939f2ab118 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 17:25:29 -0700 Subject: [PATCH 0950/2729] Update 327.Count-of-Range-Sum.cpp --- .../{ 327.Count-of-Range-Sum.cpp => 327.Count-of-Range-Sum.cpp} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename Divide_Conquer/327.Count-of-Range-Sum/{ 327.Count-of-Range-Sum.cpp => 327.Count-of-Range-Sum.cpp} (98%) diff --git a/Divide_Conquer/327.Count-of-Range-Sum/ 327.Count-of-Range-Sum.cpp b/Divide_Conquer/327.Count-of-Range-Sum/327.Count-of-Range-Sum.cpp similarity index 98% rename from Divide_Conquer/327.Count-of-Range-Sum/ 327.Count-of-Range-Sum.cpp rename to Divide_Conquer/327.Count-of-Range-Sum/327.Count-of-Range-Sum.cpp index 8a1e644c7..ec58a3f80 100644 --- a/Divide_Conquer/327.Count-of-Range-Sum/ 327.Count-of-Range-Sum.cpp +++ b/Divide_Conquer/327.Count-of-Range-Sum/327.Count-of-Range-Sum.cpp @@ -1,6 +1,6 @@ class Solution { int result; - long temp[10001]; + long temp[100001]; public: int countRangeSum(vector& nums, int lower, int upper) { From de74fd84cd7377afa57f5d7deb6f36896b16b72f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 17:31:01 -0700 Subject: [PATCH 0951/2729] Update 327.Count-of-Range-Sum.cpp --- .../327.Count-of-Range-Sum.cpp | 62 ++++++++++--------- 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/Divide_Conquer/327.Count-of-Range-Sum/327.Count-of-Range-Sum.cpp b/Divide_Conquer/327.Count-of-Range-Sum/327.Count-of-Range-Sum.cpp index ec58a3f80..ecc8aed0e 100644 --- a/Divide_Conquer/327.Count-of-Range-Sum/327.Count-of-Range-Sum.cpp +++ b/Divide_Conquer/327.Count-of-Range-Sum/327.Count-of-Range-Sum.cpp @@ -1,6 +1,6 @@ class Solution { int result; - long temp[100001]; + long temp[100005]; public: int countRangeSum(vector& nums, int lower, int upper) { @@ -26,34 +26,36 @@ class Solution { result+=p2-p1; } - int i=a, j=mid+1, p = 0; - while (i<=mid && j<=b) - { - if (nums[i]<=nums[j]) - { - temp[p] = nums[i]; - i++; - } - else - { - temp[p] = nums[j]; - j++; - } - p++; - } - while (i<=mid) - { - temp[p] = nums[i]; - i++; - p++; - } - while (j<=b) - { - temp[p] = nums[j]; - j++; - p++; - } - for (int i=0; i Date: Sun, 26 Jun 2022 17:32:25 -0700 Subject: [PATCH 0952/2729] Update Readme.md --- Divide_Conquer/327.Count-of-Range-Sum/Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Divide_Conquer/327.Count-of-Range-Sum/Readme.md b/Divide_Conquer/327.Count-of-Range-Sum/Readme.md index dd9290eab..6d44c3304 100644 --- a/Divide_Conquer/327.Count-of-Range-Sum/Readme.md +++ b/Divide_Conquer/327.Count-of-Range-Sum/Readme.md @@ -10,5 +10,6 @@ 本题的另一个训练点就是对C++的STL里lower_bound的考察。如何写自定义比较函数是关键。我们需要在右序列中找到下限的位置,希望找到的位置在原序列中是大于等于sums[i]+lower的,所以自定义函数里要写a Date: Sun, 26 Jun 2022 17:32:43 -0700 Subject: [PATCH 0953/2729] Update Readme.md --- Divide_Conquer/493.Reverse-Pairs/Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Divide_Conquer/493.Reverse-Pairs/Readme.md b/Divide_Conquer/493.Reverse-Pairs/Readme.md index 0b14903a8..894733ccd 100644 --- a/Divide_Conquer/493.Reverse-Pairs/Readme.md +++ b/Divide_Conquer/493.Reverse-Pairs/Readme.md @@ -6,5 +6,6 @@ 另外,两个有序数组的归并排序操作,代码要熟练掌握。 +补充:inplace_merge(iter1, iter2, iter3)可以实现[iter1,iter2)和[iter2,iter3)两段区间的归并排序(前提是两段各自有序)。 -[Leetcode Link](https://leetcode.com/problems/reverse-pairs) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/reverse-pairs) From 96355ed9fc49d742c56ec29d4604b596b1d5ec7f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 17:32:59 -0700 Subject: [PATCH 0954/2729] Update Readme.md --- .../315.Count-of-Smaller-Numbers-After-Self/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/Readme.md b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/Readme.md index dfc0c5e18..531d9d4d6 100644 --- a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/Readme.md +++ b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/Readme.md @@ -10,5 +10,7 @@ 最后注意,本题需要三个数组,nums, sortedNums, count。原来的数据存在nums, 归并排序后的数组存在sortedNums, count[i]对应的是nums[i]的 number of smaller elements to the right. +补充:inplace_merge(iter1, iter2, iter3)可以实现[iter1,iter2)和[iter2,iter3)两段区间的归并排序(前提是两段各自有序)。 -[Leetcode Link](https://leetcode.com/problems/count-of-smaller-numbers-after-self) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/count-of-smaller-numbers-after-self) From fe1779dad26a694c4a3b5e22f9ed4bcf2593e5d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 17:37:36 -0700 Subject: [PATCH 0955/2729] Update 315.Count-of-Smaller-Numbers-After-Self.cpp --- .../315.Count-of-Smaller-Numbers-After-Self.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp index bbeebc6a3..38457ffee 100644 --- a/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp +++ b/Divide_Conquer/315.Count-of-Smaller-Numbers-After-Self/315.Count-of-Smaller-Numbers-After-Self.cpp @@ -30,7 +30,6 @@ class Solution { } // 将两段已经有序的数组段start~mid,mid+1~end合起来排序。 - // 如果写归并排序的code会更快一些。这里就偷懒了,直接用sort函数。 - sort(sortedNums.begin()+start,sortedNums.begin()+end+1); + inplace_merge(sortedNums.begin()+start, sortedNums.begin()+mid+1, sortedNums.begin()+end+1); } }; From a5504eeb6d4c1e5146e9687e0db4920f5a215c5d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 17:39:50 -0700 Subject: [PATCH 0956/2729] Update 1649.Create-Sorted-Array-through-Instructions_DivideConque.cpp --- ...rray-through-Instructions_DivideConque.cpp | 63 +++++++++---------- 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions/1649.Create-Sorted-Array-through-Instructions_DivideConque.cpp b/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions/1649.Create-Sorted-Array-through-Instructions_DivideConque.cpp index 09ed2ea13..aa5bed503 100644 --- a/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions/1649.Create-Sorted-Array-through-Instructions_DivideConque.cpp +++ b/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions/1649.Create-Sorted-Array-through-Instructions_DivideConque.cpp @@ -35,37 +35,36 @@ class Solution { numSmaller[i] += iter-(sorted+a); } - int i=a, j=mid+1, p = 0; - while (i<=mid && j<=b) - { - if (sorted[i]<=sorted[j]) - { - temp[p] = sorted[i]; - i++; - } - else - { - temp[p] = sorted[j]; - j++; - } - p++; - } - while (i<=mid) - { - temp[p] = sorted[i]; - i++; - p++; - } - while (j<=b) - { - temp[p] = sorted[j]; - j++; - p++; - } - for (int i=0; i Date: Sun, 26 Jun 2022 17:46:39 -0700 Subject: [PATCH 0957/2729] Update 2141.Maximum-Running-Time-of-N-Computers.cpp --- ...41.Maximum-Running-Time-of-N-Computers.cpp | 31 +++++++------------ 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/2141.Maximum-Running-Time-of-N-Computers.cpp b/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/2141.Maximum-Running-Time-of-N-Computers.cpp index 698336057..013c58260 100644 --- a/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/2141.Maximum-Running-Time-of-N-Computers.cpp +++ b/Binary_Search/2141.Maximum-Running-Time-of-N-Computers/2141.Maximum-Running-Time-of-N-Computers.cpp @@ -1,37 +1,30 @@ using LL = long long; -class Solution { +class Solution { public: long long maxRunTime(int n, vector& batteries) { - LL left = 0, right = LLONG_MAX/2; - // sort(batteries.rbegin(), batteries.rend()); - + LL left = 0, right = LLONG_MAX/n; while (left < right) { LL mid = right-(right-left)/2; - if (checkOK(mid, batteries, n)) - left = mid; + if (checkOK(mid, n, batteries)) + left = mid; else - right = mid-1; + right = mid-1; } - return left; + return left; } - bool checkOK(LL T, vector&nums, int n) + bool checkOK(LL T, LL n, vector& batteries) { - int count = 0; - LL cur = 0; - for (int i=0; i= T) - { - count++; - cur-=T; - } - if (count >= n) + sum += min((LL)x, T); + if (sum >= T*n) return true; } return false; } }; + From 814052e47ebb59c2462f6527e2ced7baed6fcd65 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 18:00:28 -0700 Subject: [PATCH 0958/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Tree/2322.Minimum-Score-After-Removals-on-a-Tree/Readme.md diff --git a/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/Readme.md b/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/Readme.md new file mode 100644 index 000000000..8537558b9 --- /dev/null +++ b/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/Readme.md @@ -0,0 +1,11 @@ +### 2322.Minimum-Score-After-Removals-on-a-Tree + +题目中说要删除两条边,同时考虑的话太复杂吃不消。我们不妨先枚举其中一条边(a-b),将其砍断的话整张图就变成了两棵树,分别以a和b作为根。此时我们还需要再砍一条边,但这条边只能存在于其中一棵树里面。不妨假设是砍在了a树。那么对于b树,我们就无脑取其所有节点的XOR(记做B)即可。 + +接下来看a树,需要将其砍一刀变成两个部分。此时我们发现,任意一刀,都会将a树里砍下一棵子树(假设称为c)来。那么我们需要计算的是c子树的节点XOR(记做C),和a子树剩下部分的XOR。突破口来了,剩下部分的XOR,其实就是a子树整体的XOR(记做A),与C做XOR即可。最终这两刀砍成的三个部分,就分别是B,C,和A^C。 + +此时我们看到,只要在a树里面DFS遍历节点,那么很容易用递归的方法,用o(n)的时间计算每个节点其下方所有孩子的XOR,也就是将其作为c子树的根时所对应的C值。如果我们提前计算了A和B,那么A^C也就马上有了。于是在DFS整棵a树的节点过程中,我们等同于遍历了第二刀的位置,同时立马得到了第二刀砍出的三个部分。 + +所以本题的思想是,暴力枚举第一刀,然后遍历其中的一颗子树枚举第二刀的位置。总的时间复杂度是o(N^2). + +当然,本题还有复杂度优化的空间,比如说用移根的方法来枚举第一刀,简化第二刀的遍历。这里不深究。 From df6a1dea2d99e3e82220f70bfb91612d0c7f457a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 22:07:35 -0700 Subject: [PATCH 0959/2729] Create 2321.Maximum-Score-Of-Spliced-Array.cpp --- .../2321.Maximum-Score-Of-Spliced-Array.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array/2321.Maximum-Score-Of-Spliced-Array.cpp diff --git a/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array/2321.Maximum-Score-Of-Spliced-Array.cpp b/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array/2321.Maximum-Score-Of-Spliced-Array.cpp new file mode 100644 index 000000000..93b84fac1 --- /dev/null +++ b/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array/2321.Maximum-Score-Of-Spliced-Array.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int maximumsSplicedArray(vector& nums1, vector& nums2) + { + return max(solve(nums1,nums2), solve(nums2,nums1)); + } + int solve(vector& nums1, vector& nums2) + { + int n = nums1.size(); + vectornums(n); + for (int i=0; i Date: Sun, 26 Jun 2022 22:07:54 -0700 Subject: [PATCH 0960/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 320cea927..8a74fbc3e 100644 --- a/Readme.md +++ b/Readme.md @@ -777,10 +777,11 @@ [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) * ``Infer future from current`` [2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) -* ``max subarray`` +* ``maximum subarray`` [053.Maximum-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/053.Maximum-Subarray) (E+) [152.Maximum-Product-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/152.Maximum-Product-Subarray) (M+) [2272.Substring-With-Largest-Variance](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2272.Substring-With-Largest-Variance) (H-) +[2321.Maximum-Score-Of-Spliced-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array) (H-) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From 289068fdcae1c3fd3916fe16894af23cdca678b9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 22:12:21 -0700 Subject: [PATCH 0961/2729] Update 2322.Minimum-Score-After-Removals-on-a-Tree.cpp --- ...Minimum-Score-After-Removals-on-a-Tree.cpp | 83 ++++++++++--------- 1 file changed, 42 insertions(+), 41 deletions(-) diff --git a/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/2322.Minimum-Score-After-Removals-on-a-Tree.cpp b/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/2322.Minimum-Score-After-Removals-on-a-Tree.cpp index 4126a6f0a..1c36e33b4 100644 --- a/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/2322.Minimum-Score-After-Removals-on-a-Tree.cpp +++ b/Tree/2322.Minimum-Score-After-Removals-on-a-Tree/2322.Minimum-Score-After-Removals-on-a-Tree.cpp @@ -1,14 +1,13 @@ -class Solution { - unordered_set next[1000]; +class Solution { + unordered_set next[1005]; // next[i]: a set of adjacent nodes next to i + int visited[1005]; vectornums; - vectorvisited; int n; public: int minimumScore(vector& nums, vector>& edges) { - this->nums = nums; this->n = nums.size(); - visited.resize(n); + this->nums = nums; for (auto edge: edges) { int a = edge[0], b = edge[1]; @@ -17,70 +16,72 @@ class Solution { } int ret = INT_MAX; - for (int i=0; i Date: Sun, 26 Jun 2022 22:29:52 -0700 Subject: [PATCH 0962/2729] Create Readme.md --- .../2321.Maximum-Score-Of-Spliced-Array/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array/Readme.md diff --git a/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array/Readme.md b/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array/Readme.md new file mode 100644 index 000000000..dfe06eb6e --- /dev/null +++ b/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array/Readme.md @@ -0,0 +1,3 @@ +### 2321.Maximum-Score-Of-Spliced-Array + +我们思考将nums1的某一段替换成nums2后元素和最大,肯定是希望"增量"最大。显然,我们构造```gain[i] = nums2[i]-nums1[i]```,必然就是在gain中找一段maximum subarray sum. 将这段subarray sum加在nums1原先的元素和上,就是nums1经过区间替换后的最大元素和。 From fdf2f4c41e9f918e1c1ac02d9fe381e9e7bd1ed9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 23:21:27 -0700 Subject: [PATCH 0963/2729] Create 2320.Count-Number-of-Ways-to-Place-Houses.cpp --- ...0.Count-Number-of-Ways-to-Place-Houses.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses.cpp diff --git a/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses.cpp b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses.cpp new file mode 100644 index 000000000..bbfc862b6 --- /dev/null +++ b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses.cpp @@ -0,0 +1,21 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[10001][2]; +public: + int countHousePlacements(int n) + { + dp[1][0] = 1; + dp[1][1] = 1; + + for (int i=2; i<=n; i++) + { + dp[i][0] = (dp[i-1][0] + dp[i-1][1])%M; + dp[i][1] = dp[i-1][0]; + } + + LL ret = (dp[n][0]+dp[n][1]) % M; + + return ret * ret % M; + } +}; From 8069772bf5d1e42093b0302083b8b00c41c6bea2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 23:22:11 -0700 Subject: [PATCH 0964/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8a74fbc3e..d91647b19 100644 --- a/Readme.md +++ b/Readme.md @@ -623,6 +623,7 @@ * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) +[2320.Count-Number-of-Ways-to-Place-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses) (M+) [1388.Pizza-With-3n-Slices](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1388.Pizza-With-3n-Slices) (H-) [276.Paint-Fence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/276.Paint-Fence) (H-) [265.Paint-House-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/265.Paint-House-II) (H) From 8f62433d8b322b6c32d71026e4956d658b4cece8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 23:29:37 -0700 Subject: [PATCH 0965/2729] Create 2320.Count-Number-of-Ways-to-Place-Houses_v2.cpp --- ...ount-Number-of-Ways-to-Place-Houses_v2.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v2.cpp diff --git a/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v2.cpp b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v2.cpp new file mode 100644 index 000000000..ff32bab04 --- /dev/null +++ b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v2.cpp @@ -0,0 +1,22 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[10001]; // dp[i]: the # of plans so that there is a building at the i-th plot +public: + int countHousePlacements(int n) + { + dp[0] = 0; + dp[1] = 1; + + for (int i=2; i<=n; i++) + { + dp[i] = (dp[i-1] + dp[i-2])%M; + } + + LL ret = 1; + for (int i=1; i<=n; i++) + ret = (ret+dp[i]) % M; + + return ret * ret % M; + } +}; From 89cbb349f3a162ec68e2c2a59bd21fca824f3af1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Jun 2022 23:30:58 -0700 Subject: [PATCH 0966/2729] Update and rename 2320.Count-Number-of-Ways-to-Place-Houses.cpp to 2320.Count-Number-of-Ways-to-Place-Houses_v1.cpp --- ...> 2320.Count-Number-of-Ways-to-Place-Houses_v1.cpp} | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) rename Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/{2320.Count-Number-of-Ways-to-Place-Houses.cpp => 2320.Count-Number-of-Ways-to-Place-Houses_v1.cpp} (58%) diff --git a/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses.cpp b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v1.cpp similarity index 58% rename from Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses.cpp rename to Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v1.cpp index bbfc862b6..34580f542 100644 --- a/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses.cpp +++ b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v1.cpp @@ -1,14 +1,16 @@ using LL = long long; LL M = 1e9+7; class Solution { - LL dp[10001][2]; + LL dp[10001][2]; + // dp[i][0]: the # of plans so that there is no building at the i-th plot + // dp[i][1]: the # of plans so that there is a building at the i-th plot public: int countHousePlacements(int n) { - dp[1][0] = 1; - dp[1][1] = 1; + dp[0][0] = 1; + dp[0][1] = 0; - for (int i=2; i<=n; i++) + for (int i=1; i<=n; i++) { dp[i][0] = (dp[i-1][0] + dp[i-1][1])%M; dp[i][1] = dp[i-1][0]; From 1e355d5e51c2167e95442e139522ffd8afb5dcea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 Jun 2022 00:21:37 -0700 Subject: [PATCH 0967/2729] Create 2320.Count-Number-of-Ways-to-Place-Houses_v3.cpp --- ...ount-Number-of-Ways-to-Place-Houses_v3.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v3.cpp diff --git a/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v3.cpp b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v3.cpp new file mode 100644 index 000000000..9250a2a75 --- /dev/null +++ b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/2320.Count-Number-of-Ways-to-Place-Houses_v3.cpp @@ -0,0 +1,27 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + unordered_mapmemo; +public: + int countHousePlacements(int n) + { + LL ret = 0; + for (int r=0; 2*r-1<=n; r++) + ret = (ret + C(n-r+1, r))%M; + return ret * ret % M; + } + + LL C(int x, int y) + { + if (x Date: Mon, 27 Jun 2022 00:28:20 -0700 Subject: [PATCH 0968/2729] Create Readme.md --- .../Readme.md | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/Readme.md diff --git a/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/Readme.md b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/Readme.md new file mode 100644 index 000000000..872081b18 --- /dev/null +++ b/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses/Readme.md @@ -0,0 +1,32 @@ +### 2320.Count-Number-of-Ways-to-Place-Houses + +本题的本质就是House Robber。House Robber求的是“无相邻元素的序列”的最大元素和。本题求的是“无相邻元素的序列”的方案总数。 + +#### 解法1:DP +令dp[i][0]表示第i个位置不放置建筑的方案总数,dp[i][1]表示第i个位置放置建筑的方案总数。不难有转移方程 +```cpp +dp[i][0] = (dp[i-1][0] + dp[i-1][1])%M; +dp[i][1] = dp[i-1][0]; +``` +边界条件是dp[0][0]和dp[0][1]。考虑我们的位置是从1开始的,那么dp[0][]意味着根本没有位置放置建筑,故有 +``` +dp[0][0] = 1 +dp[0][1] = 0 +``` +最终的答案是考察第n处位置,放置建筑与不放置建筑的方案总和,即```dp[n][0]+dp[n][1]```. + +#### 解法2:Fibonacci +解答区的很多帖子都提到了斐波那契数列。如果令dp[i]表示前i个plot里合法的方案,那么dp[i]呈现的是斐波那契数列的性质。 + +例如dp[1] = 2, dp[2] = 3, dp[3] = 5, .... + +但是```dp[i]=dp[i-2]+dp[i-1]```的实际意义,确实非常难以解释的。参见我对LC美服评论区的[质疑](https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2203989/So-far-I-do-not-see-a-correct-explanation-why-the-result-is-a-Fibo-series) + +#### 解法3:组合数 +假设我们拆出一个小问题来看,在n个位置里放置k个元素,要求没有元素相邻,有多少种方案?这个答案是```C(n-(k-1), k)```. + +解释如下。我们将n个位置里拿走k-1个位置。剩下的位置里任意放置k个元素。然后再将拿走的k-1个位置插在已经放置的k个元素中间,就完美地实现了题目要求,即没有任何两个元素相邻。 + +我们遍历k,从最小的0,最大直至```2*k-1<=n```(否则必然会有两个元素相邻),将所有的组合数都加起来,就是答案。 + +当然,将这些组合数单独逐个求出,效率是低的,这个代码会TLE。 From 0c1c9444ab03e0b77fa675ce878c214007655892 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 28 Jun 2022 00:19:36 -0700 Subject: [PATCH 0969/2729] Create 2318.Number-of-Distinct-Roll-Sequences.cpp --- ...2318.Number-of-Distinct-Roll-Sequences.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/2318.Number-of-Distinct-Roll-Sequences.cpp diff --git a/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/2318.Number-of-Distinct-Roll-Sequences.cpp b/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/2318.Number-of-Distinct-Roll-Sequences.cpp new file mode 100644 index 000000000..1a78bcb8c --- /dev/null +++ b/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/2318.Number-of-Distinct-Roll-Sequences.cpp @@ -0,0 +1,46 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[10001][7][7]; +public: + int distinctSequences(int n) + { + if (n==1) return 6; + + LL count = 0; + for (int a=1; a<=6; a++) + for (int b=1; b<=6; b++) + { + if (a!=b && gcd(a,b)==1) + { + dp[2][a][b] = 1; + count++; + } + } + if (n==2) return count; + + LL ret = 0; + for (int i=3; i<=n; i++) + for (int a=1; a<=6; a++) + for (int b=1; b<=6; b++) + { + if (a==b) continue; + if (gcd(a,b)>1) continue; + + for (int x=1; x<=6; x++) + { + if (x==a) continue; + if (x==b) continue; + if (gcd(x,a)>1) continue; + + dp[i][a][b] += dp[i-1][x][a]; + dp[i][a][b] %= M; + } + + if (i==n) + ret = (ret + dp[i][a][b]) %M; + } + + return ret; + } +}; From b50debaae0b22df35dbd48f8d46c51d59aaf30bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 28 Jun 2022 00:20:18 -0700 Subject: [PATCH 0970/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d91647b19..33ae35c54 100644 --- a/Readme.md +++ b/Readme.md @@ -648,6 +648,7 @@ [1883.Minimum-Skips-to-Arrive-at-Meeting-On-Time](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1883.Minimum-Skips-to-Arrive-at-Meeting-On-Time) (H) [2036.Maximum-Alternating-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum) (M+) [2143.Choose-Numbers-From-Two-Arrays-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range) (H) +[2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From 06aa0b01a82469c821e2fab1d0585403987998a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 28 Jun 2022 09:49:53 -0700 Subject: [PATCH 0971/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/Readme.md diff --git a/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/Readme.md b/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/Readme.md new file mode 100644 index 000000000..507701172 --- /dev/null +++ b/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/Readme.md @@ -0,0 +1,13 @@ +### 2318.Number-of-Distinct-Roll-Sequences + +我们在基于前i-1位的方案之上,考虑序列的第i位的填充时,思考能否填写某个数字d,需要的约束有:和前一位不能相等,和前一位必须互质,和前两位不能相等。可见,dp[i]关系到了前两位的具体方案。所以我们设计状态dp[i][a][b],表示前i位里最后两位数字分别是a和b的情况下,所有的合法方案数目。 + +接下来我们就很容易看出dp[i]与dp[i-1]之间的转移关系。因为i的最后两位是a和b,那么i-1的最后两位必然是某个数x和a。所以我们枚举所有合法的x使得dp[i]能将b接在dp[i-1]之后,要使得```xab```合法需要的条件是: +1. a和x不能相等 +2. b和x不能相等 +3. x和a必须互质 +满足这些条件的话,就意味着```dp[i][a][b] += dp[i-1][x][a]```,即将所有合法的dp[i-1][x][a]方案后面直接加上一个b。 + +有人会说,这里dp[i][a][b]没有考虑检查a是否和x之前的那个数字相同呀。事实上,dp[i]的合法性是建立在dp[i-1]的基础上的。如果dp[i-1][x][a]代表了合法的方案数目,那么自然就不会存在a与x之前的数字相同的问题。 + +在实际计算中,我们在更新所有dp[i][a][b]的过程中,可以通过计算ab本身的合法性,来提前跳过一些不合法的dp[i][a][b] From d586a6ba215b5c051d3cd604be1c0e1a8008f122 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 28 Jun 2022 23:21:28 -0700 Subject: [PATCH 0972/2729] Update 2318.Number-of-Distinct-Roll-Sequences.cpp --- .../2318.Number-of-Distinct-Roll-Sequences.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/2318.Number-of-Distinct-Roll-Sequences.cpp b/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/2318.Number-of-Distinct-Roll-Sequences.cpp index 1a78bcb8c..9e55479c6 100644 --- a/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/2318.Number-of-Distinct-Roll-Sequences.cpp +++ b/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences/2318.Number-of-Distinct-Roll-Sequences.cpp @@ -29,12 +29,11 @@ class Solution { for (int x=1; x<=6; x++) { - if (x==a) continue; - if (x==b) continue; - if (gcd(x,a)>1) continue; - - dp[i][a][b] += dp[i-1][x][a]; - dp[i][a][b] %= M; + if (x!=b) + { + dp[i][a][b] += dp[i-1][x][a]; + dp[i][a][b] %= M; + } } if (i==n) From b72aba5621194092e6b89e17d0326e429d463975 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 29 Jun 2022 23:17:48 -0700 Subject: [PATCH 0973/2729] Update 1268.Search-Suggestions-System_v1.cpp --- .../1268.Search-Suggestions-System_v1.cpp | 87 ++++++++----------- 1 file changed, 37 insertions(+), 50 deletions(-) diff --git a/Trie/1268.Search-Suggestions-System/1268.Search-Suggestions-System_v1.cpp b/Trie/1268.Search-Suggestions-System/1268.Search-Suggestions-System_v1.cpp index d68782856..ec9dcebb9 100644 --- a/Trie/1268.Search-Suggestions-System/1268.Search-Suggestions-System_v1.cpp +++ b/Trie/1268.Search-Suggestions-System/1268.Search-Suggestions-System_v1.cpp @@ -1,26 +1,33 @@ -class Solution { - class TrieNode +class TrieNode +{ + public: + TrieNode* next[26]; + bool isEnd; + TrieNode() { - public: - TrieNode* next[26]; - int isEnd; - TrieNode() - { - for (int i=0; i<26; i++) - next[i]=NULL; - isEnd=0; - } - }; - TrieNode* root; - + for (int i=0; i<26; i++) + next[i]=NULL; + isEnd=0; + } +}; + +class Solution { + TrieNode* root; public: vector> suggestedProducts(vector& products, string searchWord) { root = new TrieNode(); - for (auto word: products) - insert(word); - - cout<next[ch-'a']==NULL) + node->next[ch-'a'] = new TrieNode(); + node = node->next[ch-'a']; + } + node->isEnd = true; + } vector>rets; TrieNode* node=root; @@ -38,50 +45,30 @@ class Solution { node = node->next[ch-'a']; word.push_back(ch); vectorans; - string temp = ""; - DFS(node,ans,temp); + string str = ""; + DFS(node,ans,str); - while (ans.size()>3) - ans.pop_back(); for (int j=0; jnext[ch-'a']==NULL) - node->next[ch-'a']=new TrieNode(); - node=node->next[ch-'a']; - } - node->isEnd+=1; - } + } - void DFS(TrieNode* node, vector&ans, string temp) - { - if (node->isEnd>0) - { - for (int k=0; kisEnd; k++) - ans.push_back(temp); - } - + void DFS(TrieNode* node, vector&ans, string& str) + { + if (ans.size()==3) return; + + if (node->isEnd == true) + ans.push_back(str); for (int i=0; i<26; i++) { - if (ans.size()>3) break; if (node->next[i]==NULL) continue; - temp.push_back('a'+i); - DFS(node->next[i],ans, temp); - temp.pop_back(); + str.push_back('a'+i); + DFS(node->next[i],ans, str); + str.pop_back(); } } - - }; From 7d9a6fe9a6619381b6989b9ae9547b3428c40d93 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 29 Jun 2022 23:20:21 -0700 Subject: [PATCH 0974/2729] Update Readme.md --- Trie/1268.Search-Suggestions-System/Readme.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Trie/1268.Search-Suggestions-System/Readme.md b/Trie/1268.Search-Suggestions-System/Readme.md index 46a03c266..540049610 100644 --- a/Trie/1268.Search-Suggestions-System/Readme.md +++ b/Trie/1268.Search-Suggestions-System/Readme.md @@ -1,14 +1,12 @@ ### 1268.Search-Suggestions-System #### 解法1: -比较严谨的做法是用Trie。根据searchWord的前缀(比如说前k个字母)在Trie中推进直至某个节点,然后以这个节点为根,用DFS的方法、根据先左后右的规则,找出最多三个合法的子路径(即能够拼成一个product)。 - -特别注意,此题中的product允许有重复,所以在TrieNode定义中,传统的bool isEnd需要改造为int count,并在构造整颗树的时候用它来计算有多少个重复(即共享完全相同的路径)的product。在DFS的过程中,如果推进到某个节点的count>1,说明会有多于1个product有着相同的名字,我们需要把它们都算上。 +比较严谨的做法是用Trie。先将所有的products的单词建树。然后,根据searchWord的前缀(比如说前k个字母)在Trie中推进直至某个节点node,然后以node为根进行DFS,根据先序遍历的规则(优先走左下方的子树),找出字典序最小的三个到叶子节点的子路径。 #### 解法2: 有一种非常取巧的方法,那就是将所有product按照字典排序。然后查找searchWord在里面的位置(用lower_bound定位),得到的就是字典序恰好大于等于searchWord的那个单词。我们查看以这个单词开始的连续三个单词,是否与searchWord共享指定书目的前缀,是的话就相应收入囊中。 -这种方法可以不必理会products中是否存在重复。但是第一步排序的过程其实比较耗时,不过题目给出了```1 <= Σ products[i].length <= 2 * 10^4```,这就是暗示了字符串排序的复杂度是可以接受的。 +这种方法第一步排序的过程其实比较耗时,不过题目给出了```1 <= Σ products[i].length <= 2 * 10^4```,这就是暗示了字符串排序的复杂度是可以接受的。 -[Leetcode Link](https://leetcode.com/problems/search-suggestions-system) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/search-suggestions-system) From 397844fb6b1e0261af03528941e5e51d87ddc3cc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Jul 2022 22:14:55 -0700 Subject: [PATCH 0975/2729] Create 1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp --- ...Path-With-Maximum-Minimum-Value.cpp_v2.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp new file mode 100644 index 000000000..c434075f3 --- /dev/null +++ b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp @@ -0,0 +1,37 @@ +using AI2 = array; +class Solution { + vector>dir = {{1,0},{-1,0},{0,1},{0,-1}}; +public: + int maximumMinimumPath(vector>& A) + { + int M = A.size(); + int N = A[0].size(); + priority_queuepq; + + pq.push({A[0][0], 0,0}); + vector>visited(M, vector(N,0)); + vector>rets(M, vector(N,0)); + + while (pq.size()>0) + { + auto [d, x, y] = pq.top(); + pq.pop(); + if (visited[x][y]==1) continue; + rets[x][y] = d; + visited[x][y] = 1; + if (x==M-1 && y==N-1) + return d; + + for (int k=0; k<4; k++) + { + int i = x+dir[k].first; + int j = y+dir[k].second; + if (i<0||i>=M||j<0||j>=N) + continue; + pq.push({min(d, A[i][j]), i, j}); + } + } + + return -1; + } +}; From d038b71d5958500fa722b007d503f3401ccf3e5a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Jul 2022 22:28:15 -0700 Subject: [PATCH 0976/2729] Update Readme.md --- .../Readme.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md index 14679ddcf..3af3b4fc9 100644 --- a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md +++ b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md @@ -1,11 +1,11 @@ ### 1102.Path-With-Maximum-Minimum-Value -此题是二分法的非常精彩的应用. +#### 解法1:二分搜索 -我们想,如果这个maximum score是x,那么意味着存在一条路径,里面不能有任何小于x的格子.因此,如果给定x,我们尝试用BFS的方法从左上角走到右下角.如果能抵达,说明至少存在一条成功的路,他们所有的元素都不会小于x,而且x还可能有提升的空间.相反,如果不能走到,说明从左上到右下被一些列小于x的各自给阻断了,因此我们对于maximum score的预期必须下调,至少得小于x. +我们想,如果这个maximum score是x,那么意味着存在一条路径,里面不能有任何小于x的格子。因此,如果给定x,我们尝试用BFS的方法从左上角走到右下角,约定不能经过任何小于x的格子。如果能抵达,说明至少存在一条成功的路,其沿途元素都不会小于x,故x是一个可行解,我们可以调高对maximum score的预期。相反,如果不能走到,说明从左上到右下肯定会被一系列小于x的格子给阻断了,因此我们对于maximum score的预期必须下调,至少得小于x. 所以二分的策略就非常清楚了: -``` +```cpp while (left Date: Sat, 2 Jul 2022 12:03:29 -0700 Subject: [PATCH 0977/2729] Update 1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp --- ...1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp index c434075f3..9395efd49 100644 --- a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp +++ b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp @@ -1,14 +1,14 @@ -using AI2 = array; +using AI3 = array; class Solution { vector>dir = {{1,0},{-1,0},{0,1},{0,-1}}; public: - int maximumMinimumPath(vector>& A) + int maximumMinimumPath(vector>& grid) { - int M = A.size(); - int N = A[0].size(); - priority_queuepq; + int M = grid.size(); + int N = grid[0].size(); + priority_queuepq; - pq.push({A[0][0], 0,0}); + pq.push({grid[0][0], 0,0}); vector>visited(M, vector(N,0)); vector>rets(M, vector(N,0)); @@ -28,7 +28,7 @@ class Solution { int j = y+dir[k].second; if (i<0||i>=M||j<0||j>=N) continue; - pq.push({min(d, A[i][j]), i, j}); + pq.push({min(d, grid[i][j]), i, j}); } } From d05b324e54b151ff40f9da1dc6fbc075088377e6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 12:08:17 -0700 Subject: [PATCH 0978/2729] Update 1102.Path-With-Maximum-Minimum-Value.cpp --- .../1102.Path-With-Maximum-Minimum-Value.cpp | 37 ++++++------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp index 687cb3831..e45f394ed 100644 --- a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp +++ b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp @@ -1,23 +1,13 @@ class Solution { public: - int maximumMinimumPath(vector>& A) + int maximumMinimumPath(vector>& grid) { - int left = INT_MAX; - int right = INT_MIN; - int M = A.size(); - int N = A[0].size(); - for (int i=0; i> A, int K) + bool check(vector> grid, int K) { - if (A[0][0]>({{1,0},{-1,0},{0,1},{0,-1}}); - int M = A.size(); - int N = A[0].size(); + int M = grid.size(), N = grid[0].size(); queue>q; q.push({0,0}); - A[0][0] = -1; + vector>visited(M, vector(N)); + visited[0][0] = 1; while (q.size()>0) { @@ -47,19 +37,16 @@ class Solution { { int i = x+dir[k].first; int j = y+dir[k].second; - if (i<0||i>=M||j<0||j>=N) - continue; - if (A[i][j]==-1) - continue; - if (A[i][j]=M||j<0||j>=N) continue; + if (visited[i][j]) continue; + if (grid[i][j] Date: Sat, 2 Jul 2022 12:09:01 -0700 Subject: [PATCH 0979/2729] Rename 1102.Path-With-Maximum-Minimum-Value.cpp to 1102.Path-With-Maximum-Minimum-Value_v1.cpp --- ...imum-Value.cpp => 1102.Path-With-Maximum-Minimum-Value_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Binary_Search/1102.Path-With-Maximum-Minimum-Value/{1102.Path-With-Maximum-Minimum-Value.cpp => 1102.Path-With-Maximum-Minimum-Value_v1.cpp} (100%) diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value_v1.cpp similarity index 100% rename from Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp rename to Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value_v1.cpp From cdaf272def3a3eae82fe1e47296bf90079035f20 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 12:14:42 -0700 Subject: [PATCH 0980/2729] Rename 1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp to 1102.Path-With-Maximum-Minimum-Value_v2.cpp --- ...lue.cpp_v2.cpp => 1102.Path-With-Maximum-Minimum-Value_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Binary_Search/1102.Path-With-Maximum-Minimum-Value/{1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp => 1102.Path-With-Maximum-Minimum-Value_v2.cpp} (100%) diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value_v2.cpp similarity index 100% rename from Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value.cpp_v2.cpp rename to Binary_Search/1102.Path-With-Maximum-Minimum-Value/1102.Path-With-Maximum-Minimum-Value_v2.cpp From c1173a72586c81f7a1191627d879f49da8d14253 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 13:40:07 -0700 Subject: [PATCH 0981/2729] Update Readme.md --- Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md index 3af3b4fc9..86864e67d 100644 --- a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md +++ b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md @@ -20,9 +20,8 @@ #### 解法2:Dijkstra 此题还可以用Dijkstra来解决,不过这是一个与常规Dijkstra问题完全对偶的场景。 -Dijkstra通常用在求最短路径的问题,在非负边权的图里,经过的节点越多,往往意味着路径会更长。所以在小顶堆的PQ中越早弹出来的节点,就是能实际路径最短的节点。 +Dijkstra通常用在求最短路径的问题,在非负边权的图里,经过的节点越多,往往意味着路径会更长。所以在小顶堆的PQ中越早弹出来的节点,对应的就是该节点的最短路径。 本题反其道而行之,求的是一个“最长路径”的问题。但这道题定义的“路径长度”不是元素和,而是沿途元素里面的最小值。所以经过的格子越多,“路径长度”反而会越小。所以结合大顶堆(而不是通常的小顶堆),也能够将这道题解出来。 - [Leetcode Link](https://leetcode.com/problems/path-with-maximum-minimum-value) From e0ae1fb213c8b0e941889e9837e24431ce34f232 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 14:04:16 -0700 Subject: [PATCH 0982/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 33ae35c54..e2ecaaea1 100644 --- a/Readme.md +++ b/Readme.md @@ -523,6 +523,7 @@ [499.The-Maze-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/499.The-Maze-III) (H) [787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) [882.Reachable-Nodes-In-Subdivided-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/882.Reachable-Nodes-In-Subdivided-Graph ) (H) +[1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) [1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid) (H) [1514.Path-with-Maximum-Probability](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1514.Path-with-Maximum-Probability) (H) [1786.Number-of-Restricted-Paths-From-First-to-Last-Node](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1786.Number-of-Restricted-Paths-From-First-to-Last-Node) (M+) From 407df52e996da820a06405ed61aff05d046cb4bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 16:02:04 -0700 Subject: [PATCH 0983/2729] Update Readme.md --- Union_Find/1631.Path-With-Minimum-Effort/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Union_Find/1631.Path-With-Minimum-Effort/Readme.md b/Union_Find/1631.Path-With-Minimum-Effort/Readme.md index c9565cf93..704b50ff6 100644 --- a/Union_Find/1631.Path-With-Minimum-Effort/Readme.md +++ b/Union_Find/1631.Path-With-Minimum-Effort/Readme.md @@ -7,3 +7,5 @@ #### 解法2:Union Find 我们将所有的边按照diff从小到大排个序。优先选最小的边,看能联通哪些点;再选次小的边,看能联通哪些点。直至选中某条边之后,发现起点和终点恰好联通,那么这条边的diff就是答案。 + +注:此题和1102非常相似。 From aee6d6d5a4ebb8c220ffe329f7d611a317702833 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 16:02:42 -0700 Subject: [PATCH 0984/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e2ecaaea1..ac05fb854 100644 --- a/Readme.md +++ b/Readme.md @@ -90,6 +90,7 @@ [1011.Capacity-To-Ship-Packages-Within-D-Days](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1011.Capacity-To-Ship-Packages-Within-D-Days) (M) [1060.Missing-Element-in-Sorted-Array](https://github.com/wisdompeak/LeetCode/blob/master/Binary_Search/1060.Missing-Element-in-Sorted-Array) (H) [1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) +[1631.Path-With-Minimum-Effort](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1631.Path-With-Minimum-Effort) (H-) [1231.Divide-Chocolate](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1231.Divide-Chocolate) (M) [1283.Find-the-Smallest-Divisor-Given-a-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1283.Find-the-Smallest-Divisor-Given-a-Threshold) (M) [1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold) (H-) From afa8f7c19dfdfebd6ea0eeec0b12740217b28328 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 16:03:07 -0700 Subject: [PATCH 0985/2729] Update Readme.md --- Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md index 86864e67d..78d2195e0 100644 --- a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md +++ b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md @@ -24,4 +24,6 @@ Dijkstra通常用在求最短路径的问题,在非负边权的图里,经过 本题反其道而行之,求的是一个“最长路径”的问题。但这道题定义的“路径长度”不是元素和,而是沿途元素里面的最小值。所以经过的格子越多,“路径长度”反而会越小。所以结合大顶堆(而不是通常的小顶堆),也能够将这道题解出来。 +注:此题和1631非常相似。 + [Leetcode Link](https://leetcode.com/problems/path-with-maximum-minimum-value) From adbf372e357ce5d772feccaf456d3d90f4ebef21 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 16:03:49 -0700 Subject: [PATCH 0986/2729] Update Readme.md --- Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md index 78d2195e0..b76823958 100644 --- a/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md +++ b/Binary_Search/1102.Path-With-Maximum-Minimum-Value/Readme.md @@ -24,6 +24,6 @@ Dijkstra通常用在求最短路径的问题,在非负边权的图里,经过 本题反其道而行之,求的是一个“最长路径”的问题。但这道题定义的“路径长度”不是元素和,而是沿途元素里面的最小值。所以经过的格子越多,“路径长度”反而会越小。所以结合大顶堆(而不是通常的小顶堆),也能够将这道题解出来。 -注:此题和1631非常相似。 +注:此题和[1631](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1631.Path-With-Minimum-Effort)非常相似。 [Leetcode Link](https://leetcode.com/problems/path-with-maximum-minimum-value) From cdce66c28f3c8ef0dcd4ca9d3696b5b7e00b16e2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 16:04:19 -0700 Subject: [PATCH 0987/2729] Update Readme.md --- Union_Find/1631.Path-With-Minimum-Effort/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Union_Find/1631.Path-With-Minimum-Effort/Readme.md b/Union_Find/1631.Path-With-Minimum-Effort/Readme.md index 704b50ff6..f71a1fdd4 100644 --- a/Union_Find/1631.Path-With-Minimum-Effort/Readme.md +++ b/Union_Find/1631.Path-With-Minimum-Effort/Readme.md @@ -8,4 +8,4 @@ #### 解法2:Union Find 我们将所有的边按照diff从小到大排个序。优先选最小的边,看能联通哪些点;再选次小的边,看能联通哪些点。直至选中某条边之后,发现起点和终点恰好联通,那么这条边的diff就是答案。 -注:此题和1102非常相似。 +注:此题和[1102](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value)非常相似。 From a1c476791f3f0990a90fbb47c15813e3993b2185 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 16:23:06 -0700 Subject: [PATCH 0988/2729] Update 1388.Pizza-With-3n-Slices.cpp --- .../1388.Pizza-With-3n-Slices.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Dynamic_Programming/1388.Pizza-With-3n-Slices/1388.Pizza-With-3n-Slices.cpp b/Dynamic_Programming/1388.Pizza-With-3n-Slices/1388.Pizza-With-3n-Slices.cpp index 39db61175..c2ede5072 100644 --- a/Dynamic_Programming/1388.Pizza-With-3n-Slices/1388.Pizza-With-3n-Slices.cpp +++ b/Dynamic_Programming/1388.Pizza-With-3n-Slices/1388.Pizza-With-3n-Slices.cpp @@ -7,17 +7,17 @@ class Solution { } int helper(int st, int en, int k, vector& slices) - { - vectorf(k+1,0); // f[i]: the maximum gain by the current round if we take i slices, and we do take the current slice. - vectorg(k+1,0); // g[i]: the maximum gain by the current round if we take i slices, and we do NOT take the current slice. + { + vectordp0(k+1); + vectordp1(k+1); for (int i=st; i<=en; i++) for (int j=min(k,i-st+1); j>=1; j--) { - g[j] = max(g[j], f[j]); - f[j] = g[j-1] + slices[i]; + dp0[j] = max(dp0[j], dp1[j]); + dp1[j] = dp0[j-1] + slices[i]; } - return max(f[k], g[k]); + return max(dp0[k], dp1[k]); } }; From 56d6d6bd34ab876d467fd28e9fd6bbb32ca512ef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Jul 2022 16:30:16 -0700 Subject: [PATCH 0989/2729] Update Readme.md --- Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md b/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md index 58c299be1..b4f6fb092 100644 --- a/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md +++ b/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md @@ -1,6 +1,6 @@ ### 1388.Pizza-With-3n-Slices -此题的条件和```213.House-Robber-II```非常相似:永远不能取相邻的两个元素;首尾元素认为是相邻的。此外,本题隐含着领一个条件:最多只能取n/3个元素。 +此题的条件和```213.House-Robber-II```非常相似:永远不能取相邻的两个元素;首尾元素认为是相邻的。此外,本题隐含着领一个条件:最多取n/3个元素(事实上肯定会取满n/3个)。 当然,我们需要验证一下,是不是任意的n/3个互不相邻的元素集合,都可以按照题目中的取数规则来实现。事实上是可以的。例如```1000101010000```,有13个元素。其中1代表我们打算取的数。我们永远先取较为外层的数(随之删去左右相邻的两个零):原序列可以得到```0010101000```,接下来```0101000```,接下来```1000```,最后```0```.虽然严格的证明不太容易,但是这个规律还是容易发现的。 From 5145d87b999054bf3a363e7a59ab12c4ec6db697 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 01:15:25 -0700 Subject: [PATCH 0990/2729] Update Readme.md --- Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md b/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md index b4f6fb092..73c80dc42 100644 --- a/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md +++ b/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md @@ -1,8 +1,10 @@ ### 1388.Pizza-With-3n-Slices -此题的条件和```213.House-Robber-II```非常相似:永远不能取相邻的两个元素;首尾元素认为是相邻的。此外,本题隐含着领一个条件:最多取n/3个元素(事实上肯定会取满n/3个)。 +此题的约束和```213.House-Robber-II```非常相似:1.永远不能取相邻的两个元素;2.首尾元素认为是相邻的(即不能同时取首尾两个元素);3.此外本题还有一个条件,恰好取n/3个。 -当然,我们需要验证一下,是不是任意的n/3个互不相邻的元素集合,都可以按照题目中的取数规则来实现。事实上是可以的。例如```1000101010000```,有13个元素。其中1代表我们打算取的数。我们永远先取较为外层的数(随之删去左右相邻的两个零):原序列可以得到```0010101000```,接下来```0101000```,接下来```1000```,最后```0```.虽然严格的证明不太容易,但是这个规律还是容易发现的。 +事实上,满足前述约束123的任何一种选取方案,都可以对应于一种本题里取pizza的方案。反之也是。严格的证明可以参考[这里](https://leetcode.cn/problems/pizza-with-3n-slices/solution/3n-kuai-pi-sa-by-leetcode-solution/)。 + +当然,我们这里可以简单用一个例子来验证一下。例如```100010101000```,有12个元素。其中三分之一(4个1)代表我们打算取的元素,它们是满足约束1,2,3的。我们先取较为外层的数(随之删去左右相邻的两个零),原序列可以得到```001010100```,接下来```010100```,接下来```100```,最后恰好取光. 因此,本题就是House-Robber-II再加上取n/3个元素的条件。 From b25f642638fefab464eb32ecbd26333b39eb1951 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 01:16:38 -0700 Subject: [PATCH 0991/2729] Update Readme.md --- Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md b/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md index 73c80dc42..16e8ff703 100644 --- a/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md +++ b/Dynamic_Programming/1388.Pizza-With-3n-Slices/Readme.md @@ -4,7 +4,7 @@ 事实上,满足前述约束123的任何一种选取方案,都可以对应于一种本题里取pizza的方案。反之也是。严格的证明可以参考[这里](https://leetcode.cn/problems/pizza-with-3n-slices/solution/3n-kuai-pi-sa-by-leetcode-solution/)。 -当然,我们这里可以简单用一个例子来验证一下。例如```100010101000```,有12个元素。其中三分之一(4个1)代表我们打算取的元素,它们是满足约束1,2,3的。我们先取较为外层的数(随之删去左右相邻的两个零),原序列可以得到```001010100```,接下来```010100```,接下来```100```,最后恰好取光. +当然,我们这里可以简单用一个例子来验证一下。例如```100010101000```,有12个元素。其中三分之一(4个1)代表我们打算取的元素,它们是满足约束1,2,3的。我们先拿走最左边的1(随之删去左右相邻的两个零),原序列可以得到```001010100```,接下来```010100```,接下来```100```,最后恰好取光. 因此,本题就是House-Robber-II再加上取n/3个元素的条件。 From dce517043e71918cc594665e1c4d1aaa1afbc8ef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 01:29:31 -0700 Subject: [PATCH 0992/2729] Create 2328.Number-of-Increasing-Paths-in-a-Grid.cpp --- ...8.Number-of-Increasing-Paths-in-a-Grid.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid.cpp diff --git a/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid.cpp b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid.cpp new file mode 100644 index 000000000..90587acd5 --- /dev/null +++ b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid.cpp @@ -0,0 +1,34 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[1000][1000]; +public: + int countPaths(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + LL ret = 0; + for (int i=0; i>& grid, int i, int j) + { + int m = grid.size(), n = grid[0].size(); + if (dp[i][j]!=0) return dp[i][j]; + + dp[i][j] = 1; + vector>dir = {{1,0},{-1,0},{0,1},{0,-1}}; + for (int k=0; k<4; k++) + { + int x = i+dir[k].first; + int y = j+dir[k].second; + if (x<0||x>=m||y<0||y>=n) continue; + if (grid[x][y]>=grid[i][j]) continue; + dp[i][j] = (dp[i][j] + dfs(grid, x, y)) % M; + } + + return dp[i][j]; + } +}; From e7bfd056dde69f779b1e4f0a6e75fef93a62acde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 01:30:05 -0700 Subject: [PATCH 0993/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ac05fb854..05cb2e4ba 100644 --- a/Readme.md +++ b/Readme.md @@ -453,6 +453,7 @@ [2305.Fair-Distribution-of-Cookies](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2305.Fair-Distribution-of-Cookies) (H-) * ``memorization`` [329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix) (M) +[2328.Number-of-Increasing-Paths-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2328.Number-of-Increasing-Paths-in-a-Grid) (M) [638.Shopping-Offers](https://github.com/wisdompeak/LeetCode/tree/master/DFS/638.Shopping-Offers) (M+) [403.Frog-Jump](https://github.com/wisdompeak/LeetCode/tree/master/DFS/403.Frog-Jump) (M+) [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) From cdef17e642f839b9e83fb0ace21c773e9fd7eea4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 01:30:48 -0700 Subject: [PATCH 0994/2729] Update Readme.md --- DFS/329.Longest-Increasing-Path-in-a-Matrix/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DFS/329.Longest-Increasing-Path-in-a-Matrix/Readme.md b/DFS/329.Longest-Increasing-Path-in-a-Matrix/Readme.md index 468814add..d0a7d26b8 100644 --- a/DFS/329.Longest-Increasing-Path-in-a-Matrix/Readme.md +++ b/DFS/329.Longest-Increasing-Path-in-a-Matrix/Readme.md @@ -1,3 +1,5 @@ ### 329.Longest-Increasing-Path-in-a-Matrix 我们从任意点A开始递归寻找各条递增路径,最终返回的时候记录从A为起点时的最长路径长度。将此结果记忆化,这样当对其他点进行DFS的时候,如果递归调用到dfs(A)就直接返回结果。 + +此题和[2328.Number-of-Increasing-Paths-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2328.Number-of-Increasing-Paths-in-a-Grid)非常类似。 From 3fc27bfa71b22f27e52698fb84b10cbcee7aee3e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 01:31:51 -0700 Subject: [PATCH 0995/2729] Create Readme.md --- DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md diff --git a/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md new file mode 100644 index 000000000..3fcba490d --- /dev/null +++ b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md @@ -0,0 +1,4 @@ +### 2328.Number-of-Increasing-Paths-in-a-Grid + + +此题和[329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix)非常类似。 From a2a26607821b6ada6a3fe97514b0cc925855e9b5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 09:05:30 -0700 Subject: [PATCH 0996/2729] Update Readme.md --- DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md index 3fcba490d..6d7f85b3e 100644 --- a/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md +++ b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/Readme.md @@ -1,4 +1,12 @@ ### 2328.Number-of-Increasing-Paths-in-a-Grid +#### 解法1:动态规划 +考虑到所有元素的数目只有1e5,那么我们可以将其按照从小到大排序。然后依次访问这些元素(i,j),查看它四周的格子(x,y)是否有比它小的。是的话,就有```dp[i][j]+=dp[x][y]```,其中dp[i][j]表示以其为结尾的、符合条件的严格递增序列的数目。特别注意,(i,j)本身也可以是一个单元素的序列,所以dp[i][j]要加上1. + +最终的答案是将所有dp[i][j]加起来。因为符合条件的严格递增序列可以以任何位置结尾。 + +#### 解法2:DFS +事实上本题不需要排序。我们只需要DFS和记忆化搜索。我们令dfs(i,j)表示以(i,j)为起点的递增序列的个数。我们可以从任意一个位置(i,j)出发,寻找四周比其大的格子(x,y),然后递归调用dfs(x,y),将其结果再加在dfs(i,j)上即可。本题需要记忆化dfs的结果来避免重复调用。 + 此题和[329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix)非常类似。 From 3ff02881eebab34b5e1e98981d8dc04170885e49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 09:07:26 -0700 Subject: [PATCH 0997/2729] Create 2328.Number-of-Increasing-Paths-in-a-Grid_v1.cpp --- ...umber-of-Increasing-Paths-in-a-Grid_v1.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid_v1.cpp diff --git a/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid_v1.cpp b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid_v1.cpp new file mode 100644 index 000000000..42e676a60 --- /dev/null +++ b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid_v1.cpp @@ -0,0 +1,39 @@ +using AI3 = array; +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int countPaths(vector>& grid) + { + vectorarray; + int m = grid.size(), n = grid[0].size(); + for (int i=0; i>dp(m, vector(n, 0)); + vector>dir = {{1,0},{-1,0},{0,1},{0,-1}}; + + LL ret = 0; + for (auto& [v, i, j]: array) + { + LL sum = 0; + for (int k=0; k<4; k++) + { + int x = i+dir[k].first; + int y = j+dir[k].second; + if (x<0||x>=m||y<0||y>=n) continue; + if (grid[x][y] >= grid[i][j]) continue; + sum = (sum + dp[x][y]) % M; + } + sum = (sum + 1) % M; + dp[i][j] = sum; + ret = (ret + sum) % M; + } + + return ret; + + } +}; From 5a6ffb84ff43773ed7b2f64442a6e4703687c28e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 09:07:58 -0700 Subject: [PATCH 0998/2729] Rename 2328.Number-of-Increasing-Paths-in-a-Grid.cpp to 2328.Number-of-Increasing-Paths-in-a-Grid_v2.cpp --- ...-Grid.cpp => 2328.Number-of-Increasing-Paths-in-a-Grid_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DFS/2328.Number-of-Increasing-Paths-in-a-Grid/{2328.Number-of-Increasing-Paths-in-a-Grid.cpp => 2328.Number-of-Increasing-Paths-in-a-Grid_v2.cpp} (100%) diff --git a/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid.cpp b/DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid_v2.cpp similarity index 100% rename from DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid.cpp rename to DFS/2328.Number-of-Increasing-Paths-in-a-Grid/2328.Number-of-Increasing-Paths-in-a-Grid_v2.cpp From 9308eee6aa89f4a1d5707466a3e895788ae5eab9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 19:08:45 -0700 Subject: [PATCH 0999/2729] Create 1504.Count-Submatrices-With-All-Ones.cpp --- .../1504.Count-Submatrices-With-All-Ones.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp new file mode 100644 index 000000000..00c5f3f93 --- /dev/null +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int numSubmat(vector>& mat) + { + int M=mat.size(); + if (M==0) return 0; + int N=mat[0].size(); + int ret = 0; + for (int i=0; i(N,0); + for (int k=i; k Date: Sun, 3 Jul 2022 19:09:25 -0700 Subject: [PATCH 1000/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 05cb2e4ba..7e8763ab4 100644 --- a/Readme.md +++ b/Readme.md @@ -1078,6 +1078,7 @@ [1253.Reconstruct-a-2-Row-Binary-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1253.Reconstruct-a-2-Row-Binary-Matrix) (M) [1354.Construct-Target-Array-With-Multiple-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1354.Construct-Target-Array-With-Multiple-Sums) (H-) [1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K) (M+) +[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1504.Count-Submatrices-With-All-Ones) (M) [1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits) (H) [1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1535.Find-the-Winner-of-an-Array-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1535.Find-the-Winner-of-an-Array-Game) (M+) From 358204cf513a6115dbdf83f18df4382548455e12 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 19:20:37 -0700 Subject: [PATCH 1001/2729] Create Readme.md --- Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md b/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md new file mode 100644 index 000000000..a51cd9fd9 --- /dev/null +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md @@ -0,0 +1,7 @@ +### 1504.Count-Submatrices-With-All-Ones + +此题的数据量非常小,o(MMN)即可解决。 + +和84、85相同的技巧,我们用两重循环遍历submatric的上边界和下边界(比如第i行和第k行,即高度是```h=k-i+1```),再横向扫一遍,得到这两个行边界之间的每一列的histogram(即以第k行为底,往上有多少个连续的1). 如果我们发现histogram数列里连续任意L列的高度都是h,那么说明就有```(1+L)*L/2```个高度为h的submatric其元素都是1(通过随意设置起点和终点). + +这样我们就不重不漏地遍历了所有不同高度位置、不同宽度位置的全1矩阵。 From b36f426f8ee6bbe6d2e4d3e1a6e4988e4fc2ea3a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 19:22:32 -0700 Subject: [PATCH 1002/2729] Update Readme.md --- Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md b/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md index a51cd9fd9..708818d87 100644 --- a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md @@ -2,6 +2,6 @@ 此题的数据量非常小,o(MMN)即可解决。 -和84、85相同的技巧,我们用两重循环遍历submatric的上边界和下边界(比如第i行和第k行,即高度是```h=k-i+1```),再横向扫一遍,得到这两个行边界之间的每一列的histogram(即以第k行为底,往上有多少个连续的1). 如果我们发现histogram数列里连续任意L列的高度都是h,那么说明就有```(1+L)*L/2```个高度为h的submatric其元素都是1(通过随意设置起点和终点). +和84、85相同的技巧,我们用两重循环遍历submatric的上边界和下边界(比如第i行和第k行,即高度是```h=k-i+1```),再横向扫一遍,得到这两个行边界之间的每一列的histogram(即以第k行为底,往上有多少个连续的1). 如果我们发现histogram数列里连续任意L列的高度都是h,那么说明就有```(1+L)*L/2```个高度为h的submatric其元素都是1(通过随意设置左端点和右端点). 这样我们就不重不漏地遍历了所有不同高度位置、不同宽度位置的全1矩阵。 From ae3f4c8028b4325dbb7b7e27927c04a8bf20c6bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Jul 2022 23:13:54 -0700 Subject: [PATCH 1003/2729] Create 2327.Number-of-People-Aware-of-a-Secret.cpp --- ...327.Number-of-People-Aware-of-a-Secret.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret.cpp diff --git a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret.cpp b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret.cpp new file mode 100644 index 000000000..941474900 --- /dev/null +++ b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret.cpp @@ -0,0 +1,28 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[1005]; +public: + int peopleAwareOfSecret(int n, int delay, int forget) + { + dp[1] = 1; + for (int i=1; i<=n; i++) + { + for (int j=i+delay; jn) break; + dp[j] += dp[i]; + dp[j] %= M; + } + } + + LL ret = 0; + for (int i=1; i<=n; i++) + { + if (i+forget>n) + ret = (ret + dp[i]) % M; + } + + return ret; + } +}; From 3a005fa9a7c689dc06175f99c2fb17d68480072d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 00:11:32 -0700 Subject: [PATCH 1004/2729] Create 2327.Number-of-People-Aware-of-a-Secret_v1.cpp --- ....Number-of-People-Aware-of-a-Secret_v1.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v1.cpp diff --git a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v1.cpp b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v1.cpp new file mode 100644 index 000000000..dde5149ad --- /dev/null +++ b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v1.cpp @@ -0,0 +1,27 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int peopleAwareOfSecret(int n, int delay, int forget) + { + vectoractive(n+1); + + active[1] = 1; + + LL ret = 0; + for (int i=1; i<=n; i++) + { + for (int j=i+delay; jn) break; + active[j] += active[i]; + active[j] %= M; + } + } + + for (int i=1; i<=n; i++) + if (i+delay > n) + ret = (ret + active[i]) % M; + return (ret + active[n]) % M; + } +}; From 74afc3e9b87bdd3f93457499fdb1f5c955be6439 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 00:15:50 -0700 Subject: [PATCH 1005/2729] Update and rename 2327.Number-of-People-Aware-of-a-Secret.cpp to 2327.Number-of-People-Aware-of-a-Secret_v2.cpp --- ...327.Number-of-People-Aware-of-a-Secret.cpp | 28 ---------------- ....Number-of-People-Aware-of-a-Secret_v2.cpp | 32 +++++++++++++++++++ 2 files changed, 32 insertions(+), 28 deletions(-) delete mode 100644 Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret.cpp create mode 100644 Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v2.cpp diff --git a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret.cpp b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret.cpp deleted file mode 100644 index 941474900..000000000 --- a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret.cpp +++ /dev/null @@ -1,28 +0,0 @@ -using LL = long long; -LL M = 1e9+7; -class Solution { - LL dp[1005]; -public: - int peopleAwareOfSecret(int n, int delay, int forget) - { - dp[1] = 1; - for (int i=1; i<=n; i++) - { - for (int j=i+delay; jn) break; - dp[j] += dp[i]; - dp[j] %= M; - } - } - - LL ret = 0; - for (int i=1; i<=n; i++) - { - if (i+forget>n) - ret = (ret + dp[i]) % M; - } - - return ret; - } -}; diff --git a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v2.cpp b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v2.cpp new file mode 100644 index 000000000..6b19e4a27 --- /dev/null +++ b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v2.cpp @@ -0,0 +1,32 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int peopleAwareOfSecret(int n, int delay, int forget) + { + vectordiff(n+1); + vectoractive(n+1); + + LL ret = 0; + + if (1+delay <= n) + diff[1+delay] += 1; + if (1+forget <= n) + diff[1+forget] -= 1; + + for (int i=2; i<=n; i++) + { + active[i] = (active[i-1] + diff[i]) % M; + + if (i+delay <= n) + diff[i+delay] = (diff[i+delay] + active[i]) % M; + if (i+forget <= n) + diff[i+forget] = (diff[i+forget] - active[i] + M) % M; + } + + for (int i=1; i<=n; i++) + if (i+delay > n) + ret = (ret + active[i]) % M; + return (ret + active[n]) % M; + } +}; From ed258a4195dd4f5925607f3b635c5ceddcffea82 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 00:16:34 -0700 Subject: [PATCH 1006/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7e8763ab4..6aa57b99b 100644 --- a/Readme.md +++ b/Readme.md @@ -1268,6 +1268,7 @@ [2158.Amount-of-New-Area-Painted-Each-Day](https://github.com/wisdompeak/LeetCode/tree/master/Others/2158.Amount-of-New-Area-Painted-Each-Day) (H-) [2237.Count-Positions-on-Street-With-Required-Brightness](https://github.com/wisdompeak/LeetCode/tree/master/Others/2237.Count-Positions-on-Street-With-Required-Brightness) (M) [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) +[2327.Number-of-People-Aware-of-a-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Others/2327.Number-of-People-Aware-of-a-Secret) (H-) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From fdeffe4819d213022fb23ea1b47a19222eec258d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 08:33:35 -0700 Subject: [PATCH 1007/2729] Update 2327.Number-of-People-Aware-of-a-Secret_v1.cpp --- .../2327.Number-of-People-Aware-of-a-Secret_v1.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v1.cpp b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v1.cpp index dde5149ad..53457cb0b 100644 --- a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v1.cpp +++ b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v1.cpp @@ -4,9 +4,9 @@ class Solution { public: int peopleAwareOfSecret(int n, int delay, int forget) { - vectoractive(n+1); + vectordp(n+1); // dp[i]: # of new persons who know the news in the i-th day - active[1] = 1; + dp[1] = 1; LL ret = 0; for (int i=1; i<=n; i++) @@ -14,14 +14,14 @@ class Solution { for (int j=i+delay; jn) break; - active[j] += active[i]; - active[j] %= M; + dp[j] += dp[i]; + dp[j] %= M; } } for (int i=1; i<=n; i++) - if (i+delay > n) - ret = (ret + active[i]) % M; - return (ret + active[n]) % M; + if (i+forget > n) + ret = (ret + dp[i]) % M; + return ret; } }; From 2057ea7af4a7729aba03fc4538683b218bd2740b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 08:44:40 -0700 Subject: [PATCH 1008/2729] Update 2327.Number-of-People-Aware-of-a-Secret_v2.cpp --- ....Number-of-People-Aware-of-a-Secret_v2.cpp | 30 +++++++++---------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v2.cpp b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v2.cpp index 6b19e4a27..1af588b92 100644 --- a/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v2.cpp +++ b/Others/2327.Number-of-People-Aware-of-a-Secret/2327.Number-of-People-Aware-of-a-Secret_v2.cpp @@ -3,30 +3,28 @@ LL M = 1e9+7; class Solution { public: int peopleAwareOfSecret(int n, int delay, int forget) - { + { + vectordp(n+1); // dp[i]: # of new persons who know the news in the i-th day vectordiff(n+1); - vectoractive(n+1); - LL ret = 0; + dp[1] = 1; + diff[1] += 1; + diff[2] += -1; - if (1+delay <= n) - diff[1+delay] += 1; - if (1+forget <= n) - diff[1+forget] -= 1; - - for (int i=2; i<=n; i++) + LL ret = 0; + for (int i=1; i<=n; i++) { - active[i] = (active[i-1] + diff[i]) % M; - + dp[i] = (dp[i-1] + diff[i] + M) % M; + if (i+delay <= n) - diff[i+delay] = (diff[i+delay] + active[i]) % M; + diff[i+delay] += dp[i]; if (i+forget <= n) - diff[i+forget] = (diff[i+forget] - active[i] + M) % M; + diff[i+forget] -= dp[i]; } for (int i=1; i<=n; i++) - if (i+delay > n) - ret = (ret + active[i]) % M; - return (ret + active[n]) % M; + if (i+forget > n) + ret = (ret + dp[i]) % M; + return ret; } }; From e91a601b6679c6358093a80d2b4bcd462261bdf7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 09:26:07 -0700 Subject: [PATCH 1009/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Others/2327.Number-of-People-Aware-of-a-Secret/Readme.md diff --git a/Others/2327.Number-of-People-Aware-of-a-Secret/Readme.md b/Others/2327.Number-of-People-Aware-of-a-Secret/Readme.md new file mode 100644 index 000000000..a6900b45b --- /dev/null +++ b/Others/2327.Number-of-People-Aware-of-a-Secret/Readme.md @@ -0,0 +1,21 @@ +### 2327.Number-of-People-Aware-of-a-Secret + +#### 解法1:N^2 DP +本题显然是一个DP,那么如何设计状态变量呢?如果dp[i]表示第i天的时候有多少人被感染,那么情况就比较复杂,因为有些人是刚被感染的(是被第i-delay天刚被感染的人传染的),有些人是已经感染了一段时间的,这两部分如何区分?此外,还要考虑到第i天可能有一部分人刚好恢复健康,那部分人对应的是第```i-forget```天刚被感染的人。 + +所以由上面的分析,在每一天中,“刚被感染”的人数是一个非常有用的信息量。所以我们应该将其单独定义。所以不妨令dp[i]表示第i天刚被感染的人。那么根据题意,在第i+delay直至i+forget-1天,每天新感染的人数都会固定增加dp[i],即 +```cpp +for (int j=i+delay; jn,那么dp[i]就可以贡献给ret。 + +#### 解法2: 差分数组 +从上面的dp转移方程可以看出,在一个区间内赋值同一个值,用for循环显然是低效率的,我们必然会引入差分数组。定义diff[i]表示dp[i]相比于dp[i-1]之间的增量,即```dp[i]=dp[i-1]+diff[i]```。于是我们可以用两处增量的定义,来替换整个for循环 +``` +diff[i+delay] += dp[i]; +diff[i+forget] -= dp[i]; +``` +这里需要特别注意diff的初始条件。将解法1里```dp[1]=1```翻译过来,所对应的diff的初始条件是```diff[1]+=1, diff[2]+=-1```. From 1001150c6e750ebc3a79a29344a6530b5587e1ab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 11:46:05 -0700 Subject: [PATCH 1010/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 6aa57b99b..25ac8dd53 100644 --- a/Readme.md +++ b/Readme.md @@ -29,7 +29,7 @@ [1580.Put-Boxes-Into-the-Warehouse-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1580.Put-Boxes-Into-the-Warehouse-II) (H-) [1687.Delivering-Boxes-from-Storage-to-Ports](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1687.Delivering-Boxes-from-Storage-to-Ports) (H) [1793.Maximum-Score-of-a-Good-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1793.Maximum-Score-of-a-Good-Subarray) (M+) -[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make/Readme.md](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) +[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag) (M+) * ``Sliding window`` [532.K-diff-Pairs-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/532.K-diff-Pairs-in-an-Array) (H-) From cb50adb26adabf472338e013b0eb6ec83549ca4e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 22:33:36 -0700 Subject: [PATCH 1011/2729] Create 2242.Maximum-Score-of-a-Node-Sequence.cpp --- .../2242.Maximum-Score-of-a-Node-Sequence.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/2242.Maximum-Score-of-a-Node-Sequence/2242.Maximum-Score-of-a-Node-Sequence.cpp diff --git a/Greedy/2242.Maximum-Score-of-a-Node-Sequence/2242.Maximum-Score-of-a-Node-Sequence.cpp b/Greedy/2242.Maximum-Score-of-a-Node-Sequence/2242.Maximum-Score-of-a-Node-Sequence.cpp new file mode 100644 index 000000000..e8960fbb2 --- /dev/null +++ b/Greedy/2242.Maximum-Score-of-a-Node-Sequence/2242.Maximum-Score-of-a-Node-Sequence.cpp @@ -0,0 +1,37 @@ +class Solution { + vector> nxt[50000]; +public: + int maximumScore(vector& scores, vector>& edges) + { + int n = scores.size(); + for (auto edge: edges) + { + int a= edge[0], b=edge[1]; + nxt[a].push_back({scores[b],b}); + nxt[b].push_back({scores[a],a}); + } + for (int i=0; i 3) + nxt[i].resize(3); + } + + int ret = -1; + + for (auto edge: edges) + { + int a= edge[0], b=edge[1]; + for (auto& [_, i] : nxt[a]) + for (auto & [_, j] : nxt[b]) + { + if (i==j) continue; + if (i==b || j==a) continue; + ret = max(ret, scores[i]+scores[a]+scores[b]+scores[j]); + break; + } + } + + return ret; + } +}; From f87f0ddc0ce7f3fd759b0b47246249654b67765f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 22:44:12 -0700 Subject: [PATCH 1012/2729] Create Readme.md --- Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md diff --git a/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md b/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md new file mode 100644 index 000000000..7c35a5b11 --- /dev/null +++ b/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md @@ -0,0 +1,7 @@ +### 2242.Maximum-Score-of-a-Node-Sequence + +因为题目需要找的序列只有四个节点、三条边,所以我们可以通过穷举中间的边,来暴力枚举所有的节点组合。 + +比如,如果我们考察以(a,b)为中间的边,那么我们接下来就要找a的一个邻接节点i,b的一个邻接节点j,组成i-a-b-j的序列。为了使得节点的score总和最大,原则上贪心地找a的最大邻居、b的最大邻居。但是容易想到会有一些特殊情况,比如a的最大邻居恰好是b或者j的话,我们就无法保证这个序列的四个节点是互异的。同理,b的最大邻居也有这样的问题。 + +那么我们是否该枚举所有a的邻居与b的邻居的组合,考察所有可能的{i,j}再取最大值吗?其实不必。根据之前的分析,我们只需要考察a的最大的三个邻居即可,这样就一定能找到一个不与b和j重复的。同理,我们也只保留b的最大的三个邻居。这样,最多9组配对,必然可以找到一组互异的i-a-b-j,我们取其中的最大值即可。 From 536b12a79347180f374661766afc36144fc26356 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 22:44:36 -0700 Subject: [PATCH 1013/2729] Update Readme.md --- Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md b/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md index 7c35a5b11..100ce0872 100644 --- a/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md +++ b/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md @@ -5,3 +5,5 @@ 比如,如果我们考察以(a,b)为中间的边,那么我们接下来就要找a的一个邻接节点i,b的一个邻接节点j,组成i-a-b-j的序列。为了使得节点的score总和最大,原则上贪心地找a的最大邻居、b的最大邻居。但是容易想到会有一些特殊情况,比如a的最大邻居恰好是b或者j的话,我们就无法保证这个序列的四个节点是互异的。同理,b的最大邻居也有这样的问题。 那么我们是否该枚举所有a的邻居与b的邻居的组合,考察所有可能的{i,j}再取最大值吗?其实不必。根据之前的分析,我们只需要考察a的最大的三个邻居即可,这样就一定能找到一个不与b和j重复的。同理,我们也只保留b的最大的三个邻居。这样,最多9组配对,必然可以找到一组互异的i-a-b-j,我们取其中的最大值即可。 + +本题的时间复杂度就是```o(9*E)``` From 995a7b591d5ea47e786da45417eafeb12644a585 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 22:45:11 -0700 Subject: [PATCH 1014/2729] Update Readme.md --- Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md b/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md index 100ce0872..8b68f67a4 100644 --- a/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md +++ b/Greedy/2242.Maximum-Score-of-a-Node-Sequence/Readme.md @@ -6,4 +6,4 @@ 那么我们是否该枚举所有a的邻居与b的邻居的组合,考察所有可能的{i,j}再取最大值吗?其实不必。根据之前的分析,我们只需要考察a的最大的三个邻居即可,这样就一定能找到一个不与b和j重复的。同理,我们也只保留b的最大的三个邻居。这样,最多9组配对,必然可以找到一组互异的i-a-b-j,我们取其中的最大值即可。 -本题的时间复杂度就是```o(9*E)``` +本题的时间复杂度就是```o(ElogE + 9*E)``` From 0a2e35f62dc8b61b5c7c59b97c3538c4575b0e63 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Jul 2022 22:50:08 -0700 Subject: [PATCH 1015/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 25ac8dd53..f0af325d7 100644 --- a/Readme.md +++ b/Readme.md @@ -1105,6 +1105,7 @@ [2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) +[2242.Maximum-Score-of-a-Node-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2242.Maximum-Score-of-a-Node-Sequence) (M+) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) From 74953dce19674c1a3af2fca2afd5f4f63d84920f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Jul 2022 12:02:28 -0700 Subject: [PATCH 1016/2729] Create 2277.Closest-Node-to-Path-in-Tree.cpp --- .../2277.Closest-Node-to-Path-in-Tree.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp diff --git a/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp b/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp new file mode 100644 index 000000000..e9b49915f --- /dev/null +++ b/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp @@ -0,0 +1,60 @@ +class Solution { + vector nxt[1005]; + int matrix[1005][1005]; +public: + vector closestNode(int n, vector>& edges, vector>& query) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + nxt[a].push_back(b); + nxt[b].push_back(a); + } + + for (int i=0; irets; + for (auto& q: query) + { + int start = q[0], end = q[1], node = q[2]; + int dist = INT_MAX; + int ret; + solve(start, end, node, dist, ret); + rets.push_back(ret); + } + return rets; + } + + void dfs(int start, int cur, int dist) + { + for (int j: nxt[cur]) + { + if (j!=start && matrix[start][j]==0) + { + matrix[start][j] = dist+1; + dfs(start, j, dist+1); + } + } + } + + void solve(int cur, int end, int node, int & dist, int& ret) + { + if (matrix[cur][node] < dist) + { + dist = matrix[cur][node]; + ret = cur; + } + + for (int j: nxt[cur]) + { + if (matrix[cur][end]==matrix[j][end]+1) + { + solve(j, end, node, dist, ret); + break; + } + } + } + + +}; From 0d2f84f059aaf68fc79042b455bda6a5e79dc207 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Jul 2022 12:03:07 -0700 Subject: [PATCH 1017/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f0af325d7..d9fdb2333 100644 --- a/Readme.md +++ b/Readme.md @@ -232,6 +232,7 @@ [1666.Change-the-Root-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1666.Change-the-Root-of-a-Binary-Tree) (H-) [1932.Merge-BSTs-to-Create-Single-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1932.Merge-BSTs-to-Create-Single-BST) (H) [2003.Smallest-Missing-Genetic-Value-in-Each-Subtree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2003.Smallest-Missing-Genetic-Value-in-Each-Subtree) (H) +[2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H-) [2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) From fc7f4a0fff6b6db12b9b39ca100f0b518aa141ca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Jul 2022 12:15:09 -0700 Subject: [PATCH 1018/2729] Create Readme.md --- Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md diff --git a/Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md b/Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md new file mode 100644 index 000000000..706a92508 --- /dev/null +++ b/Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md @@ -0,0 +1,5 @@ +### 2277.Closest-Node-to-Path-in-Tree + +本题的时间复杂度要求是o(N^2),所以常规解法是,从node开始dfs得到所有节点到node的距离dist2node。然后从start开始dfs整棵树,对于能够通往end的这个分支上的节点,取最小的dist2node。 + +本题还有一种比较精彩的解法。先遍历所有的点作为起点,dfs整棵树,这样得到全局的matrix[i][j]表示任意两点之间的距离。然后对于start,我们遍历它的邻居j,发现如果有```matrix[start][end]==matrix[j][end]+1```,说明j是位于从start到end的路径上。依次递归下去,就能直接从start走向end,沿途中取最小的matrix[j][node]. From 1b446640e33cbfdd478a4973f4bdc3c9654d8bf2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Jul 2022 13:07:59 -0700 Subject: [PATCH 1019/2729] Create 2313.Minimum-Flips-in-Binary-Tree-to-Get-Result.cpp --- ...mum-Flips-in-Binary-Tree-to-Get-Result.cpp | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result.cpp diff --git a/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result.cpp b/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result.cpp new file mode 100644 index 000000000..45618a38c --- /dev/null +++ b/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result.cpp @@ -0,0 +1,86 @@ +/** + * 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 { + unordered_map>dp; +public: + int minimumFlips(TreeNode* root, bool result) + { + return dfs(root,result); + } + + int dfs(TreeNode* node, int expected) + { + if (!node->left && !node->right) + { + return node->val != expected; + } + + if (dp.find(node)!=dp.end() && dp[node].find(expected)!=dp[node].end()) + return dp[node][expected]; + + int ans = INT_MAX/2; + if (node->val == 2) + { + if (expected == 1) + { + ans = min(ans, dfs(node->left, 1)); + ans = min(ans, dfs(node->right, 1)); + } + else if (expected == 0) + { + ans = min(ans, dfs(node->left, 0) + dfs(node->right, 0)); + } + } + else if (node->val == 3) + { + if (expected == 1) + { + ans = min(ans, dfs(node->left, 1) + dfs(node->right, 1)); + } + else if (expected == 0) + { + ans = min(ans, dfs(node->left, 0)); + ans = min(ans, dfs(node->right, 0)); + } + } + else if (node->val == 4) + { + if (expected == 1) + { + ans = min(ans, dfs(node->left, 0) + dfs(node->right, 1)); + ans = min(ans, dfs(node->left, 1) + dfs(node->right, 0)); + } + else if (expected == 0) + { + ans = min(ans, dfs(node->left, 0) + dfs(node->right, 0)); + ans = min(ans, dfs(node->left, 1) + dfs(node->right, 1)); + } + } + else + { + TreeNode* child = node->left ? node->left : node->right; + if (expected == 1) + { + ans = min(ans, dfs(child, 0)); + } + else if (expected == 0) + { + ans = min(ans, dfs(child, 1)); + } + } + + dp[node][expected] = ans; + return ans; + } + + +}; From 8596a281bcec614c5580c338f926a568e78820b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Jul 2022 13:09:03 -0700 Subject: [PATCH 1020/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d9fdb2333..83cac9910 100644 --- a/Readme.md +++ b/Readme.md @@ -233,6 +233,7 @@ [1932.Merge-BSTs-to-Create-Single-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1932.Merge-BSTs-to-Create-Single-BST) (H) [2003.Smallest-Missing-Genetic-Value-in-Each-Subtree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2003.Smallest-Missing-Genetic-Value-in-Each-Subtree) (H) [2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H-) +[2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) [2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) From 2ef632f451670b6d121d3b7891904f5589658266 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Jul 2022 13:21:11 -0700 Subject: [PATCH 1021/2729] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result/Readme.md diff --git a/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result/Readme.md b/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result/Readme.md new file mode 100644 index 000000000..bec4b1138 --- /dev/null +++ b/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result/Readme.md @@ -0,0 +1,14 @@ +### 2313.Minimum-Flips-in-Binary-Tree-to-Get-Result + +本题只要想到用tree dp来做,一切就迎刃而解。我们定义```dfs(node, expected)```表示为使得子树eval(node)的结果等于expected,所需要所做的最小修改。然后我们根据node的运算符和expcted的数值,分情况讨论: +1. 如果node是OR,且expcted是true,那么只要返回```dfs(node->left, 1)```或者```dfs(node->right, 1)```中的较小值. +2. 如果node是OR,且expcted是false,那么需要递归```dfs(node->left, 0)+dfs(node->right, 0)```. +3. 如果node是AND,且expcted是true,那么需要递归```dfs(node->left, 1)+dfs(node->right, 1)```. +4. 如果node是AND,且expcted是false,那么只要返回```dfs(node->left, 0)```或者```dfs(node->right, 0)```中的较小值. +5. 如果node是XOR,且expcted是true,那么只要返回```dfs(node->left, 0)+dfs(node->right, 1)```或者```dfs(node->left, 1)+dfs(node->right, 0)```中的较小值. +6. 如果node是XOR,且expcted是false,那么只要返回```dfs(node->left, 0)+dfs(node->right, 0)```或者```dfs(node->left, 1)+dfs(node->right, 1)```中的较小值. +7. 如果node是NOT,且expcted是true,那么需要递归```dfs(child, 0)```,其中child是node的唯一子树(左子树或者右子树) +8. 如果node是NOT,且expcted是false,那么需要递归```dfs(child, 1)``` +9. 如果node是叶子节点,那么只需要返回```node->val != expected``` + +记得所有的结果需要记忆化,加快访问。 From db0bd4df26d1db50b753520713826704927bf96e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Jul 2022 23:36:57 -0700 Subject: [PATCH 1022/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/1608.Special-Array-With-X-Elements-Greater-Than-or-Equal-X/Readme.md b/Binary_Search/1608.Special-Array-With-X-Elements-Greater-Than-or-Equal-X/Readme.md index ef6facc01..06e76f214 100644 --- a/Binary_Search/1608.Special-Array-With-X-Elements-Greater-Than-or-Equal-X/Readme.md +++ b/Binary_Search/1608.Special-Array-With-X-Elements-Greater-Than-or-Equal-X/Readme.md @@ -9,7 +9,7 @@ 这样的时间复杂度就是 ```log(N)*N```. -对于有唯一确定解的题目(注意不是有唯一最优解),除了可以沿用我一贯推荐的```while(left<=right)```模板之外,我们可以用这样的模板: +对于有唯一确定解的题目(注意不是有唯一最优解),除了可以沿用我一贯推荐的```while(left Date: Thu, 7 Jul 2022 22:42:50 -0700 Subject: [PATCH 1023/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 83cac9910..a740406ae 100644 --- a/Readme.md +++ b/Readme.md @@ -809,6 +809,7 @@ [1738.Find-Kth-Largest-XOR-Coordinate-Value](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1738.Find-Kth-Largest-XOR-Coordinate-Value) (M+) [1835.Find-XOR-Sum-of-All-Pairs-Bitwise-AND](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1835.Find-XOR-Sum-of-All-Pairs-Bitwise-AND) (M) * ``Bit Mask`` +[320.Generalized-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/320.Generalized-Abbreviation) (M) [1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters) (M+) [1284.Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1284.Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix) (M+) [1452.People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1452.People-Whose-List-of-Favorite-Companies-Is-Not-a-Subset-of-Another-List) (H-) @@ -846,7 +847,6 @@ [1754.Largest-Merge-Of-Two-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/1754.Largest-Merge-Of-Two-Strings) (M+) [1849.Splitting-a-String-Into-Descending-Consecutive-Values](https://github.com/wisdompeak/LeetCode/tree/master/String/1849.Splitting-a-String-Into-Descending-Consecutive-Values) (M+) * ``Abbreviation`` -[320.Generalized-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/320.Generalized-Abbreviation) (M) [408.Valid-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/408.Valid-Word-Abbreviation) (M) [411.Minimum-Unique-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/411.Minimum-Unique-Word-Abbreviation) (H) [2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings) (H) From 52899e7e054442f986273e98446733639473709f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Jul 2022 18:40:41 -0700 Subject: [PATCH 1024/2729] Create 2263.Make-Array-Non-decreasing-or-Non-increasing.cpp --- ...Array-Non-decreasing-or-Non-increasing.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing/2263.Make-Array-Non-decreasing-or-Non-increasing.cpp diff --git a/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing/2263.Make-Array-Non-decreasing-or-Non-increasing.cpp b/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing/2263.Make-Array-Non-decreasing-or-Non-increasing.cpp new file mode 100644 index 000000000..0a5748969 --- /dev/null +++ b/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing/2263.Make-Array-Non-decreasing-or-Non-increasing.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int convertArray(vector& nums) { + int ret = solve(nums); + reverse(nums.begin(),nums.end()); + ret = min(ret, solve(nums)); + return ret; + } + + int solve(vector& nums) { + int res = 0; + priority_queue que; + for(auto num: nums) { + if(!que.empty() && que.top()>num) { + res += que.top() - num; + que.pop(); + que.push(num); + } + que.push(num); + } + return res; + } +}; From 04920caaf075d136a24a6bda535b7174dcbf78c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Jul 2022 18:41:23 -0700 Subject: [PATCH 1025/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a740406ae..ada57f8d3 100644 --- a/Readme.md +++ b/Readme.md @@ -1109,6 +1109,7 @@ [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2242.Maximum-Score-of-a-Node-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2242.Maximum-Score-of-a-Node-Sequence) (M+) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) +[2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) [2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) From 7c631bfcbc43dbb29b802e09add07806a5809058 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Jul 2022 23:03:09 -0700 Subject: [PATCH 1026/2729] Create Readme.md --- .../Readme.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing/Readme.md diff --git a/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing/Readme.md b/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing/Readme.md new file mode 100644 index 000000000..40827c503 --- /dev/null +++ b/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing/Readme.md @@ -0,0 +1,27 @@ +### 2263.Make-Array-Non-decreasing-or-Non-increasing + +此题有nlogn的贪心解法,但理解起来比较有难度。我们通过例子来解释。我们先考虑如何实现一个非递减序列。 + +假设数组前三个元素已经是```2,6,8```,那么我们必须不需要任何操作。 + +如果第四个元素是5,那么我们要让最后两个元素“非递减”,无论如何至少要消耗三次操作。比如将第四个元素升为8。此外还有其他的操作,比如将最后两个元素都变成6,将最后两个元素都变成7,等等。这些操作的代价都相同,即都是3. 在这里,为了在后续更容易地构造“非递减”序列,我们这就保守地将第三和第四个元素都变成5(同样花费3个代价)。此时我们将序列写作 +``` +idx 1, 2, (3, 4) +val 2, 6, 5 +``` +注意,这里我们将第三个元素和第四个元素“捆绑”在一起,让它们今后“共进退”,也就是永远取相同的值,这样能够让后面的元素更容易地“递增”地接上去。 + +此时会说,这样的序列并不是“非递减”的呀。没关系,之前我们分析过(3,4)这两个元素,我们可以让它们都是5,也可以让它们都是6,也可以让它们都是7或者8,这些方案都不改变之前付出的代价3,我们称之为“弹性范围”. 我们现在只是标注了弹性范围的下限,而它们其实可以在不增加消耗地前提下,匹配它们前面的任意元素的值,比如说6,就可以与第二个元素相接了成为“非递增”了. 事实上,无论如何,(3,4)这两个元素一定可以“无代价”地与之前的元素成功相接:这是因为(3,4)两个元素弹性变化范围的上限是8,而8是之前序列里的最大元素,6只不过是次大元素,所以定会在(3,4)两个元素的弹性变化范围内。 + +我们继续这个例子,假如第五个元素是4。此时数组里的最大元素是第二个的6,所以我们必然想把4提升到6,或者把6降到4. 所以我们至少需要2个代价。换而言之,我们用2个代价,可以将(2,5)这两个元素在4,5,6之间弹性变化。我们记做 +``` +idx 1, (3, 4), (2, 5) +val 2, 5, 4 +``` +同样,我们虽然标记了4,但是因为(2,5)这两个元素的弹性范围是4~6,它必然可以在需要的时候与之前的(3,4)匹配(因为5是之前的次大值,小于6)。所以至此,我们用了3+2=5个必须付出的代价,但理论上可以保证前5个元素一定可以调整为“非递减”序列。 + +这里再说明一下,为什么我们总标记弹性区间的下限呢?当然是为了贪心地好让后面的元素以更小的代价接上来呀。 + +以后再遇到新的数字,步骤就与之前完全一致了。如果新元素比val数组里的所有元素都大,那么索性无代价地加入(反正以后还有机会削减)。如果新元素比val数组里的最大值小,那么我们就特意将最大值的元素与新元素“捆绑”处理(约定相同的值),并可以得到一个弹性区间(弹性区间内的代价不变)。区间的下限就是新元素的值,上限就是刚才的最大值。注意我们将捆绑后的元素放入val数组里的时候,只标记下限。此时我们一定有结论:最新捆绑的元素一定可以变换到某个数值,能与之前的元素拼接成“非递减”序列。 + +将以上的思路整理一下,程序只需要一个优先队列即可实现。 From 416a2adae511a04cebdb127214a5fe0faee563ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 11:28:47 -0700 Subject: [PATCH 1027/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ada57f8d3..de23eb34b 100644 --- a/Readme.md +++ b/Readme.md @@ -403,6 +403,7 @@ [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) +[2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) * ``Sort+PQ`` [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) @@ -1109,7 +1110,6 @@ [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2242.Maximum-Score-of-a-Node-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2242.Maximum-Score-of-a-Node-Sequence) (M+) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) -[2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) [2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) From 10717c2276ec6d9cc07014115e2e6afea61c6bc8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 11:29:42 -0700 Subject: [PATCH 1028/2729] Create 2332.The-Latest-Time-to-Catch-a-Bus.cpp --- .../2332.The-Latest-Time-to-Catch-a-Bus.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/2332.The-Latest-Time-to-Catch-a-Bus/2332.The-Latest-Time-to-Catch-a-Bus.cpp diff --git a/Greedy/2332.The-Latest-Time-to-Catch-a-Bus/2332.The-Latest-Time-to-Catch-a-Bus.cpp b/Greedy/2332.The-Latest-Time-to-Catch-a-Bus/2332.The-Latest-Time-to-Catch-a-Bus.cpp new file mode 100644 index 000000000..baf379d61 --- /dev/null +++ b/Greedy/2332.The-Latest-Time-to-Catch-a-Bus/2332.The-Latest-Time-to-Catch-a-Bus.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int latestTimeCatchTheBus(vector& buses, vector& passengers, int capacity) + { + int m = passengers.size(); + + sort(buses.begin(), buses.end()); + sort(passengers.begin(), passengers.end()); + + int j = 0; + int ret = -1; + + for (int i=0; i0) + { + cap--; + if (j>=1 && passengers[j]-1 != passengers[j-1]) + ret = passengers[j]-1; + else if (j==0) + ret = passengers[j]-1; + j++; + } + + if (cap > 0) + { + if (j>=1 && passengers[j-1]!=buses[i]) + ret = buses[i]; + else if (j==0) + ret = buses[i]; + } + } + + return ret; + } +}; From 777ac431550f5d515032531e9945dc362be2d28f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 11:31:04 -0700 Subject: [PATCH 1029/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index de23eb34b..147d12e8a 100644 --- a/Readme.md +++ b/Readme.md @@ -1114,6 +1114,7 @@ [2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) [2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) [2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K) (H-) +[2332.The-Latest-Time-to-Catch-a-Bus](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2332.The-Latest-Time-to-Catch-a-Bus) (H-) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 7e64cb1d9b45b519adc470e515ff50f86b5db7ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 11:40:50 -0700 Subject: [PATCH 1030/2729] Create Readme.md --- .../Readme.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Greedy/2332.The-Latest-Time-to-Catch-a-Bus/Readme.md diff --git a/Greedy/2332.The-Latest-Time-to-Catch-a-Bus/Readme.md b/Greedy/2332.The-Latest-Time-to-Catch-a-Bus/Readme.md new file mode 100644 index 000000000..6e3e02b8a --- /dev/null +++ b/Greedy/2332.The-Latest-Time-to-Catch-a-Bus/Readme.md @@ -0,0 +1,24 @@ +### 2332.The-Latest-Time-to-Catch-a-Bus + +我们想象,如果“我”不存在,只有已知的那些passengers,那么我们应该很容易这道哪些乘客上哪些车。而现在想做的基本方针,是看看能不能比某个乘客早一秒到达,这样就把他的位置挤占了(当然还有其他约束条件),从而搭上这班车。 + +我们先来写代码,看看当前这些passengers与车的匹配。这是一个明显的双指针 +```cpp + int j = 0; + for (int i=0; i0) + { + // passengers[j]可以乘坐buses[i] + cap--; + j++; + } + } +``` + +那么我们就考察,如果我们比passengers[j]早到一秒钟,能不能挤掉它的位置坐上buses[i]呢?显然,只要```passengers[j]-1!=passengers[j-1]```,我们就可以实现。 + +那么还有没有其他不需要挤占其他乘客的可能性呢?其实buses[i]不一定都坐满了。如果最后一个上车的乘客与班车开动的时刻之间有空隙,那么我们就直接在buses[i]时刻上车即可。 + +依据上面的算法,我们遍历每辆车,考察该车的每个乘客能否被挤占,或者是否可以卡点上车,就可以确定自己上车的时间。 From 59a4f215949620a591622f7a76437f83998c8da0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 12:24:00 -0700 Subject: [PATCH 1031/2729] Create 2333.Minimum-Sum-of-Squared-Difference.cpp --- ...2333.Minimum-Sum-of-Squared-Difference.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Greedy/2333.Minimum-Sum-of-Squared-Difference/2333.Minimum-Sum-of-Squared-Difference.cpp diff --git a/Greedy/2333.Minimum-Sum-of-Squared-Difference/2333.Minimum-Sum-of-Squared-Difference.cpp b/Greedy/2333.Minimum-Sum-of-Squared-Difference/2333.Minimum-Sum-of-Squared-Difference.cpp new file mode 100644 index 000000000..e76ba1c4e --- /dev/null +++ b/Greedy/2333.Minimum-Sum-of-Squared-Difference/2333.Minimum-Sum-of-Squared-Difference.cpp @@ -0,0 +1,51 @@ +using LL = long long; +class Solution { +public: + long long minSumSquareDiff(vector& nums1, vector& nums2, int k1, int k2) + { + vectornums; + for (int i=0; ipresum(n); + presum[0] = nums[0]; + for (int i=1; i Date: Sat, 9 Jul 2022 13:40:33 -0700 Subject: [PATCH 1032/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 147d12e8a..1936fc65d 100644 --- a/Readme.md +++ b/Readme.md @@ -1107,6 +1107,7 @@ [2193.Minimum-Number-of-Moves-to-Make-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome) (H+) [2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) +[2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) [2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2242.Maximum-Score-of-a-Node-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2242.Maximum-Score-of-a-Node-Sequence) (M+) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) From a27f96c64b8a63acd352f3cd43e825abdbfabe3f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 13:49:25 -0700 Subject: [PATCH 1033/2729] Update 2333.Minimum-Sum-of-Squared-Difference.cpp --- ...2333.Minimum-Sum-of-Squared-Difference.cpp | 45 ++++++++----------- 1 file changed, 18 insertions(+), 27 deletions(-) diff --git a/Greedy/2333.Minimum-Sum-of-Squared-Difference/2333.Minimum-Sum-of-Squared-Difference.cpp b/Greedy/2333.Minimum-Sum-of-Squared-Difference/2333.Minimum-Sum-of-Squared-Difference.cpp index e76ba1c4e..16391a0ba 100644 --- a/Greedy/2333.Minimum-Sum-of-Squared-Difference/2333.Minimum-Sum-of-Squared-Difference.cpp +++ b/Greedy/2333.Minimum-Sum-of-Squared-Difference/2333.Minimum-Sum-of-Squared-Difference.cpp @@ -8,44 +8,35 @@ class Solution { nums.push_back(abs(nums1[i]-nums2[i])); sort(nums.rbegin(), nums.rend()); - int n = nums.size(); - int cap = k1+k2; + int n = nums.size(); vectorpresum(n); presum[0] = nums[0]; for (int i=1; i Date: Sat, 9 Jul 2022 14:00:26 -0700 Subject: [PATCH 1034/2729] Create Readme.md --- Greedy/2333.Minimum-Sum-of-Squared-Difference/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2333.Minimum-Sum-of-Squared-Difference/Readme.md diff --git a/Greedy/2333.Minimum-Sum-of-Squared-Difference/Readme.md b/Greedy/2333.Minimum-Sum-of-Squared-Difference/Readme.md new file mode 100644 index 000000000..001918de8 --- /dev/null +++ b/Greedy/2333.Minimum-Sum-of-Squared-Difference/Readme.md @@ -0,0 +1,9 @@ +### 2333.Minimum-Sum-of-Squared-Difference + +这道题和```2233.Maximum-Product-After-K-Increments```非常类似。我们令```nums[i]=abs(nums1[i]-nums2[i])```和```k=k1+k2```,那么就是要在nums里面的元素最多做k次减一的操作,使得所有元素的平方和最小。 + +将nums降序排列之后,我们必然试图先减小最大值nums[0]。当最大值降到nums[1]的时候,如果还有操作余地,那就试图将两个当前并列最大的元素将至nums[2],依次执行。所以我们显然可以找到一个位置i,使得不超过k次操作可以将前i个元素都降到nums[i]一样大,条件就是```presum[i] - nums[i]*(i+1) <= k```. + +之后我们可能还有多余的操作次数```diff = k - (presum[i] - nums[i]*(i+1))```,这些操作可以让前i+1个元素都再降一些,但又不足以降至nums[i+1]。显然,我们可以将这些diff平均分配给这i+1个元素,这样大家都可以再降```diff/(i+1)```。如果除不尽,那么意味着有部分元素可以再降1. + +最终答案就是将三部分元素的平方和相加即可。 From 8a18901f606d9a05abd88aece4e2d907e3a1b486 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 15:01:16 -0700 Subject: [PATCH 1035/2729] Update 84-Largest-Rectangle-in-Histogram.cpp --- .../84-Largest-Rectangle-in-Histogram.cpp | 46 +++++-------------- 1 file changed, 12 insertions(+), 34 deletions(-) diff --git a/Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram.cpp b/Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram.cpp index 07e44f972..9236f41f7 100644 --- a/Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram.cpp +++ b/Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram.cpp @@ -1,43 +1,21 @@ class Solution { public: - /** - * @param height: A list of integer - * @return: The area of largest rectangle in the histogram - */ - int largestRectangleArea(vector &height) + int largestRectangleArea(vector& heights) { - if (height.size()==0) return 0; - if (height.size()==1) return height[0]; - - height.push_back(0); - height.insert(height.begin(),0); - stacks; - - int result=0; - - for (int i=0; iStack; + int result = 0; + for (int i=0; i=height[s.top()]) + while (!Stack.empty() && heights[Stack.top()] > heights[i]) { - s.push(i); - continue; + int H = heights[Stack.top()]; + Stack.pop(); + result = max(result, H*(i-Stack.top()-1)); } - - if (height[i]height[i]) - { - - int Height = height[s.top()]; - s.pop(); - result = max(result, Height*(i-s.top()-1)); - - } - s.push(i); - } + Stack.push(i); } - - return result; + return result; } }; From f59649b1416798d16cd5a6977201121389085e31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 15:07:25 -0700 Subject: [PATCH 1036/2729] Update Readme.md --- .../Readme.md | 26 +++---------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/Stack/084.Largest-Rectangle-in-Histogram/Readme.md b/Stack/084.Largest-Rectangle-in-Histogram/Readme.md index 8d901f659..ce7df6c34 100644 --- a/Stack/084.Largest-Rectangle-in-Histogram/Readme.md +++ b/Stack/084.Largest-Rectangle-in-Histogram/Readme.md @@ -1,32 +1,14 @@ ### leetcode-84-Largest-Rectangle-in-Histogram -#### 此类是贪心法的典型题。 ----------- -贪心法的原则是维护一个递增(严格的说是非递减)的栈序列s,s里面是所给数组元素的index(注意不是数组元素本身)。当下一个元素满足递增的要求时,入栈: -```c -if (height[i]>height[s.top()]) - s.push(height[i]); -``` -当下一个元素不满足递增的要求时,就退栈处理栈顶的一些元素,使得即将入列的元素依然满足递增关系。退栈处理的过程中可以方便地考察那些退栈元素所围成的最大面积。其高度易知是height[s.top()],但宽度是什么呢?注意是和次顶元素的位置有关: -```cpp -while (height[s.back()]>height[i]) -{ - Height = height[s.top()]; - s.pop(); // 提取次顶元素的位置 - result = max(result, Height * (i-s.top()-1);   -} -``` -注意如果写成以下就是错误的: -```c -result = max(result, height[s.top()] * (i-s.top()); -``` +此题是单调栈的经典应用。对于每个位置height[i],找出它的prevSmaller和nextSmaller,那么中间的区间,就可以构建一个以height[i]为高的矩形。 +比较笨的方法就是写3-pass。第一遍是用单调栈求出所有每个元素i的prevSmaller[i]。再逆序遍历一遍,求出每个元素i的nextSmaller[i]。最后一遍计算```area[i] = height[i]*(nextSmaller[i]-prevSmaller[i]-1)```. -原因是次顶元素和栈顶元素可能在index上并不是相邻的,中间可能隔着一些已经被处理掉的大数。因此在考虑当前的栈顶元素围成的面积,应该包括这些位置,所以其宽度不仅是i-s.top(),而要更大。   +高级一点的方法只需要1-pass。维护一个递增的单调栈。当新元素i比栈顶元素小时,说明栈顶元素的nextSmaller就是i,而栈顶元素的prevSmaller就是栈的次顶元素。 其他的技巧:   ---------- 在height数组末添加元素0,是为了保证最后强制回溯。在height数组首端添加元素0,是为了便于处理s.pop()之后栈为空的特殊情况;这样处理后永远不会栈空。 -[Leetcode Link](https://leetcode.com/problems/largest-rectangle-in-histogram) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/largest-rectangle-in-histogram) From 082fafa0aa08a7c69e9d43687fe476512505159c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 15:07:41 -0700 Subject: [PATCH 1037/2729] Update Readme.md --- Stack/084.Largest-Rectangle-in-Histogram/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Stack/084.Largest-Rectangle-in-Histogram/Readme.md b/Stack/084.Largest-Rectangle-in-Histogram/Readme.md index ce7df6c34..fabb5ef63 100644 --- a/Stack/084.Largest-Rectangle-in-Histogram/Readme.md +++ b/Stack/084.Largest-Rectangle-in-Histogram/Readme.md @@ -6,8 +6,8 @@ 高级一点的方法只需要1-pass。维护一个递增的单调栈。当新元素i比栈顶元素小时,说明栈顶元素的nextSmaller就是i,而栈顶元素的prevSmaller就是栈的次顶元素。 -其他的技巧:   ----------- +#### 其他的技巧: + 在height数组末添加元素0,是为了保证最后强制回溯。在height数组首端添加元素0,是为了便于处理s.pop()之后栈为空的特殊情况;这样处理后永远不会栈空。 From a2c2c11eb2fc84e56f52a5a7266e2163a900bff1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 15:14:34 -0700 Subject: [PATCH 1038/2729] Create 2334.Subarray-With-Elements-Greater-Than-Varying-Threshold.cpp --- ...lements-Greater-Than-Varying-Threshold.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold.cpp diff --git a/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold.cpp b/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold.cpp new file mode 100644 index 000000000..9d32d277b --- /dev/null +++ b/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int validSubarraySize(vector& nums, int threshold) + { + nums.insert(nums.begin(), 0); + nums.push_back(0); + + int n = nums.size(); + stackstk; + for (int i=0; i threshold) + return i-stk.top()-1; + } + stk.push(i); + } + + return -1; + + } +}; From 22826cd841dba3469d8708c6a68914f807ae58ab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 15:15:39 -0700 Subject: [PATCH 1039/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1936fc65d..2ba09c275 100644 --- a/Readme.md +++ b/Readme.md @@ -335,6 +335,7 @@ * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) +[2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [255.Verify-Preorder-Sequence-in-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/255.Verify-Preorder-Sequence-in-Binary-Search-Tree) (H) [496.Next-Greater-Element-I](https://github.com/wisdompeak/LeetCode/tree/master/Stack/496.Next-Greater-Element-I) (H-) From bdaaa315102626e28c183913957fb4beae884687 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 15:18:41 -0700 Subject: [PATCH 1040/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold/Readme.md diff --git a/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold/Readme.md b/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold/Readme.md new file mode 100644 index 000000000..464a33287 --- /dev/null +++ b/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold/Readme.md @@ -0,0 +1,5 @@ +### 2334.Subarray-With-Elements-Greater-Than-Varying-Threshold + +这道题的套路隐藏地非常巧妙。如果我们将nums看成一个histogram,那么本质就是求一个rectange,其面积要大于threshold。 + +于是这就完全转化成了`84-Largest-Rectangle-in-Histogram`,我们只要遍历每个元素,考察它作为矩形的高时,宽的最大范围,再查看area是否大于threshold即可。 From a2c45e9b28f269d63e1e5b1b5a3410f9546f9894 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 16:12:59 -0700 Subject: [PATCH 1041/2729] Create 084.Largest-Rectangle-in-Histogram_v1.cpp --- .../084.Largest-Rectangle-in-Histogram_v1.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v1.cpp diff --git a/Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v1.cpp b/Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v1.cpp new file mode 100644 index 000000000..631517722 --- /dev/null +++ b/Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v1.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int largestRectangleArea(vector& heights) + { + int n = heights.size(); + stackstk; + vectornextSmaller(n, n); + for (int i=0; i heights[i]) + { + nextSmaller[stk.top()] = i; + stk.pop(); + } + stk.push(i); + } + + while (!stk.empty()) stk.pop(); + vectorprevSmaller(n, -1); + for (int i=0; i heights[i]) + { + stk.pop(); + } + if (!stk.empty()) + prevSmaller[i] = stk.top(); + stk.push(i); + } + + int ret = 0; + for (int i=0; i Date: Sat, 9 Jul 2022 16:13:10 -0700 Subject: [PATCH 1042/2729] Rename 84-Largest-Rectangle-in-Histogram.cpp to 84-Largest-Rectangle-in-Histogram_v2.cpp --- ...-in-Histogram.cpp => 84-Largest-Rectangle-in-Histogram_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Stack/084.Largest-Rectangle-in-Histogram/{84-Largest-Rectangle-in-Histogram.cpp => 84-Largest-Rectangle-in-Histogram_v2.cpp} (100%) diff --git a/Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram.cpp b/Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram_v2.cpp similarity index 100% rename from Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram.cpp rename to Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram_v2.cpp From ddeb50cd7e2c1260175393abf35e81d9bf179a40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 16:13:51 -0700 Subject: [PATCH 1043/2729] Rename 84-Largest-Rectangle-in-Histogram_v2.cpp to 84.Largest-Rectangle-in-Histogram_v2.cpp --- ...-Histogram_v2.cpp => 84.Largest-Rectangle-in-Histogram_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Stack/084.Largest-Rectangle-in-Histogram/{84-Largest-Rectangle-in-Histogram_v2.cpp => 84.Largest-Rectangle-in-Histogram_v2.cpp} (100%) diff --git a/Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram_v2.cpp b/Stack/084.Largest-Rectangle-in-Histogram/84.Largest-Rectangle-in-Histogram_v2.cpp similarity index 100% rename from Stack/084.Largest-Rectangle-in-Histogram/84-Largest-Rectangle-in-Histogram_v2.cpp rename to Stack/084.Largest-Rectangle-in-Histogram/84.Largest-Rectangle-in-Histogram_v2.cpp From 017cfa6caa5baf2a45a04f64a22feb271c05f4a1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 16:49:11 -0700 Subject: [PATCH 1044/2729] Rename 84.Largest-Rectangle-in-Histogram_v2.cpp to 084.Largest-Rectangle-in-Histogram_v2.cpp --- ...Histogram_v2.cpp => 084.Largest-Rectangle-in-Histogram_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Stack/084.Largest-Rectangle-in-Histogram/{84.Largest-Rectangle-in-Histogram_v2.cpp => 084.Largest-Rectangle-in-Histogram_v2.cpp} (100%) diff --git a/Stack/084.Largest-Rectangle-in-Histogram/84.Largest-Rectangle-in-Histogram_v2.cpp b/Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v2.cpp similarity index 100% rename from Stack/084.Largest-Rectangle-in-Histogram/84.Largest-Rectangle-in-Histogram_v2.cpp rename to Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v2.cpp From e3ffac477fe54e03f7ab8a7a7271869cf2ff796d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Jul 2022 16:54:59 -0700 Subject: [PATCH 1045/2729] Update 85-Maximal-Rectangle.cpp --- .../85-Maximal-Rectangle.cpp | 68 +++++++------------ 1 file changed, 23 insertions(+), 45 deletions(-) diff --git a/Stack/085.Maximal-Rectangle/85-Maximal-Rectangle.cpp b/Stack/085.Maximal-Rectangle/85-Maximal-Rectangle.cpp index f31412f12..c7e9c7e14 100644 --- a/Stack/085.Maximal-Rectangle/85-Maximal-Rectangle.cpp +++ b/Stack/085.Maximal-Rectangle/85-Maximal-Rectangle.cpp @@ -1,66 +1,44 @@ class Solution { public: - /** - * @param matrix a boolean 2D matrix - * @return an integer - */ - int maximalRectangle(vector > &matrix) + int maximalRectangle(vector>& matrix) { int M=matrix.size(); - if (M==0) return 0; int N=matrix[0].size(); - auto q= vector(N,0); - int result = 0; + auto hist = vector(N,0); + int result=0; for (int i=0; iheight) - { - if (height.size()==0) return 0; - if (height.size()==1) return height[0]; - - stacks; - height.push_back(0); - height.insert(height.begin(),0); - - int result=0; - - for (int i=0; i heights) + { + heights.insert(heights.begin(),0); + heights.push_back(0); + stackStack; + int result = 0; + for (int i=0; i=height[s.top()]) + while (!Stack.empty() && heights[Stack.top()] > heights[i]) { - s.push(i); - continue; - } - - if (height[i] Date: Sun, 10 Jul 2022 09:30:54 -0700 Subject: [PATCH 1046/2729] Create 2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp --- .../2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp diff --git a/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp b/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp new file mode 100644 index 000000000..e0744df89 --- /dev/null +++ b/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int fillCups(vector& amount) + { + sort(amount.rbegin(), amount.rend()); + int total = accumulate(amount.begin(), amount.end(), 0); + if (amount[0]>=(total+1)/2) + return amount[0]; + else + return (total+1)/2; + + } +}; From 9b8af7d0123c2c92fdc8f178c32b1315fcee128d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 09:33:50 -0700 Subject: [PATCH 1047/2729] Create 2335.Minimum-Amount-of-Time-to-Fill-Cups_v1.cpp --- ...Minimum-Amount-of-Time-to-Fill-Cups_v1.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v1.cpp diff --git a/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v1.cpp b/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v1.cpp new file mode 100644 index 000000000..48d5cbdea --- /dev/null +++ b/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v1.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int fillCups(vector& amount) + { + priority_queuepq; + for (int x: amount) + { + if (x!=0) + pq.push(x); + } + int ret = 0; + while (pq.size()>=2) + { + int a = pq.top(); + pq.pop(); + int b = pq.top(); + pq.pop(); + ret++; + if (a-1>0) + pq.push(a-1); + if (b-1>0) + pq.push(b-1); + } + + if (pq.size()==1) + ret += pq.top(); + return ret; + + } +}; From 5db1e1ead21aecbb5dc561e6fb491691045773a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 09:34:21 -0700 Subject: [PATCH 1048/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 2ba09c275..d2af0c88f 100644 --- a/Readme.md +++ b/Readme.md @@ -421,6 +421,7 @@ [984.String-Without-AAA-or-BBB](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/984.String-Without-AAA-or-BBB) (M+) [1405.Longest-Happy-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1405.Longest-Happy-String) (H-) [1953.Maximum-Number-of-Weeks-for-Which-You-Can-Work](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1953.Maximum-Number-of-Weeks-for-Which-You-Can-Work) (M+) +[2335.Minimum-Amount-of-Time-to-Fill-Cups](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups) (M+) #### [DFS](https://github.com/wisdompeak/LeetCode/tree/master/DFS) [037.Sudoku-Solver](https://github.com/wisdompeak/LeetCode/tree/master/DFS/037.Sudoku-Solver) (M+) From f9bab6f490be9bd86f1e393566a12eae46d26cc6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 09:49:21 -0700 Subject: [PATCH 1049/2729] Update 2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp --- .../2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp b/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp index e0744df89..8af54e3e3 100644 --- a/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp +++ b/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/2335.Minimum-Amount-of-Time-to-Fill-Cups_v2.cpp @@ -4,7 +4,7 @@ class Solution { { sort(amount.rbegin(), amount.rend()); int total = accumulate(amount.begin(), amount.end(), 0); - if (amount[0]>=(total+1)/2) + if (amount[0]>=total/2+1) return amount[0]; else return (total+1)/2; From 69c059bbec2b4f5151d1d31fa72145cff6c05b26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 09:51:34 -0700 Subject: [PATCH 1050/2729] Create Readme.md --- .../2335.Minimum-Amount-of-Time-to-Fill-Cups/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/Readme.md diff --git a/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/Readme.md b/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/Readme.md new file mode 100644 index 000000000..0c6571fa7 --- /dev/null +++ b/Priority_Queue/2335.Minimum-Amount-of-Time-to-Fill-Cups/Readme.md @@ -0,0 +1,9 @@ +### 2335.Minimum-Amount-of-Time-to-Fill-Cups + +如果我们将三种元素组成一个序列,一次取俩,每次抓取尽量要是不同的元素。言下之意就是希望将不同元素尽量间隔分布。于是这道题的本质就是```767.Reorganize-String```。 + +#### 解法1:模拟 +基本思想是,每个回合尽量使用当前剩余频次最多的两种元素,这样就能尽量最大化剩下元素的种类数,方便尽可能持久地凑成pair。所以我们用一个大顶堆的pq,每次读取最大的两个元素,各自减一后再放回去,直至pq里面只剩下一种元素。 + +#### 解法2:抽屉原理 +假设元素的总个数是total,如果最多元素的种类占据了二分之一以上,即```amount[0]>=total/2+1```,那么我们就无法保证间隔排列,所以必须操作amount[0]次,每次要么搭配一个其他种类的元素,要么自己单独被取出。反之,如果```amount[0] Date: Sun, 10 Jul 2022 10:24:28 -0700 Subject: [PATCH 1051/2729] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index d2af0c88f..392c3d159 100644 --- a/Readme.md +++ b/Readme.md @@ -1108,9 +1108,6 @@ [2182.Construct-String-With-Repeat-Limit](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2182.Construct-String-With-Repeat-Limit) (M+) [2193.Minimum-Number-of-Moves-to-Make-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2193.Minimum-Number-of-Moves-to-Make-Palindrome) (H+) [2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) -[2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) -[2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) -[2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) [2242.Maximum-Score-of-a-Node-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2242.Maximum-Score-of-a-Node-Sequence) (M+) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) @@ -1118,6 +1115,10 @@ [2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) [2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K) (H-) [2332.The-Latest-Time-to-Catch-a-Bus](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2332.The-Latest-Time-to-Catch-a-Bus) (H-) +* ``Smear Top Elements`` +[2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) +[2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) +[2234.Maximum-Total-Beauty-of-the-Gardens](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2234.Maximum-Total-Beauty-of-the-Gardens) (H-) * ``LIS`` [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) [354.Russian-Doll-Envelopes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/354.Russian-Doll-Envelopes) (H-) From 5a5b23077209f882d0b4d07b2a70fdd2ba276af0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 10:37:45 -0700 Subject: [PATCH 1052/2729] Create 2337.Move-Pieces-to-Obtain-a-String.cpp --- .../2337.Move-Pieces-to-Obtain-a-String.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp diff --git a/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp b/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp new file mode 100644 index 000000000..5babc627b --- /dev/null +++ b/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + bool canChange(string start, string target) + { + string s, t; + + vectorpos1; + vectorpos2; + for (int i=0; i pos2[i]) return false; + } + } + + return true; + } +}; From acdbcb2345ba6981a6e79a8f360447014326104a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 10:39:36 -0700 Subject: [PATCH 1053/2729] Update 2337.Move-Pieces-to-Obtain-a-String.cpp --- .../2337.Move-Pieces-to-Obtain-a-String.cpp | 51 ++++++------------- 1 file changed, 15 insertions(+), 36 deletions(-) diff --git a/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp b/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp index 5babc627b..a4ee4dbc5 100644 --- a/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp +++ b/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp @@ -2,44 +2,23 @@ class Solution { public: bool canChange(string start, string target) { - string s, t; - - vectorpos1; - vectorpos2; - for (int i=0; ij) + return false; + if (start[i]=='L' && i pos2[i]) return false; - } - } - return true; } }; From 4cf14bf56fa435775b491206e0564892fdf6dd26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 10:40:48 -0700 Subject: [PATCH 1054/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 392c3d159..d27be1e67 100644 --- a/Readme.md +++ b/Readme.md @@ -1243,6 +1243,7 @@ [1997.First-Day-Where-You-Have-Been-in-All-the-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/1997.First-Day-Where-You-Have-Been-in-All-the-Rooms) (H) [2018.Check-if-Word-Can-Be-Placed-In-Crossword](https://github.com/wisdompeak/LeetCode/tree/master/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword) (M+) [2147.Number-of-Ways-to-Divide-a-Long-Corridor](https://github.com/wisdompeak/LeetCode/tree/master/Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor) (M) +[2337.Move-Pieces-to-Obtain-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2337.Move-Pieces-to-Obtain-a-String) (aka. 777.Swap-Adjacent-in-LR-String) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From a16ac6c6e11e74487303d310846bb6b682971039 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 10:48:07 -0700 Subject: [PATCH 1055/2729] Create Readme.md --- Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md diff --git a/Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md b/Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md new file mode 100644 index 000000000..50ee487df --- /dev/null +++ b/Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md @@ -0,0 +1,9 @@ +### 2337.Move-Pieces-to-Obtain-a-String + +此题和```777. Swap Adjacent in LR String```一模一样。 + +因为任何LR都不会彼此跨越,所以我们很容易得到一个必要条件,那就是将空格字符拿掉之后,start和target字符串必须完全一致,先相同位置上的字符都是彼此对应的。 + +其次,因为target里的L必须是从start里对应的L向右移动得到,所以另一个必要条件就是查看他们的初始位置:start里的L必须比target里对应的L更靠左。同理,start里的R必须比target里对应的R更靠右。如果不满足,就可以直接返回true。 + +以上两个必要条件都满足后,答案就是充分的。 From a67ff5df3086a824f8615d45ff1f59cfc89cb9fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 11:07:28 -0700 Subject: [PATCH 1056/2729] Update 2337.Move-Pieces-to-Obtain-a-String.cpp --- .../2337.Move-Pieces-to-Obtain-a-String.cpp | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp b/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp index a4ee4dbc5..c2ab3af99 100644 --- a/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp +++ b/Others/2337.Move-Pieces-to-Obtain-a-String/2337.Move-Pieces-to-Obtain-a-String.cpp @@ -2,23 +2,29 @@ class Solution { public: bool canChange(string start, string target) { - int i=0; - int j=0; - while (ij) - return false; + return false; if (start[i]=='L' && ij) return false; - i++; + j++; } + + for (int k=j; k Date: Sun, 10 Jul 2022 11:18:06 -0700 Subject: [PATCH 1057/2729] Update Primes.cpp --- Template/Math/Primes.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/Template/Math/Primes.cpp b/Template/Math/Primes.cpp index d3e1ac207..9c8f08d03 100644 --- a/Template/Math/Primes.cpp +++ b/Template/Math/Primes.cpp @@ -1,20 +1,18 @@ // Find all primes <= n. vectorEratosthenes(int n) { - auto q=vector(n+1,0); + vectorq(n+1,0); + vectorprimes; for (int i=2; i<=sqrt(n); i++) { - if (q[i]==0) + if (q[i]==1) continue; + int j=i*2; + while (j<=n) { - int j=i*2; - while (j<=n) - { - q[j]=1; - j+=i; - } + q[j]=1; + j+=i; } - } - vectorprimes; + } for (int i=2; i<=n; i++) { if (q[i]==0) From 7884d170417e66992f7011344210cf8fd8bac128 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 11:24:46 -0700 Subject: [PATCH 1058/2729] Create 2338.Count-the-Number-of-Ideal-Arrays.cpp --- .../2338.Count-the-Number-of-Ideal-Arrays.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/2338.Count-the-Number-of-Ideal-Arrays.cpp diff --git a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/2338.Count-the-Number-of-Ideal-Arrays.cpp b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/2338.Count-the-Number-of-Ideal-Arrays.cpp new file mode 100644 index 000000000..45685d3cc --- /dev/null +++ b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/2338.Count-the-Number-of-Ideal-Arrays.cpp @@ -0,0 +1,66 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[10001][15]; +public: + int idealArrays(int n, int maxValue) + { + dp[0][0] = 1; + for (int i=1; i<=n; i++) + { + dp[i][0] = 1; + for (int j=1; j<=14; j++) + { + for (int k=0; k<=j; k++) + { + dp[i][j] += dp[i-1][j-k]; + dp[i][j] %= M; + } + } + } + + vectorprimes = Eratosthenes(maxValue); + + LL ret = 1; + for (int t=2; t<=maxValue; t++) + { + int x = t; + LL ans = 1; + for (auto p: primes) + { + int count = 0; + while (x>1 && (x%p==0)) + { + x/=p; + count++; + } + ans = ans * dp[n][count] % M; + } + ret = (ret + ans) % M; + } + + return ret; + } + + vectorEratosthenes(int n) + { + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); + } + return primes; + } +}; From cd31c3d9fee7011feaff0af33cab512dde26edfa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 11:25:39 -0700 Subject: [PATCH 1059/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d27be1e67..d2910b8bb 100644 --- a/Readme.md +++ b/Readme.md @@ -628,6 +628,7 @@ [2218.Maximum-Value-of-K-Coins-From-Piles](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2218.Maximum-Value-of-K-Coins-From-Piles) (H-) [2222.Number-of-Ways-to-Select-Buildings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings) (M+) [2312.Selling-Pieces-of-Wood](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2312.Selling-Pieces-of-Wood) (M+) +[2338.Count-the-Number-of-Ideal-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From ad30089a97acabebc26b7fe812db0f690623b452 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 11:50:08 -0700 Subject: [PATCH 1060/2729] Update 2338.Count-the-Number-of-Ideal-Arrays.cpp --- .../2338.Count-the-Number-of-Ideal-Arrays.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/2338.Count-the-Number-of-Ideal-Arrays.cpp b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/2338.Count-the-Number-of-Ideal-Arrays.cpp index 45685d3cc..83ae63cab 100644 --- a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/2338.Count-the-Number-of-Ideal-Arrays.cpp +++ b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/2338.Count-the-Number-of-Ideal-Arrays.cpp @@ -1,7 +1,7 @@ using LL = long long; LL M = 1e9+7; class Solution { - LL dp[10001][15]; + LL dp[10001][15]; // dp[i][j]: how many distinct ways to put j same factors in the first i positions (allowing multple factors in the same position) public: int idealArrays(int n, int maxValue) { From 0da54f89bc187eceea2b34b74e2acef2e0654bbe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 12:21:42 -0700 Subject: [PATCH 1061/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md diff --git a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md new file mode 100644 index 000000000..43db52884 --- /dev/null +++ b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md @@ -0,0 +1,21 @@ +### 2338.Count-the-Number-of-Ideal-Arrays + +我们令序列的最后一个元素是x,那么这个长度为n的序列的本质就是从1开始,每次乘以1或者一个x的非1的因数,直至最后一个元素变成x。显然,这些非1的因数的集合必须是x的一个分解,比如说,当n=4, x=24的时候,可以有```30 = 1*2*3*5```,对应的序列就是{1,2,6,30};或者```30 = 5*1*3*2```,对应的序列就是{5,5,15,30},以及其他。 + +考虑到x的分解其实太多了,但是质因数分解是唯一的,比如记做```x = a*b*c...```。所以我们很容易发现,我们本质只需要将每个质因数任意地分配这n个位置上,最后都能对应一个符合条件的序列。注意,言下之意,每个位置可以允许放置多个质因数。比如上面的例子,将30的质因数分解```2*3*5```任意丢进4个位置上,```(),(2,3),(5),()```,那么本质上就对应了序列{1,6,30,30}。 + +既然每个质因数都可以独立放置,那么假设x有k个质因数,那么以x为结尾的序列个数是不是就是```n^k```呢?我们这里发现了一个问题,那就是没法保证这些序列是distinct的,问题出在相同的质因数上。比如说n=2,x=4的例子,x有两个相同的质因数(记做2a和2b),如果各自独立地扔进两个位置,那么我们会有四种分配方式 ```{a1, a2}, {a2, a1}, {_ , a1*a2}, {a1*a2, _}```. 但是前两者序列都对应了{2,4}这一样的序列。 + +至此,我们调整目标,当前需要解决的问题是:对于k个相同的质因数,我们想将它们分配在n个位置上(允许一个位置有多个),那么有多少种看上去“不同”的分配方式。这应该就是一个典型的DP题。我们类似地定义dp[i][j],那么转移方程的关键就是看第i个位置上我们放置了多少个质因数,假设如果有t个,那么问题就转移到了dp[i-1][j-t]。所以大致的dp方程就是 +```cp +for (int i=1; i<=n; i++) + for (int j=0; j<=k; j++) + { + for (int k=0; k<=j; k++) + dp[i][j] += dp[i-1][j-k]; + } +``` +预处理全部dp值的时间复杂度是o(NKK),其中K是对于x的某个质因数的个数。考虑到x的上限是10000,就算这个质因数是最小的2,那么重复出现的次数也不会超过14,否则2^14就超过了上限。所以dp的时间复杂度就是o(196N),考虑到N是1e4,那么恰好完美符合题目的预期。 + +综上,本题的解法是:从1到MaxVal遍历x作为序列的最后一个元素:对x做质因数分解,对于每种质因数,如果个数是k,我们就有dp[n][k]种分配方法,然后将所有不同质因数的分配方法相乘。最后把不同的x的结果再相加。 + From 1f64dfc273c405971410d467a3b84e0719449c37 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 12:22:07 -0700 Subject: [PATCH 1062/2729] Update Readme.md --- .../2338.Count-the-Number-of-Ideal-Arrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md index 43db52884..98cf83134 100644 --- a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md +++ b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md @@ -1,6 +1,6 @@ ### 2338.Count-the-Number-of-Ideal-Arrays -我们令序列的最后一个元素是x,那么这个长度为n的序列的本质就是从1开始,每次乘以1或者一个x的非1的因数,直至最后一个元素变成x。显然,这些非1的因数的集合必须是x的一个分解,比如说,当n=4, x=24的时候,可以有```30 = 1*2*3*5```,对应的序列就是{1,2,6,30};或者```30 = 5*1*3*2```,对应的序列就是{5,5,15,30},以及其他。 +我们令序列的最后一个元素是x,那么这个长度为n的序列的本质就是从1开始,每次乘以1或者一个x的非1的因数,直至最后一个元素变成x。显然,这些非1的因数的集合必须是x的一个分解,比如说,当n=4, x=30的时候,可以有```30 = 1*2*3*5```,对应的序列就是{1,2,6,30};或者```30 = 5*1*3*2```,对应的序列就是{5,5,15,30},以及其他。 考虑到x的分解其实太多了,但是质因数分解是唯一的,比如记做```x = a*b*c...```。所以我们很容易发现,我们本质只需要将每个质因数任意地分配这n个位置上,最后都能对应一个符合条件的序列。注意,言下之意,每个位置可以允许放置多个质因数。比如上面的例子,将30的质因数分解```2*3*5```任意丢进4个位置上,```(),(2,3),(5),()```,那么本质上就对应了序列{1,6,30,30}。 From cb0f5b49358efa6675bd8245465c3e4f15a805af Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 12:24:04 -0700 Subject: [PATCH 1063/2729] Update Readme.md --- .../2338.Count-the-Number-of-Ideal-Arrays/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md index 98cf83134..f54742885 100644 --- a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md +++ b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md @@ -2,9 +2,9 @@ 我们令序列的最后一个元素是x,那么这个长度为n的序列的本质就是从1开始,每次乘以1或者一个x的非1的因数,直至最后一个元素变成x。显然,这些非1的因数的集合必须是x的一个分解,比如说,当n=4, x=30的时候,可以有```30 = 1*2*3*5```,对应的序列就是{1,2,6,30};或者```30 = 5*1*3*2```,对应的序列就是{5,5,15,30},以及其他。 -考虑到x的分解其实太多了,但是质因数分解是唯一的,比如记做```x = a*b*c...```。所以我们很容易发现,我们本质只需要将每个质因数任意地分配这n个位置上,最后都能对应一个符合条件的序列。注意,言下之意,每个位置可以允许放置多个质因数。比如上面的例子,将30的质因数分解```2*3*5```任意丢进4个位置上,```(),(2,3),(5),()```,那么本质上就对应了序列{1,6,30,30}。 +考虑到x的分解其实太多了,但是质因数分解是唯一的,比如记做```x = a*b*c...```。所以我们很容易发现,我们本质只需要将每个质因数任意地分配这n个位置上,最后都能对应一个符合条件的序列。特别注意,每个位置可以允许放置多个质因数。比如上面的例子,将30的质因数分解```2*3*5```任意丢进4个位置上:我们可以```(),(2),(5),(3)```,那么本质上就对应了序列{1,2,10,30};我们也可以```(),(2,3),(5),()```,那么本质上就对应了序列{1,6,30,30}。 -既然每个质因数都可以独立放置,那么假设x有k个质因数,那么以x为结尾的序列个数是不是就是```n^k```呢?我们这里发现了一个问题,那就是没法保证这些序列是distinct的,问题出在相同的质因数上。比如说n=2,x=4的例子,x有两个相同的质因数(记做2a和2b),如果各自独立地扔进两个位置,那么我们会有四种分配方式 ```{a1, a2}, {a2, a1}, {_ , a1*a2}, {a1*a2, _}```. 但是前两者序列都对应了{2,4}这一样的序列。 +既然每个质因数都可以独立放置,那么假设x总共有k个质因数,那么以x为结尾的序列个数是不是就是```n^k```呢?我们这里发现了一个问题,那就是没法保证这些序列是distinct的,问题出在相同的质因数上。比如说n=2,x=4的例子,x有两个相同的质因数(记做2a和2b),如果各自独立地扔进两个位置,那么我们会有四种分配方式 ```{a1, a2}, {a2, a1}, {_ , a1*a2}, {a1*a2, _}```. 但是前两者序列都对应了{2,4}这一样的序列。 至此,我们调整目标,当前需要解决的问题是:对于k个相同的质因数,我们想将它们分配在n个位置上(允许一个位置有多个),那么有多少种看上去“不同”的分配方式。这应该就是一个典型的DP题。我们类似地定义dp[i][j],那么转移方程的关键就是看第i个位置上我们放置了多少个质因数,假设如果有t个,那么问题就转移到了dp[i-1][j-t]。所以大致的dp方程就是 ```cp From dde2b08a1ed164e0321192bb462a6d9e9989538d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 12:25:10 -0700 Subject: [PATCH 1064/2729] Update Readme.md --- .../2338.Count-the-Number-of-Ideal-Arrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md index f54742885..603b32adf 100644 --- a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md +++ b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md @@ -2,7 +2,7 @@ 我们令序列的最后一个元素是x,那么这个长度为n的序列的本质就是从1开始,每次乘以1或者一个x的非1的因数,直至最后一个元素变成x。显然,这些非1的因数的集合必须是x的一个分解,比如说,当n=4, x=30的时候,可以有```30 = 1*2*3*5```,对应的序列就是{1,2,6,30};或者```30 = 5*1*3*2```,对应的序列就是{5,5,15,30},以及其他。 -考虑到x的分解其实太多了,但是质因数分解是唯一的,比如记做```x = a*b*c...```。所以我们很容易发现,我们本质只需要将每个质因数任意地分配这n个位置上,最后都能对应一个符合条件的序列。特别注意,每个位置可以允许放置多个质因数。比如上面的例子,将30的质因数分解```2*3*5```任意丢进4个位置上:我们可以```(),(2),(5),(3)```,那么本质上就对应了序列{1,2,10,30};我们也可以```(),(2,3),(5),()```,那么本质上就对应了序列{1,6,30,30}。 +考虑到x的普通因数分解其实太多了,但是质因数分解是唯一的,比如记做```x = a*b*c...```。所以我们很容易发现,我们本质只需要将每个质因数任意地分配这n个位置上,最后都能对应一个符合条件的序列。特别注意,每个位置可以允许放置多个质因数。比如上面的例子,将30的质因数分解```2*3*5```任意丢进4个位置上:我们可以```(),(2),(5),(3)```,那么本质上就对应了序列{1,2,10,30};我们也可以```(),(2,3),(5),()```,那么本质上就对应了序列{1,6,30,30}。 既然每个质因数都可以独立放置,那么假设x总共有k个质因数,那么以x为结尾的序列个数是不是就是```n^k```呢?我们这里发现了一个问题,那就是没法保证这些序列是distinct的,问题出在相同的质因数上。比如说n=2,x=4的例子,x有两个相同的质因数(记做2a和2b),如果各自独立地扔进两个位置,那么我们会有四种分配方式 ```{a1, a2}, {a2, a1}, {_ , a1*a2}, {a1*a2, _}```. 但是前两者序列都对应了{2,4}这一样的序列。 From 635499dc40b985ee22709b69daddfeccd1ae1d96 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Jul 2022 12:31:04 -0700 Subject: [PATCH 1065/2729] Update Readme.md --- .../2338.Count-the-Number-of-Ideal-Arrays/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md index 603b32adf..52964c695 100644 --- a/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md +++ b/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays/Readme.md @@ -11,8 +11,8 @@ for (int i=1; i<=n; i++) for (int j=0; j<=k; j++) { - for (int k=0; k<=j; k++) - dp[i][j] += dp[i-1][j-k]; + for (int t=0; t<=j; t++) + dp[i][j] += dp[i-1][j-t]; } ``` 预处理全部dp值的时间复杂度是o(NKK),其中K是对于x的某个质因数的个数。考虑到x的上限是10000,就算这个质因数是最小的2,那么重复出现的次数也不会超过14,否则2^14就超过了上限。所以dp的时间复杂度就是o(196N),考虑到N是1e4,那么恰好完美符合题目的预期。 From 535a03aec79fca8890f836678f1cb5a6d3b5185f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Jul 2022 14:16:38 -0700 Subject: [PATCH 1066/2729] Create 2343.Query-Kth-Smallest-Trimmed-Number.cpp --- ...2343.Query-Kth-Smallest-Trimmed-Number.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/2343.Query-Kth-Smallest-Trimmed-Number/2343.Query-Kth-Smallest-Trimmed-Number.cpp diff --git a/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/2343.Query-Kth-Smallest-Trimmed-Number.cpp b/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/2343.Query-Kth-Smallest-Trimmed-Number.cpp new file mode 100644 index 000000000..d80baf130 --- /dev/null +++ b/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/2343.Query-Kth-Smallest-Trimmed-Number.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector smallestTrimmedNumbers(vector& nums, vector>& queries) + { + int m = nums.size(), n = nums[0].size(); + vector>ans(n+1, vector(m)); + + for (int i=0; i>bucket(10); + for (int i=0; irets; + for (auto& q: queries) + { + rets.push_back(ans[q[1]][q[0]-1]); + } + + return rets; + } +}; From d829cf345a526001f836ab488ce8585c8bb069de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Jul 2022 14:17:13 -0700 Subject: [PATCH 1067/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d2910b8bb..f52b0bd6b 100644 --- a/Readme.md +++ b/Readme.md @@ -1165,6 +1165,7 @@ [1686.Stone-Game-VI](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1686.Stone-Game-VI) (H-) [1996.The-Number-of-Weak-Characters-in-the-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1996.The-Number-of-Weak-Characters-in-the-Game) (M+) [2250.Count-Number-of-Rectangles-Containing-Each-Point](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point) (H-) +[2343.Query-Kth-Smallest-Trimmed-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2343.Query-Kth-Smallest-Trimmed-Number) (H-) * ``Indexing Sort`` [041.First-Missing-Positive](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/041.First-Missing-Positive/Readme.md) (H) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 7bea3d3cbc1b78f7767c364541ca0c3365714750 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Jul 2022 14:40:46 -0700 Subject: [PATCH 1068/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Greedy/2343.Query-Kth-Smallest-Trimmed-Number/Readme.md diff --git a/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/Readme.md b/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/Readme.md new file mode 100644 index 000000000..3cb9c6995 --- /dev/null +++ b/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/Readme.md @@ -0,0 +1,13 @@ +### 2343.Query-Kth-Smallest-Trimmed-Number + +本题的数据规模非常小,对每个query进行暴力处理也是可以过的。 + +这里介绍一个比较优秀的“基数排序”的算法。我们令ans[i][j]表示只保留i位数字时,排列第j小的元素的原始index。 + +我们先考虑只保留一位数字的情况。假设此时的元素排序后是这些:0(x),0(x),1(x),1(x),2(x),3(x),3(x),3(x),4(x),4(x)...其中括号里面的是对应的index,具体数字不重要,他们构成了ans[1][j]. + +然后我们考虑只保留两位数字的情况。这些元素的第二位数字只有10种可能0~9,并且我们知道第二位数字是排序的primary key。这里我们就有一个技巧能够加快排序。我们构造10个bucket。我们将第一轮有序的元素按照他们各自的第二位数字,按照先后顺序扔进不同的bucket里面。此时就有一个非常好的性质:不同的bucket之间的元素必然是有序的(bucket小靠前);同一个bucket内的元素也是有序的(先扔进去的是第一轮里的较小元素,必然会靠前)。此时我们相当于只用了线性的时间就实现了所有元素的排序。我们此时将所有元素按照bucket的顺序和bucket内部的先后顺序访问一遍,就得到了ans[2][j]. + +以此类推,我们可以实现保留三位数字的元素的排序ans[3][j],等等。 + +最终我们对于每个query,我们返回的其实就是ans[trim][k-1]. From 9bb9f34086e75c566ba5a8ff71d9c06a4e9a0e14 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Jul 2022 15:13:20 -0700 Subject: [PATCH 1069/2729] Update 2343.Query-Kth-Smallest-Trimmed-Number.cpp --- ...2343.Query-Kth-Smallest-Trimmed-Number.cpp | 36 ++++++++++--------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/2343.Query-Kth-Smallest-Trimmed-Number.cpp b/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/2343.Query-Kth-Smallest-Trimmed-Number.cpp index d80baf130..663a7d191 100644 --- a/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/2343.Query-Kth-Smallest-Trimmed-Number.cpp +++ b/Greedy/2343.Query-Kth-Smallest-Trimmed-Number/2343.Query-Kth-Smallest-Trimmed-Number.cpp @@ -4,34 +4,36 @@ class Solution { { int m = nums.size(), n = nums[0].size(); vector>ans(n+1, vector(m)); - - for (int i=0; i>bucket(10); - for (int i=0; i>buckets(10); + + for (int j=0; jrets; - for (auto& q: queries) + for (auto q: queries) { rets.push_back(ans[q[1]][q[0]-1]); - } - + } return rets; } }; From 6f638188faf3855fee02bed6d7dc1baef47c5ab6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 22 Jul 2022 16:30:43 -0700 Subject: [PATCH 1070/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/1953.Maximum-Number-of-Weeks-for-Which-You-Can-Work/Readme.md b/Priority_Queue/1953.Maximum-Number-of-Weeks-for-Which-You-Can-Work/Readme.md index e7f794da6..4b44349c7 100644 --- a/Priority_Queue/1953.Maximum-Number-of-Weeks-for-Which-You-Can-Work/Readme.md +++ b/Priority_Queue/1953.Maximum-Number-of-Weeks-for-Which-You-Can-Work/Readme.md @@ -1,6 +1,6 @@ ### 1953.Maximum-Number-of-Weeks-for-Which-You-Can-Work -这道题和其他用PQ来做解决“间隔约束”的任务规划问题很相似。但是本题的特点是,不需要输出具体的解决方案。为什么呢?因为本题给出的数据量很大,本质上会有```1e5*1e9```个milestone需要安排。按照```054.Distant-Barcodes```的PQ做法,那么跑```1e14/2```次PQ的弹出、加入操作,显然会TLE。 +这道题和其他用PQ来做解决“间隔约束”的任务规划问题很相似。但是本题的特点是,不需要输出具体的解决方案。为什么呢?因为本题给出的数据量很大,本质上会有```1e5*1e9```个milestone需要安排。按照```1054.Distant-Barcodes```的PQ做法,那么跑```1e14/2```次PQ的弹出、加入操作,显然会TLE。 其实本题有明显的贪心算法。我们可以想象,如果某个任务X的milestone特别多,超过了总体的半数(加1),那么根据抽屉原理,必然有两个相同的任务X会相邻。反之,我们必然可以让任务X彼此之间至少间隔一位,让其他任务填充其中,也就是能完成所有milestone的安排。 From 058b9552654b53f73968bbec1b7819ccf6855e3b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Jul 2022 14:01:45 -0700 Subject: [PATCH 1071/2729] Update Readme.md --- Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md b/Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md index 50ee487df..e45f08866 100644 --- a/Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md +++ b/Others/2337.Move-Pieces-to-Obtain-a-String/Readme.md @@ -4,6 +4,6 @@ 因为任何LR都不会彼此跨越,所以我们很容易得到一个必要条件,那就是将空格字符拿掉之后,start和target字符串必须完全一致,先相同位置上的字符都是彼此对应的。 -其次,因为target里的L必须是从start里对应的L向右移动得到,所以另一个必要条件就是查看他们的初始位置:start里的L必须比target里对应的L更靠左。同理,start里的R必须比target里对应的R更靠右。如果不满足,就可以直接返回true。 +其次,因为target里的L必须是从start里对应的L向左移动得到,所以另一个必要条件就是查看他们的初始位置:start里的L必须比target里对应的L更靠右。同理,start里的R必须比target里对应的R更靠左。如果不满足,就可以直接返回true。 以上两个必要条件都满足后,答案就是充分的。 From 5bbc7d7dd1dcfda6fd4a5144c9d82b9f7fedceef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Jul 2022 14:05:56 -0700 Subject: [PATCH 1072/2729] Create 2350.Shortest-Impossible-Sequence-of-Rolls.cpp --- ....Shortest-Impossible-Sequence-of-Rolls.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Greedy/2350.Shortest-Impossible-Sequence-of-Rolls/2350.Shortest-Impossible-Sequence-of-Rolls.cpp diff --git a/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls/2350.Shortest-Impossible-Sequence-of-Rolls.cpp b/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls/2350.Shortest-Impossible-Sequence-of-Rolls.cpp new file mode 100644 index 000000000..af9906659 --- /dev/null +++ b/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls/2350.Shortest-Impossible-Sequence-of-Rolls.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int shortestSequence(vector& rolls, int k) + { + int n = rolls.size(); + unordered_setSet; + + int ret = 0; + for (int i=n-1; i>=0; i--) + { + Set.insert(rolls[i]); + if (Set.size()==k) + { + ret++; + Set.clear(); + } + } + return ret+1; + + } +}; From 7097a2d5471b04c91ccdce1de39cc49aee25df93 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Jul 2022 14:06:36 -0700 Subject: [PATCH 1073/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f52b0bd6b..640f6294a 100644 --- a/Readme.md +++ b/Readme.md @@ -1116,6 +1116,7 @@ [2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) [2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K) (H-) [2332.The-Latest-Time-to-Catch-a-Bus](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2332.The-Latest-Time-to-Catch-a-Bus) (H-) +[2350.Shortest-Impossible-Sequence-of-Rolls](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls) (M+) * ``Smear Top Elements`` [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) From ad659e415b1753a3a1d71b4f795752c603429702 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Jul 2022 15:07:31 -0700 Subject: [PATCH 1074/2729] Create Readme.md --- .../2350.Shortest-Impossible-Sequence-of-Rolls/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2350.Shortest-Impossible-Sequence-of-Rolls/Readme.md diff --git a/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls/Readme.md b/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls/Readme.md new file mode 100644 index 000000000..ef1907cf5 --- /dev/null +++ b/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls/Readme.md @@ -0,0 +1,9 @@ +### 2350.Shortest-Impossible-Sequence-of-Rolls + +我们考虑长度为1是否满足。我们势必会想找到一个最短的区间[0:m],使得rolls[0:m]里面必然包括了1到k。这意味着仅在这个前缀里,我们可以构造任意的、长度为1的序列。如果找不到这样的m,自然本题就终止了。此时我们关注m这个位置,不难得知,rolls[m]一定是在这个区间里唯一出现的一个元素,不妨记做x。 + +此时我们考虑长度为2的情况。因为x是[0:m]中最“稀有”的元素(最晚出现、仅出现了一次),这意味着在所有的长度为2的序列中,以x打头的序列最不容易找到。根据前述,我们必须舍弃掉前m-1个元素,直到第m个元素我们才找到了x。于是我们就只需要考虑构造“x*”这种序列,为了能让`*`可以是任意元素,我们必须在m之后再找一段区间,记做[m+1,n],使得其中包含了1到k。如果能找到这样的n,那么意味着我们在[0:n]的前缀里可以构造任意的、长度为2的序列。类似地,我们需要注意到rolls[n]一定是[m+1:n]这个区间里唯一出现的一个元素,不妨记做y。 + +同理,我们在考虑长度为3的情况时,`xy*`是最难构造的。因为最短只有在[0:n]的前缀里才出现`xy`。所以接下来的任务就是从n+1开始找一段区间,需要包含1到k的所有元素... + +依次类推,我们发现本题的本质就是从rolls的起点,不停地寻找一段区间,使其恰好包含了1到k所有的元素。能连续找到多少个这样的区间,就意味着我们可以构造多长的序列,使得序列里的每一个元素都有可能是1到k。 From 62f45c17859a45930f152dc3b9325f6edc215ce5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Jul 2022 00:46:22 -0700 Subject: [PATCH 1075/2729] Create 2354.Number-of-Excellent-Pairs.cpp --- .../2354.Number-of-Excellent-Pairs.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Two_Pointers/2354.Number-of-Excellent-Pairs/2354.Number-of-Excellent-Pairs.cpp diff --git a/Two_Pointers/2354.Number-of-Excellent-Pairs/2354.Number-of-Excellent-Pairs.cpp b/Two_Pointers/2354.Number-of-Excellent-Pairs/2354.Number-of-Excellent-Pairs.cpp new file mode 100644 index 000000000..29118caef --- /dev/null +++ b/Two_Pointers/2354.Number-of-Excellent-Pairs/2354.Number-of-Excellent-Pairs.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { +public: + long long countExcellentPairs(vector& nums, int k) + { + vectorarr; + unordered_setSet(nums.begin(), nums.end()); + + LL ret = 0; + for (auto x: Set) + { + int count = __builtin_popcount(x); + arr.push_back(count); + if (count * 2 >= k) + ret++; + } + + sort(arr.begin(), arr.end()); + + LL n = arr.size(); + LL j = n-1; + for (int i=0; i=0 && arr[i]+arr[j]>=k) + j--; + if (j>=i) + ret += (n-(j+1))*2; + else + ret += (n-(i+1))*2; + } + + return ret; + } +}; From 9f52242a0db43e94b3bf34827c28b6d913f84abc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Jul 2022 00:46:56 -0700 Subject: [PATCH 1076/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 640f6294a..a4f3e751e 100644 --- a/Readme.md +++ b/Readme.md @@ -31,6 +31,7 @@ [1793.Maximum-Score-of-a-Good-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1793.Maximum-Score-of-a-Good-Subarray) (M+) [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag) (M+) +[2354.Number-of-Excellent-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2354.Number-of-Excellent-Pairs) (H-) * ``Sliding window`` [532.K-diff-Pairs-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/532.K-diff-Pairs-in-an-Array) (H-) [611.Valid-Triangle-Number](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/611.Valid-Triangle-Number) (M+) From eeecd9a1087cb71d85833ddfcc96b6598a11aa16 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Jul 2022 01:25:19 -0700 Subject: [PATCH 1077/2729] Create Readme.md --- .../2354.Number-of-Excellent-Pairs/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md diff --git a/Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md b/Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md new file mode 100644 index 000000000..d70bbcf30 --- /dev/null +++ b/Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md @@ -0,0 +1,15 @@ +### 2354.Number-of-Excellent-Pairs + +因为涉及的都是位操作,我们不妨枚举一下对于单个bit位上可能出现的情况: +``` +a b a&b + a|b +1 1 1 + 1 = 2 +1 0 0 + 1 = 1 +0 1 0 + 1 = 1 +0 0 0 + 0 = 0 +``` +我们不难发现,无论a是0还是1,与b配对后,能得到的bit 1的个数的增量,完全取决于b本身是0还是1. 我们将这个结论从单个bit扩展到整数时依然成立,就是无论整数A是如何,与整数B配对后,bit 1的总个数的增量,就是B含有的bit 1的数目。也就是说,任意两个整数A与B配对后,得到的bit 1的总个数,就是他们各自bit 1的数目相加。 + +所以我们只需要将去重后的nums里面的每个元素,转化为其bit 1的数目,得到一个新的数组arr。那么本题的本质就是问在arr里面有多少个pair,使得其元素和大于等于k即可。显然,将arr排序之后,用双指针即可线性地找到所有pairs。注意,因为允许调换顺序,pair的数目要乘以2加入结果. + +此外,本题还允许pair里面的元素相同。所以我们还要单独考察arr里面的每一个元素,查看它自身组成一个pair的话是否符合题意。 From 6a3cf14256e4235580707ec10d2d7e2bb2834976 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Jul 2022 01:25:59 -0700 Subject: [PATCH 1078/2729] Update Readme.md --- Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md b/Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md index d70bbcf30..948869f51 100644 --- a/Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md +++ b/Two_Pointers/2354.Number-of-Excellent-Pairs/Readme.md @@ -8,7 +8,7 @@ a b a&b + a|b 0 1 0 + 1 = 1 0 0 0 + 0 = 0 ``` -我们不难发现,无论a是0还是1,与b配对后,能得到的bit 1的个数的增量,完全取决于b本身是0还是1. 我们将这个结论从单个bit扩展到整数时依然成立,就是无论整数A是如何,与整数B配对后,bit 1的总个数的增量,就是B含有的bit 1的数目。也就是说,任意两个整数A与B配对后,得到的bit 1的总个数,就是他们各自bit 1的数目相加。 +我们不难发现,无论a是0还是1,与b配对后,能得到的bit 1的数目的增量,完全取决于b本身是0还是1. 我们将这个结论从单个bit扩展到整数时依然成立,就是无论整数A是如何,与整数B配对后,bit 1的总数目的增量,就是B含有的bit 1的数目。也就是说,任意两个整数A与B配对后,得到的bit 1的总数目,就是他们各自bit 1的数目相加。 所以我们只需要将去重后的nums里面的每个元素,转化为其bit 1的数目,得到一个新的数组arr。那么本题的本质就是问在arr里面有多少个pair,使得其元素和大于等于k即可。显然,将arr排序之后,用双指针即可线性地找到所有pairs。注意,因为允许调换顺序,pair的数目要乘以2加入结果. From a7ff629753eb312afd990ca1df6c74af7ba880f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Jul 2022 13:13:51 -0700 Subject: [PATCH 1079/2729] Update 2354.Number-of-Excellent-Pairs.cpp --- .../2354.Number-of-Excellent-Pairs.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Two_Pointers/2354.Number-of-Excellent-Pairs/2354.Number-of-Excellent-Pairs.cpp b/Two_Pointers/2354.Number-of-Excellent-Pairs/2354.Number-of-Excellent-Pairs.cpp index 29118caef..d08d9c3dc 100644 --- a/Two_Pointers/2354.Number-of-Excellent-Pairs/2354.Number-of-Excellent-Pairs.cpp +++ b/Two_Pointers/2354.Number-of-Excellent-Pairs/2354.Number-of-Excellent-Pairs.cpp @@ -9,10 +9,7 @@ class Solution { LL ret = 0; for (auto x: Set) { - int count = __builtin_popcount(x); - arr.push_back(count); - if (count * 2 >= k) - ret++; + arr.push_back(__builtin_popcount(x)); } sort(arr.begin(), arr.end()); @@ -24,9 +21,16 @@ class Solution { while (j>=0 && arr[i]+arr[j]>=k) j--; if (j>=i) - ret += (n-(j+1))*2; + ret += n-(j+1); else - ret += (n-(i+1))*2; + ret += n-(i+1); + } + ret *= 2; + + for (auto x: arr) + { + if (x*2>=k) + ret++; } return ret; From bc6756cb7ccea531e1beb7dccda0036d886911fc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 Aug 2022 23:38:07 -0700 Subject: [PATCH 1080/2729] Create 2359.Find-Closest-Node-to-Given-Two-Nodes.cpp --- ...9.Find-Closest-Node-to-Given-Two-Nodes.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp diff --git a/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp b/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp new file mode 100644 index 000000000..7acab1c41 --- /dev/null +++ b/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + vectorgetDist(vector& edges, int node) + { + int n = edges.size(); + vectordist(n, -1); + int i = node; + dist[i] = 0; + while (edges[i]!=-1 && dist[edges[i]]==-1) + { + int j = edges[i]; + dist[j] = dist[i] + 1; + i = j; + } + return dist; + } + + int closestMeetingNode(vector& edges, int node1, int node2) + { + int n = edges.size(); + + vectordist1 = getDist(edges, node1); + vectordist2 = getDist(edges, node2); + + + int ret = INT_MAX; + int ans = -1; + for (int i=0; i Date: Thu, 4 Aug 2022 23:38:42 -0700 Subject: [PATCH 1081/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a4f3e751e..44b74dce3 100644 --- a/Readme.md +++ b/Readme.md @@ -1248,6 +1248,7 @@ [2018.Check-if-Word-Can-Be-Placed-In-Crossword](https://github.com/wisdompeak/LeetCode/tree/master/Others/2018.Check-if-Word-Can-Be-Placed-In-Crossword) (M+) [2147.Number-of-Ways-to-Divide-a-Long-Corridor](https://github.com/wisdompeak/LeetCode/tree/master/Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor) (M) [2337.Move-Pieces-to-Obtain-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2337.Move-Pieces-to-Obtain-a-String) (aka. 777.Swap-Adjacent-in-LR-String) (M+) +[2359.Find-Closest-Node-to-Given-Two-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2359.Find-Closest-Node-to-Given-Two-Nodes) (M) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From a28fb9c130e62ecf7120526d896d94dbe4df961e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 Aug 2022 23:42:10 -0700 Subject: [PATCH 1082/2729] Update 313.Super-Ugly-Number_dp_pq.cpp --- .../313.Super-Ugly-Number_dp_pq.cpp | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/Dynamic_Programming/313.Super-Ugly-Number/313.Super-Ugly-Number_dp_pq.cpp b/Dynamic_Programming/313.Super-Ugly-Number/313.Super-Ugly-Number_dp_pq.cpp index c561f7f96..f446641e8 100644 --- a/Dynamic_Programming/313.Super-Ugly-Number/313.Super-Ugly-Number_dp_pq.cpp +++ b/Dynamic_Programming/313.Super-Ugly-Number/313.Super-Ugly-Number_dp_pq.cpp @@ -1,30 +1,33 @@ -typedef pair PII; +using LL = long long; +typedef pair PII; class Solution { public: int nthSuperUglyNumber(int n, vector& primes) { - vectorp(primes.size(),0); - - vectorrets({1}); - priority_queue, greater<>>pq; - for (int i=0; irets({1}); + vectorp(k, 0); + + priority_queue, greater<>>pq; + for (int i=0; i Date: Thu, 4 Aug 2022 23:48:56 -0700 Subject: [PATCH 1083/2729] Create Readme.md --- Others/2359.Find-Closest-Node-to-Given-Two-Nodes/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/2359.Find-Closest-Node-to-Given-Two-Nodes/Readme.md diff --git a/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/Readme.md b/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/Readme.md new file mode 100644 index 000000000..d29c2e425 --- /dev/null +++ b/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/Readme.md @@ -0,0 +1,3 @@ +### 2359.Find-Closest-Node-to-Given-Two-Nodes + +本题就是直观的模拟。我们只要遍历所有的节点,查看它到node1的距离与它到node2的距离即可。那么这两个距离怎么求呢?我们事实上只要从node1开始无脑走一遍,就可以得到任意节点i到node1的距离dist1[i],同理也可以得到任意节点到node2的距离dist2[i]。我们把这两个距离数组都保存下来,再遍历所有的i,求出最小的`max{dist1[i], dist2[i]}`即可。 From 2c7d2e14285c78c8698aeb5654c7c97bf755c14b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 00:10:56 -0700 Subject: [PATCH 1084/2729] Create 2360.Longest-Cycle-in-a-Graph.cpp --- .../2360.Longest-Cycle-in-a-Graph.cpp | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Graph/2360.Longest-Cycle-in-a-Graph/2360.Longest-Cycle-in-a-Graph.cpp diff --git a/Graph/2360.Longest-Cycle-in-a-Graph/2360.Longest-Cycle-in-a-Graph.cpp b/Graph/2360.Longest-Cycle-in-a-Graph/2360.Longest-Cycle-in-a-Graph.cpp new file mode 100644 index 000000000..a1cf9bde1 --- /dev/null +++ b/Graph/2360.Longest-Cycle-in-a-Graph/2360.Longest-Cycle-in-a-Graph.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + int longestCycle(vector& edges) + { + int n = edges.size(); + vectorindegree(n); + for (int i=0; ivisited(n); + queueq; + for (int i=0; i Date: Sat, 6 Aug 2022 00:11:31 -0700 Subject: [PATCH 1085/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 44b74dce3..c284143a5 100644 --- a/Readme.md +++ b/Readme.md @@ -969,6 +969,7 @@ [1719.Number-Of-Ways-To-Reconstruct-A-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1719.Number-Of-Ways-To-Reconstruct-A-Tree) (H+) [1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph) (M+) [1782.Count-Pairs-Of-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1782.Count-Pairs-Of-Nodes) (H) +[2360.Longest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2360.Longest-Cycle-in-a-Graph) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From fda8f4fe0d8fab7b5c317051218245e656b5cbf5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 00:27:54 -0700 Subject: [PATCH 1086/2729] Create Readme.md --- Graph/2360.Longest-Cycle-in-a-Graph/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Graph/2360.Longest-Cycle-in-a-Graph/Readme.md diff --git a/Graph/2360.Longest-Cycle-in-a-Graph/Readme.md b/Graph/2360.Longest-Cycle-in-a-Graph/Readme.md new file mode 100644 index 000000000..f108cb535 --- /dev/null +++ b/Graph/2360.Longest-Cycle-in-a-Graph/Readme.md @@ -0,0 +1,7 @@ +### 2360.Longest-Cycle-in-a-Graph + +因为每个节点最多只有一个出度,所以本质上图的表现形式就是,可能有若干个环,可能有若干单链,也可能有一些单链指向了环。但是不可能有单链从环上引出,否则那个节点上必然就有两个出度(一个继续指向环,另一个走出环)。 + +所以我们先用拓扑排序的方法,将入度为0的节点逐层剪除。剩下的必然就是一系列的环。我们从任何一个未访问过的节点出发,顺着指向的edge走下去,就能遍历完这个环。再找下一个未访问的节点,就又开始遍历一个环。最终我们就可以找到长度最大的环。 + +`2127.Maximum-Employees-to-Be-Invited-to-a-Meeting`是本题的升级版。 From 921fb91fd7420771954a78b7f615f3e3462133b9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 12:59:24 -0700 Subject: [PATCH 1087/2729] Create 2365.Task-Scheduler-II.cpp --- .../2365.Task-Scheduler-II.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Greedy/2365.Task-Scheduler-II/2365.Task-Scheduler-II.cpp diff --git a/Greedy/2365.Task-Scheduler-II/2365.Task-Scheduler-II.cpp b/Greedy/2365.Task-Scheduler-II/2365.Task-Scheduler-II.cpp new file mode 100644 index 000000000..866371460 --- /dev/null +++ b/Greedy/2365.Task-Scheduler-II/2365.Task-Scheduler-II.cpp @@ -0,0 +1,18 @@ +using LL = long long; +class Solution { +public: + long long taskSchedulerII(vector& tasks, int space) + { + int n = tasks.size(); + unordered_mapMap; + LL cur = 0; + for (int i=0; i Date: Sat, 6 Aug 2022 13:03:53 -0700 Subject: [PATCH 1088/2729] Create Readme.md --- Greedy/2365.Task-Scheduler-II/Readme.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 Greedy/2365.Task-Scheduler-II/Readme.md diff --git a/Greedy/2365.Task-Scheduler-II/Readme.md b/Greedy/2365.Task-Scheduler-II/Readme.md new file mode 100644 index 000000000..e61609fc9 --- /dev/null +++ b/Greedy/2365.Task-Scheduler-II/Readme.md @@ -0,0 +1,4 @@ +### 2365.Task-Scheduler-II +此题与`Task-Scheduler-I`最大的区别在于所有的任务执行的顺序已经给定了。假设当前需要执行的任务是A,那么现在能否执行A的唯一条件,就是任务A是否有冷冻期。如果有有冷冻期,那么我们就需要推迟到冷冻期结束之后的第一天执行(如果冷冻期的结束日期比当前晚的话)。那么冷冻期的结束日期是怎么确定的呢?那就是上次执行A的时候就可以确定的。 + +所以我们只需要要维护一个哈希表time,来记录每个任务的冷冻期结束日期。每完成一个任务,就更新它的冷冻期结束日期,这样今后遇到相同任务时,就可以知道可以开工的时间。如果当前任务没有冷冻结期束日期,那么就可以在当天去执行。 From 6d438899fb8aaaf64d691e048c219ab867959107 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 13:06:47 -0700 Subject: [PATCH 1089/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c284143a5..aa23d44e2 100644 --- a/Readme.md +++ b/Readme.md @@ -1119,6 +1119,7 @@ [2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K) (H-) [2332.The-Latest-Time-to-Catch-a-Bus](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2332.The-Latest-Time-to-Catch-a-Bus) (H-) [2350.Shortest-Impossible-Sequence-of-Rolls](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls) (M+) +[2365.Task-Scheduler-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2365.Task-Scheduler-II) (M) * ``Smear Top Elements`` [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) From 05051e5e5d664095defc4ffecff8c168833b9846 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 13:47:17 -0700 Subject: [PATCH 1090/2729] Create 2366.Minimum-Replacements-to-Sort-the-Array.cpp --- ...Minimum-Replacements-to-Sort-the-Array.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Greedy/2366.Minimum-Replacements-to-Sort-the-Array/2366.Minimum-Replacements-to-Sort-the-Array.cpp diff --git a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/2366.Minimum-Replacements-to-Sort-the-Array.cpp b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/2366.Minimum-Replacements-to-Sort-the-Array.cpp new file mode 100644 index 000000000..a51cda631 --- /dev/null +++ b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/2366.Minimum-Replacements-to-Sort-the-Array.cpp @@ -0,0 +1,41 @@ +using LL = long long; +class Solution { +public: + long long minimumReplacement(vector& nums) + { + LL ret = 0; + for (int i = nums.size()-2; i>=0; i--) + { + LL x = nums[i+1]; + LL y = nums[i]; + if (y<=x) continue; + + LL k = y/x; + LL d = y%x; + if (d==0) + { + ret += k-1; + nums[i] = x; + continue; + } + + // d + k*p <= x - p + LL p = (x-d) / (k+1); + + LL x2 = x - p; + LL d2 = d + k*p; + + if (d2 < x2) + { + nums[i] = x2-1; + } + else + { + nums[i] = d2; + } + ret += k; + } + + return ret; + } +}; From 5ac2e008e450267583296954c4639ef871536cad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 13:47:49 -0700 Subject: [PATCH 1091/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index aa23d44e2..6c8d7e599 100644 --- a/Readme.md +++ b/Readme.md @@ -1120,6 +1120,7 @@ [2332.The-Latest-Time-to-Catch-a-Bus](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2332.The-Latest-Time-to-Catch-a-Bus) (H-) [2350.Shortest-Impossible-Sequence-of-Rolls](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls) (M+) [2365.Task-Scheduler-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2365.Task-Scheduler-II) (M) +[2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) * ``Smear Top Elements`` [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) From 62477d37be4ef8d3001ae66a39deabe66f96e2bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 13:59:16 -0700 Subject: [PATCH 1092/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md diff --git a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md new file mode 100644 index 000000000..181a44b10 --- /dev/null +++ b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md @@ -0,0 +1,9 @@ +### 2366.Minimum-Replacements-to-Sort-the-Array + +我们从后往前看,对于最后一个数,我们肯定不会拆分。一旦将其拆分的话变小的话,那么前面的数就有更大的概率需要拆得更小。 + +接着假设最后一个数是x,倒数第二个数是y。如果y小于等于x,那么最后两个元素已经是递增关系,y就不用拆分了,理由同上。如果y大于x,那么就必须拆分y,那么怎么拆分呢? + +根据规则,我们想要尽量少地拆分,又不能拆出大于x的数(否则破坏递增),不难通过贪心的思想,知道我们需要尽量拆出x来。假设y除以x的商是k,余数是d,那么我们有一个初始方案:就是拆成一个d,加上k个x。这一定保证了拆分数最少。但是d太小的话,会影响左侧元素迫使他们拆分地更细。所以我们试图在不改变这k+1份的前提下,尽量地抬升d。怎么抬升呢?显然是由这k个x来提供帮助。如果这k个x集体减少一,那么d就能抬升k。为什么这k个x需要集体行动呢?因为人多力量大啊,让某些x不出力的话留着也没有啥用,不如提供给d来加速d的抬升。 + +那么我们将d抬升多少呢?注意提升后的d不能比下降后的x高。因为我们想抬升d是因为d是当前y拆分出来的最小值,是制约前面元素拆分的“瓶颈”。所以最理想的情况是y恰好拆分成均匀的k份。 From 6e356f427edabb08fa21f9a799d72371d6707194 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 15:15:50 -0700 Subject: [PATCH 1093/2729] Update Readme.md --- .../Readme.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md index 181a44b10..6ad7847fb 100644 --- a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md +++ b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md @@ -4,6 +4,20 @@ 接着假设最后一个数是x,倒数第二个数是y。如果y小于等于x,那么最后两个元素已经是递增关系,y就不用拆分了,理由同上。如果y大于x,那么就必须拆分y,那么怎么拆分呢? -根据规则,我们想要尽量少地拆分,又不能拆出大于x的数(否则破坏递增),不难通过贪心的思想,知道我们需要尽量拆出x来。假设y除以x的商是k,余数是d,那么我们有一个初始方案:就是拆成一个d,加上k个x。这一定保证了拆分数最少。但是d太小的话,会影响左侧元素迫使他们拆分地更细。所以我们试图在不改变这k+1份的前提下,尽量地抬升d。怎么抬升呢?显然是由这k个x来提供帮助。如果这k个x集体减少一,那么d就能抬升k。为什么这k个x需要集体行动呢?因为人多力量大啊,让某些x不出力的话留着也没有啥用,不如提供给d来加速d的抬升。 +根据规则,我们想要尽量少地拆分,又不能拆出大于x的数(否则破坏递增),不难通过贪心的思想,知道我们需要尽量拆出完整的x来。假设y除以x的商是k,余数是d,那么我们有一个初始方案:就是拆成一个d,加上k个x。这一定保证了拆分的数目最少。但是d太小的话,会影响左侧元素迫使他们拆分地更细。所以我们试图在不改变这k+1拆份的前提下,尽量地抬升d。怎么抬升呢?显然是由这k个x来提供帮助。如果这k个x集体减少一,那么d就能抬升k。为什么这k个x需要集体行动呢?因为人多力量大啊,让某些x不出力的话留着也没有啥用,不如提供给d来加速d的抬升。 -那么我们将d抬升多少呢?注意提升后的d不能比下降后的x高。因为我们想抬升d是因为d是当前y拆分出来的最小值,是制约前面元素拆分的“瓶颈”。所以最理想的情况是y恰好拆分成均匀的k份。 +那么我们将d抬升多少呢?注意提升后的d不能比下降后的x高。因为我们想抬升d是因为d是当前y拆分出来的最小值,是制约前面元素拆分的“瓶颈”。所以最理想的情况是将y恰好拆分成均匀的k份。如果不行,那么我们就将d抬升至小于等于降低后的x。令所有的x降低p,则有比等式 +``` +d + p*k <= x - p +``` +这样得到 +``` +p <= (x-d) / (k+1) +``` +意思是p不能再大了,再大的话d要反超x了。 + +这样操作之后,原本的1个d和k个x,变成了1个d2和k个x2,其中`d2 = d + p`,`x2 = x - p`,且`d2 <= x2`. + +此时这是不是最优的操作呢?并不是。如果`d2 < x2`,其实我们可以将k个x2里面的一部分(而不是整体)拿出1来再贡献给d2,必然可以使得d2再拉至于x2-1平齐的高度。这是因为之前我们知道,如果k个x2每人都再贡献1出来,会导致`d2`会比`x2-1`还大。所以这意味着,如果贡献出部分的1出来,就能让`d2`与`x2-1`持平。在这种情况下,`x2-1`就是拆分出来的k+1份里的最小值。 + +于是,这个回合结束我们将nums[i]赋值为`x2`(如果`d2==x2`)或者`x2-1`(如果`d2 Date: Sat, 6 Aug 2022 23:49:55 -0700 Subject: [PATCH 1094/2729] Update 2277.Closest-Node-to-Path-in-Tree.cpp --- .../2277.Closest-Node-to-Path-in-Tree.cpp | 71 ++++++++++--------- 1 file changed, 36 insertions(+), 35 deletions(-) diff --git a/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp b/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp index e9b49915f..9c7753a92 100644 --- a/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp +++ b/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp @@ -1,5 +1,5 @@ class Solution { - vector nxt[1005]; + vectornext[1005]; int matrix[1005][1005]; public: vector closestNode(int n, vector>& edges, vector>& query) @@ -7,54 +7,55 @@ class Solution { for (auto& edge: edges) { int a = edge[0], b = edge[1]; - nxt[a].push_back(b); - nxt[b].push_back(a); + next[a].push_back(b); + next[b].push_back(a); } for (int i=0; irets; for (auto& q: query) { - int start = q[0], end = q[1], node = q[2]; + int start = q[0], end = q[1], node = q[2]; int dist = INT_MAX; int ret; - solve(start, end, node, dist, ret); - rets.push_back(ret); - } - return rets; - } - - void dfs(int start, int cur, int dist) - { - for (int j: nxt[cur]) - { - if (j!=start && matrix[start][j]==0) + + int cur = start; + while (1) { - matrix[start][j] = dist+1; - dfs(start, j, dist+1); - } + if (matrix[cur][node] < dist) + { + dist = matrix[cur][node]; + ret = cur; + } + if (cur==end) break; + + for (int j: next[cur]) + { + if (matrix[cur][end]==matrix[j][end]+1) + { + cur = j; + break; + } + } + } + rets.push_back(ret); } + + return rets; + } - void solve(int cur, int end, int node, int & dist, int& ret) + void dfs(int root, int cur, int dist) { - if (matrix[cur][node] < dist) - { - dist = matrix[cur][node]; - ret = cur; - } - - for (int j: nxt[cur]) + for (int j: next[cur]) { - if (matrix[cur][end]==matrix[j][end]+1) - { - solve(j, end, node, dist, ret); - break; - } + if (j!=root && matrix[root][j]==0) + { + matrix[root][j] = dist+1; + dfs(root, j, dist+1); + } } } - - }; From 3f1381bf10663a97974223806530f92a188afd06 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 23:52:13 -0700 Subject: [PATCH 1095/2729] Create 2370.Longest-Ideal-Subsequence.cpp --- .../2370.Longest-Ideal-Subsequence.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence.cpp diff --git a/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence.cpp b/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence.cpp new file mode 100644 index 000000000..6b9bdd931 --- /dev/null +++ b/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int longestIdealString(string s, int k) + { + int n = s.size(); + s = "#"+s; + vectorprev(26, 0); + vectordp(n+1,1); + dp[0] = 0; + + int ret = 0; + for (int i=1; i<=n; i++) + { + for (int j=max(0,s[i]-'a'-k); j<=min(25, s[i]-'a'+k); j++) + { + int p = prev[j]; + dp[i] = max(dp[i], dp[p]+1); + } + prev[s[i]-'a'] = i; + ret = max(ret, dp[i]); + } + + return ret; + } +}; From f77ff849e858e4281c8059c18d7b0865e7a51def Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Aug 2022 23:52:52 -0700 Subject: [PATCH 1096/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6c8d7e599..0728bb177 100644 --- a/Readme.md +++ b/Readme.md @@ -1154,6 +1154,7 @@ [792.Number-of-Matching-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/792.Number-of-Matching-Subsequences) (H-) [1055.Shortest-Way-to-Form-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1055.Shortest-Way-to-Form-String) (M+) [2055.Plates-Between-Candles](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2055.Plates-Between-Candles) (M+) +[2370.Longest-Ideal-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2370.Longest-Ideal-Subsequence) (M) * ``Sort`` 164.Maximum-Gap (H) [179.Largest-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/179.Largest-Number) (H-) From 89c3ffd7e85f3a4f3e73e0b98b79922e542c2b5e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Aug 2022 00:33:43 -0700 Subject: [PATCH 1097/2729] Create Readme.md --- Greedy/2370.Longest-Ideal-Subsequence/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2370.Longest-Ideal-Subsequence/Readme.md diff --git a/Greedy/2370.Longest-Ideal-Subsequence/Readme.md b/Greedy/2370.Longest-Ideal-Subsequence/Readme.md new file mode 100644 index 000000000..bd5594ce6 --- /dev/null +++ b/Greedy/2370.Longest-Ideal-Subsequence/Readme.md @@ -0,0 +1,7 @@ +### 2370.Longest-Ideal-Subsequence + +本题是常规的动态规划。令dp[i]表示以i为结尾的最长subsequence的长度。我们需要寻找这个subsequence的上一个位置j,这样就有`dp[i]=dp[j]+1`。那么j可以是在哪里呢?根据题意,j所在的字母必须是与s[i]的ASCII差距在k以内的字母。在知道是哪些字母后,于是我们需要维护一个长度为26的数组`prev[ch]`,表示当前位置i之前最近的字母ch出现在哪个位置。 + +举个例子,如果当前s[i]='b',且k=1。那么我们就需要查看这两处位置`j1 = prev['a']`和`j2 = prev['c]`,这样就可以有`dp[i] = max(dp[j1], dp[j2]) + 1`. 特别注意,对于任意的dp[i]都有一个基本解是`dp[i] = 1`. + +最终的答案是返回在全局`dp[i]`中最大的一个。 From e538eb51034360986250ea43263fa7f04307672e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 10 Aug 2022 18:34:19 -0700 Subject: [PATCH 1098/2729] Update Readme.md --- Others/2281.Sum-of-Total-Strength-of-Wizards/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2281.Sum-of-Total-Strength-of-Wizards/Readme.md b/Others/2281.Sum-of-Total-Strength-of-Wizards/Readme.md index 79a422d31..58991c6e0 100644 --- a/Others/2281.Sum-of-Total-Strength-of-Wizards/Readme.md +++ b/Others/2281.Sum-of-Total-Strength-of-Wizards/Readme.md @@ -1,4 +1,4 @@ -### 6077.Sum-of-Total-Strength-of-Wizards +### 2281.Sum-of-Total-Strength-of-Wizards 根据套路,我们不会去枚举所有的subarray再找其中的weakest。相反,我们遍历每个元素将其作为weakest,再找对应的subarray。 From 43de226996660857f4a30107a421bf3a7fb08337 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 07:46:04 -0700 Subject: [PATCH 1099/2729] Create 357.Count-Numbers-with-Unique-Digits.cpp --- .../357.Count-Numbers-with-Unique-Digits.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Others/357.Count-Numbers-with-Unique-Digits/357.Count-Numbers-with-Unique-Digits.cpp diff --git a/Others/357.Count-Numbers-with-Unique-Digits/357.Count-Numbers-with-Unique-Digits.cpp b/Others/357.Count-Numbers-with-Unique-Digits/357.Count-Numbers-with-Unique-Digits.cpp new file mode 100644 index 000000000..063b3287e --- /dev/null +++ b/Others/357.Count-Numbers-with-Unique-Digits/357.Count-Numbers-with-Unique-Digits.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int countNumbersWithUniqueDigits(int n) + { + if (n==0) return 1; + int ret = 1; + for (int len = 1; len <= n; len++) + ret += A(10, len) - A(9,len-1); + return ret; + } + + int A(int m, int n) + { + int ret = 1; + for (int i=0; i Date: Sun, 14 Aug 2022 07:46:58 -0700 Subject: [PATCH 1100/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 0728bb177..286f3dd41 100644 --- a/Readme.md +++ b/Readme.md @@ -1315,6 +1315,8 @@ [347.Top-K-Frequent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/347.Top-K-Frequent-Elements) (M+) [973.K-Closest-Points-to-Origin](https://github.com/wisdompeak/LeetCode/tree/master/Others/973.K-Closest-Points-to-Origin) (M) [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) +* ``数位计算`` +[357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M+) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From dfa5c526a643cabbd5a58d74748634cfc718c818 Mon Sep 17 00:00:00 2001 From: kken Date: Sun, 14 Aug 2022 22:52:14 +0800 Subject: [PATCH 1101/2729] Rename 781.Rabbits-in-Forest.cpp. to 781.Rabbits-in-Forest.cpp --- .../{781.Rabbits-in-Forest.cpp. => 781.Rabbits-in-Forest.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/781.Rabbits-in-Forest/{781.Rabbits-in-Forest.cpp. => 781.Rabbits-in-Forest.cpp} (100%) diff --git a/Greedy/781.Rabbits-in-Forest/781.Rabbits-in-Forest.cpp. b/Greedy/781.Rabbits-in-Forest/781.Rabbits-in-Forest.cpp similarity index 100% rename from Greedy/781.Rabbits-in-Forest/781.Rabbits-in-Forest.cpp. rename to Greedy/781.Rabbits-in-Forest/781.Rabbits-in-Forest.cpp From b51eba70b39225abd815d7c056db79c0c3583937 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 07:57:24 -0700 Subject: [PATCH 1102/2729] Create Readme.md --- Others/357.Count-Numbers-with-Unique-Digits/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/357.Count-Numbers-with-Unique-Digits/Readme.md diff --git a/Others/357.Count-Numbers-with-Unique-Digits/Readme.md b/Others/357.Count-Numbers-with-Unique-Digits/Readme.md new file mode 100644 index 000000000..becd49c8b --- /dev/null +++ b/Others/357.Count-Numbers-with-Unique-Digits/Readme.md @@ -0,0 +1,7 @@ +### 357.Count-Numbers-with-Unique-Digits + +本题长度不超过n的数字里有多少是所有digit都不同的。 + +对于长度固定为n的数字,就是在10个不同的digit里(从0到9)里选n个随意排列即可。也就是A(10,n)。但是注意到不能有leading zero,所以必须刨去其中以0开头的排列,这些有A(9,n-1)个。故答案是`A(10,n)-A(9,n-1)`. + +特别注意,需要单独考虑0。长度为1的数字里是允许leading zero的。 From b3683735dbf4138e446a8de7396b91991c388f5d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 08:19:19 -0700 Subject: [PATCH 1103/2729] Create 2376.Count-Special-Integers.cpp --- .../2376.Count-Special-Integers.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Others/2376.Count-Special-Integers/2376.Count-Special-Integers.cpp diff --git a/Others/2376.Count-Special-Integers/2376.Count-Special-Integers.cpp b/Others/2376.Count-Special-Integers/2376.Count-Special-Integers.cpp new file mode 100644 index 000000000..d7a946fac --- /dev/null +++ b/Others/2376.Count-Special-Integers/2376.Count-Special-Integers.cpp @@ -0,0 +1,50 @@ +class Solution { + int ret = 0; +public: + int countSpecialNumbers(int N) + { + string s = to_string(N); + int n = s.size(); + + for (int len=1; len<=n-1; len++) + ret += A(10, len) - A(9, len-1); + + vectorvisited(10); + dfs(s, 0, visited); + + return ret; + } + + void dfs(string&s, int i, vector&visited) + { + int n = s.size(); + if (i>=n) + { + ret++; + return; + } + + for (int d=0; d<=9; d++) + { + if (d==0 && i==0) continue; + if (visited[d] == 1) continue; + if (d < s[i]-'0') + ret += A(10-i-1, n-1-i); + else if (d == s[i]-'0') + { + visited[d] = 1; + dfs(s, i+1, visited); + visited[d] = 0; + } + } + } + + int A(int m, int k) + { + if (k==0) return 1; + int ret = 1; + for (int i=0; i Date: Sun, 14 Aug 2022 08:25:52 -0700 Subject: [PATCH 1104/2729] Create Readme.md --- Others/2376.Count-Special-Integers/Readme.md | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Others/2376.Count-Special-Integers/Readme.md diff --git a/Others/2376.Count-Special-Integers/Readme.md b/Others/2376.Count-Special-Integers/Readme.md new file mode 100644 index 000000000..a5ac1f98d --- /dev/null +++ b/Others/2376.Count-Special-Integers/Readme.md @@ -0,0 +1,22 @@ +### 2376.Count-Special-Integers + +本题本质和`1012.Numbers-With-Repeated-Digits`,完全一致。如果本题的答案是`X`,那么`N-X`就是1012的答案。 + +基本思路就是递归和数学方法相结合。我们从高到低穷举每一位的digit的可能。如果当前构造的高位数字已经注定比N小,那么剩下的排列方法就是一个组合数计算。如果当前构造的高位数字和N是一样的,那么就递归处理下一位。 + +大致的思路是: +```cpp +void dfs(string s, int i) // 处理s的第i位 +{ + for (int d = 0; d <= 9; d++) { + if (visited[d]) continue; + if (d < s[i]) + ret += Permuation(未使用的数字个数,未填充的位数); + else if (d == s[i]) + { + visited[d] = 1; + dfs(s, i); + } + } +} +``` From 2a85004a900e4bbaab91d804c3be06497d5d5a3a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 08:27:01 -0700 Subject: [PATCH 1105/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 286f3dd41..234a132c0 100644 --- a/Readme.md +++ b/Readme.md @@ -991,7 +991,6 @@ [963.Minimum-Area-Rectangle-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/963.Minimum-Area-Rectangle-II) (H-) [964.Least-Operators-to-Express-Number](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/964.Least-Operators-to-Express-Number) (H) [972.Equal-Rational-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Math/972.Equal-Rational-Numbers) (H) -[1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [1017.Convert-to-Base--2](https://github.com/wisdompeak/LeetCode/tree/master/Math/1017.Convert-to-Base--2) (M+) [1073.Adding-Two-Negabinary-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Math/1073.Adding-Two-Negabinary-Numbers) (H-) [1025.Divisor-Game](https://github.com/wisdompeak/LeetCode/tree/master/Math/1025.Divisor-Game) (M) @@ -1316,7 +1315,9 @@ [973.K-Closest-Points-to-Origin](https://github.com/wisdompeak/LeetCode/tree/master/Others/973.K-Closest-Points-to-Origin) (M) [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` -[357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M+) +[357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) +[2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) +[1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From 0299bc81dbd4a5ecd2fd3e9fdd2c00623ca9764c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 09:46:37 -0700 Subject: [PATCH 1106/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 234a132c0..2ea2f5a98 100644 --- a/Readme.md +++ b/Readme.md @@ -976,7 +976,6 @@ #### [Math](https://github.com/wisdompeak/LeetCode/tree/master/Math) [089.Gray-Code](https://github.com/wisdompeak/LeetCode/tree/master/Math/089.Gray-Code) (M+) (aka. 1238. Circular Permutation in Binary Representation) -[233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) 458.Poor-Pigs (H) [400.n-th-digit](https://github.com/wisdompeak/LeetCode/tree/master/Math/400.n-th-digit) (M) [441.Arranging-Coins](https://github.com/wisdompeak/LeetCode/tree/master/Math/441.Arranging-Coins) (M-) @@ -1315,6 +1314,7 @@ [973.K-Closest-Points-to-Origin](https://github.com/wisdompeak/LeetCode/tree/master/Others/973.K-Closest-Points-to-Origin) (M) [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` +[233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) From b6b53705eccd3fa4f22314c6710d857b878ee368 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 10:30:59 -0700 Subject: [PATCH 1107/2729] Update Readme.md --- Math/233.Number-of-Digit-One/Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Math/233.Number-of-Digit-One/Readme.md b/Math/233.Number-of-Digit-One/Readme.md index 27aa4842a..948dbd30d 100644 --- a/Math/233.Number-of-Digit-One/Readme.md +++ b/Math/233.Number-of-Digit-One/Readme.md @@ -16,5 +16,6 @@ c. 如果Y<1,那么最低两位如论取什么,都会导致这个数大于n 综合整理上述的分类讨论方案,可以将它适用于任何一个数位(个位、十位、千位、万位...),将这些数的统计全部加起来就是答案。 +此题和`1067. Digit Count in Range`非常相似。 -[Leetcode Link](https://leetcode.com/problems/number-of-digit-one) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/number-of-digit-one) From 6f1076b2056f3493dd41d0b30dda6ec7df8765f1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 10:32:04 -0700 Subject: [PATCH 1108/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2ea2f5a98..db25ba9ed 100644 --- a/Readme.md +++ b/Readme.md @@ -1235,7 +1235,6 @@ 918.Maximum-Sum-Circular-Subarray (H-) [927.Three-Equal-Parts](https://github.com/wisdompeak/LeetCode/tree/master/Others/927.Three-Equal-Parts) (M) [978.Longest-Turbulent-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Others/978.Longest-Turbulent-Subarray) (H-) -1067.Digit-Count-in-Range (H) 1183.Maximum-Number-of-Ones (H) [1267.Count-Servers-that-Communicate](https://github.com/wisdompeak/LeetCode/tree/master/Others/1267.Count-Servers-that-Communicate) (M+) [1538.Guess-the-Majority-in-a-Hidden-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1538.Guess-the-Majority-in-a-Hidden-Array) (M+) @@ -1315,6 +1314,7 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) +[1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) From c7ffb4eacc45686e8cdb453f68cc719c08851245 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 23:30:56 -0700 Subject: [PATCH 1109/2729] Delete 992.Subarrays-with-K-Different-Integers_v2.cpp --- ...Subarrays-with-K-Different-Integers_v2.cpp | 25 ------------------- 1 file changed, 25 deletions(-) delete mode 100644 Two_Pointers/992.Subarrays-with-K-Different-Integers/992.Subarrays-with-K-Different-Integers_v2.cpp diff --git a/Two_Pointers/992.Subarrays-with-K-Different-Integers/992.Subarrays-with-K-Different-Integers_v2.cpp b/Two_Pointers/992.Subarrays-with-K-Different-Integers/992.Subarrays-with-K-Different-Integers_v2.cpp deleted file mode 100644 index 66a2d8827..000000000 --- a/Two_Pointers/992.Subarrays-with-K-Different-Integers/992.Subarrays-with-K-Different-Integers_v2.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - int lengthOfLongestSubstringKDistinct(string s, int k) - { - vectorfreq(256,0); - int count = 0; - int i = 0; - int ret = 0; - for (int j=0; jk) - { - freq[s[i]]--; - if (freq[s[i]]==0) - count--; - i++; - } - ret = max(ret, j-i+1); - } - return ret; - } -}; From 982bca4b16383adf3a613cecd1c706c6c8eed10a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Aug 2022 23:33:33 -0700 Subject: [PATCH 1110/2729] Update Readme.md --- .../Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/Readme.md b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/Readme.md index 82a8f045c..23e2d1e94 100644 --- a/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/Readme.md +++ b/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path/Readme.md @@ -8,4 +8,6 @@ dp[i][j]的前驱状态有两个,dp[i-1][j]和dp[i][j-1]. 假设前驱状态 特别地,如果dp[i][j]的前驱状态的集合是空集,那么意味着无论如何,从起点到(i,j)都不会有合法的路径,故dp[i][j]也必须赋值为空集。 +另外,本题有一个剪枝的技巧。因为路径的步长是固定,当我们走完一定步数之后,发现剩下未走的步数就算都看做是右括号,也无法抵消当前剩余的左括号的话,那么注定这条路径是不能成功的,就可以提前终止。 + 最终的答案就是查看dp[m-1][n-1]这个集合是否包含零元素。 From 7625358d751de8ffaecec8ac92f2d5d0f67bb983 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Aug 2022 22:31:20 -0700 Subject: [PATCH 1111/2729] Update Readme.md --- Others/1067.Digit-Count-in-Range/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Others/1067.Digit-Count-in-Range/Readme.md b/Others/1067.Digit-Count-in-Range/Readme.md index 3e8913225..d9c523707 100644 --- a/Others/1067.Digit-Count-in-Range/Readme.md +++ b/Others/1067.Digit-Count-in-Range/Readme.md @@ -1,8 +1,8 @@ ### 1067.Digit-Count-in-Range -如果digit不是0的话,代码完全类似于 233. Number of Digit One +如果digit不是0的话,代码完全类似于`233. Number of Digit One`,用一个helper函数计算[1,n]的数字d的出现次数,然后返回`helper(high)-helper(low-1)`. -基本思想就是逐个位数的考虑,计算出现digit的次数。比如说num=2452,digit=4 +233的基本思想就是逐个位数的考虑,计算出现digit的次数。比如说num=2452,digit=4 考虑个位时,就是计算出现XXX1的次数。如果XXX是从000到234,显然都是必然可行的。如果XXX是235的话,因为个位数是2小于4,所以不可以。因此count+=235*1; @@ -19,4 +19,4 @@ 如果digit是0的话,唯一的区别在于第一条。d前面的数字只能从1取至(XX-1),这样的话YY可以取任何数字(00-99),所以出现d的次数是 ```(XX-1)*pow(10,i-1)```.至于XX为什么不能取00呢?因为XX如果取00,接下来的第i位也是0,那么这些都是leading zeros,计算第i位的0出现的次数是没有意义的。 -[Leetcode Link](https://leetcode.com/problems/digit-count-in-range) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/digit-count-in-range) From 2a7ff0c67acb1615803397ef07954e12159191ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Aug 2022 22:39:24 -0700 Subject: [PATCH 1112/2729] Update 1067.Digit-Count-in-Range.cpp --- .../1067.Digit-Count-in-Range.cpp | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp b/Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp index afdb5568a..8466d9b6e 100644 --- a/Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp +++ b/Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp @@ -1,27 +1,29 @@ class Solution { public: int digitsCount(int d, int low, int high) - { + { + return helper(d, high)-helper(d,low-1); } - int helper(int digit, int x) + int helper(int d, int n) { - int len = to_string(x).size(); + string s = to_string(n); + int len = s.size(); int count = 0; - if (digit!=0) + if (d!=0) { for (int i=1; i<=len; i++) { int divisor = pow(10,i); - count += x/divisor * pow(10,i-1); + count += n/divisor * pow(10,i-1); - int y = (x - x/divisor*divisor)/pow(10,i-1); - if (y > digit) + int y = s[len-i]-'0'; + if (y > d) count += pow(10,i-1); - else if (y==digit) - count += (x%(int)(pow(10,i-1)))+1; + else if (y==d) + count += n%(int)(pow(10,i-1)) + 1; } } else @@ -29,13 +31,13 @@ class Solution { for (int i=1; i digit) + int y = s[len-i]-'0'; + if (y > d) count += pow(10,i-1); - else if (y==digit) - count += (x%(int)(pow(10,i-1)))+1; + else if (y==d) + count += n%(int)(pow(10,i-1)) + 1; } } From ec80c57b616c43f295e05d35d6e8f33159d2326e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Aug 2022 22:39:34 -0700 Subject: [PATCH 1113/2729] Update 1067.Digit-Count-in-Range.cpp --- Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp b/Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp index 8466d9b6e..12faf5681 100644 --- a/Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp +++ b/Others/1067.Digit-Count-in-Range/1067.Digit-Count-in-Range.cpp @@ -1,8 +1,7 @@ class Solution { public: int digitsCount(int d, int low, int high) - { - + { return helper(d, high)-helper(d,low-1); } From 0930dddbe076f142fd6ed38c7f8394c4131ccd48 Mon Sep 17 00:00:00 2001 From: Xiao Sun Date: Sat, 20 Aug 2022 16:20:26 -0400 Subject: [PATCH 1114/2729] Update 325.Maximum Size Subarray Sum Equals k.cpp Preventing overflow in new added OJ cases. --- .../325.Maximum Size Subarray Sum Equals k.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Hash/325.Maximum-Size-Subarray-Sum-Equals-k/325.Maximum Size Subarray Sum Equals k.cpp b/Hash/325.Maximum-Size-Subarray-Sum-Equals-k/325.Maximum Size Subarray Sum Equals k.cpp index f13801e30..d119311fe 100644 --- a/Hash/325.Maximum-Size-Subarray-Sum-Equals-k/325.Maximum Size Subarray Sum Equals k.cpp +++ b/Hash/325.Maximum-Size-Subarray-Sum-Equals-k/325.Maximum Size Subarray Sum Equals k.cpp @@ -2,8 +2,8 @@ class Solution { public: int maxSubArrayLen(vector& nums, int k) { - unordered_map>Map; - int sum=0; + unordered_map>Map; + long sum=0; int result=INT_MIN; nums.insert(nums.begin(),0); From 8fa8c832f4a70878619c19c7bc2a06ae815a62ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Aug 2022 15:51:11 -0700 Subject: [PATCH 1115/2729] Create 2382.Maximum-Segment-Sum-After-Removals.cpp --- ...382.Maximum-Segment-Sum-After-Removals.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp b/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp new file mode 100644 index 000000000..2d6efb5c4 --- /dev/null +++ b/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp @@ -0,0 +1,46 @@ +using LL = long long; +class Solution { +public: + vector maximumSegmentSum(vector& nums, vector& removeQueries) + { + int n = nums.size(); + mapMap; + multisetSet; + Map[0] = n-1; + vectorpresum(n); + for (int i=0; irets; + + for (int t: removeQueries) + { + auto iter = Map.upper_bound(t); + iter = prev(iter); + int start = iter->first; + int end = iter->second; + + Map.erase(start); + LL sum = presum[end] - (start==0 ? 0:presum[start-1]); + Set.erase(Set.lower_bound(sum)); + + if (t-1>=start) + { + Map[start] = t-1; + Set.insert(presum[t-1] - (start==0?0:presum[start-1])); + } + + if (t+1 <= end) + { + Map[t+1] = end; + Set.insert(presum[end] - (t+1==0 ? 0:presum[t+1-1])); + } + + LL ret = Set.empty() ? 0 : *prev(Set.end()); + rets.push_back(ret); + } + + return rets; + } +}; From 2e023de7d11476f7f973cdd2fcebcdf5ea5e7fbe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Aug 2022 16:19:54 -0700 Subject: [PATCH 1116/2729] Update 2382.Maximum-Segment-Sum-After-Removals.cpp --- ...382.Maximum-Segment-Sum-After-Removals.cpp | 36 ++++++++++--------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp b/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp index 2d6efb5c4..a91a537b3 100644 --- a/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp +++ b/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp @@ -4,43 +4,47 @@ class Solution { vector maximumSegmentSum(vector& nums, vector& removeQueries) { int n = nums.size(); - mapMap; - multisetSet; - Map[0] = n-1; + mapMap; // start->end + multisetSet; // segment sum + vectorpresum(n); for (int i=0; irets; for (int t: removeQueries) - { + { auto iter = Map.upper_bound(t); iter = prev(iter); + int start = iter->first; - int end = iter->second; - + int end = iter->second; + Map.erase(start); - LL sum = presum[end] - (start==0 ? 0:presum[start-1]); + LL sum = presum[end] - (start==0?0:presum[start-1]); Set.erase(Set.lower_bound(sum)); - - if (t-1>=start) + + if (start <= t-1) { Map[start] = t-1; - Set.insert(presum[t-1] - (start==0?0:presum[start-1])); + Set.insert(presum[t-1] - (start==0?0:presum[start-1])); } - + if (t+1 <= end) { - Map[t+1] = end; - Set.insert(presum[end] - (t+1==0 ? 0:presum[t+1-1])); - } + Map[t+1] = end; + Set.insert(presum[end] - (t+1==0?0:presum[t+1-1])); + } - LL ret = Set.empty() ? 0 : *prev(Set.end()); + LL ret = Set.empty()? 0: (*Set.rbegin()); rets.push_back(ret); } - return rets; + return rets; + } }; From 1a0f1791685609d37b1d417121917d8e57c4fc1a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Aug 2022 16:20:33 -0700 Subject: [PATCH 1117/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index db25ba9ed..8986ee06c 100644 --- a/Readme.md +++ b/Readme.md @@ -189,6 +189,7 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) +[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) From b5b6a5f37fdf2484356ef5bb84d11870514c48db Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Aug 2022 19:23:54 -0700 Subject: [PATCH 1118/2729] Create Readme.md --- Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md b/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md new file mode 100644 index 000000000..aac07bd62 --- /dev/null +++ b/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md @@ -0,0 +1,5 @@ +### 2382.Maximum-Segment-Sum-After-Removals + +我们用一个有序Map来维护当前存在的segments,其中key是起点,val是终点。另外我们在用一个有序的multiset来维护当前存在的segment sum。 + +每次我们考虑一个分割点t,根据题意,它必然存在一个segment里。可以在Map里找到这个segment,记做[start,end]。我们只需要将这个segment从Map中移出,将这个segment sum从Set里移出。再将新生成的两个新区间(如果存在的话)放入Map和Set里即可。每次qeury之后,可以从Set里直接读出当前的最大值。 From 1b775cb496fd2028c62d997d3d2ad6e1850d55ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Aug 2022 19:24:08 -0700 Subject: [PATCH 1119/2729] Update Readme.md --- Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md b/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md index aac07bd62..2a2bec3ec 100644 --- a/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md +++ b/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md @@ -2,4 +2,4 @@ 我们用一个有序Map来维护当前存在的segments,其中key是起点,val是终点。另外我们在用一个有序的multiset来维护当前存在的segment sum。 -每次我们考虑一个分割点t,根据题意,它必然存在一个segment里。可以在Map里找到这个segment,记做[start,end]。我们只需要将这个segment从Map中移出,将这个segment sum从Set里移出。再将新生成的两个新区间(如果存在的话)放入Map和Set里即可。每次qeury之后,可以从Set里直接读出当前的最大值。 +每次我们考虑一个分割点t,根据题意,它必然存在一个segment里。可以在Map里找到这个segment,记做[start,end]。我们只需要将这个segment从Map中移出,将这个segment sum从Set里移出。再将新生成的两个新区间(如果存在的话)放入Map和Set里即可。每次query之后,可以从Set里直接读出当前的最大值。 From 8565a801b52342bca83d198ecd206c51e14b8dfd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Aug 2022 19:25:09 -0700 Subject: [PATCH 1120/2729] Update Readme.md --- Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md b/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md index 2a2bec3ec..749dc9310 100644 --- a/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md +++ b/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md @@ -2,4 +2,4 @@ 我们用一个有序Map来维护当前存在的segments,其中key是起点,val是终点。另外我们在用一个有序的multiset来维护当前存在的segment sum。 -每次我们考虑一个分割点t,根据题意,它必然存在一个segment里。可以在Map里找到这个segment,记做[start,end]。我们只需要将这个segment从Map中移出,将这个segment sum从Set里移出。再将新生成的两个新区间(如果存在的话)放入Map和Set里即可。每次query之后,可以从Set里直接读出当前的最大值。 +每次我们考虑一个分割点t,根据题意,它必然存在一个segment里。可以用upper_bound在Map里找到这个segment,记做[start,end]。我们只需要将这个segment从Map中移出,并将对应的segment sum从Set里移出。再将新生成的两个新区间(如果存在的话)和各自的区间和放入Map和Set里即可。每次query之后,可以从Set里直接读出当前的最大值。 From 5882d8e71493fe9d589aa29b5bd6824fd49ca6ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Aug 2022 20:32:24 -0700 Subject: [PATCH 1121/2729] Create 2381.Shifting-Letters-II.cpp --- .../2381.Shifting-Letters-II.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Others/2381.Shifting-Letters-II/2381.Shifting-Letters-II.cpp diff --git a/Others/2381.Shifting-Letters-II/2381.Shifting-Letters-II.cpp b/Others/2381.Shifting-Letters-II/2381.Shifting-Letters-II.cpp new file mode 100644 index 000000000..5343e69f3 --- /dev/null +++ b/Others/2381.Shifting-Letters-II/2381.Shifting-Letters-II.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + string shiftingLetters(string s, vector>& shifts) + { + int n = s.size(); + vectordiff(n+1); + for (auto& shift: shifts) + { + int start = shift[0], end = shift[1], dir = shift[2]; + int d = (dir==0)? -1:1; + diff[start]+=d; + diff[end+1]-=d; + } + + int cur = 0; + string ret; + for (int i=0; i Date: Sat, 20 Aug 2022 20:33:00 -0700 Subject: [PATCH 1122/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8986ee06c..15cc8c428 100644 --- a/Readme.md +++ b/Readme.md @@ -1286,6 +1286,7 @@ [2237.Count-Positions-on-Street-With-Required-Brightness](https://github.com/wisdompeak/LeetCode/tree/master/Others/2237.Count-Positions-on-Street-With-Required-Brightness) (M) [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) [2327.Number-of-People-Aware-of-a-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Others/2327.Number-of-People-Aware-of-a-Secret) (H-) +[2381.Shifting-Letters-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/2381.Shifting-Letters-II) (M) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From cdeb824483ed40eedb3da05a76be61282919c9a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Aug 2022 20:41:16 -0700 Subject: [PATCH 1123/2729] Create Readme.md --- Others/2381.Shifting-Letters-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2381.Shifting-Letters-II/Readme.md diff --git a/Others/2381.Shifting-Letters-II/Readme.md b/Others/2381.Shifting-Letters-II/Readme.md new file mode 100644 index 000000000..918e90459 --- /dev/null +++ b/Others/2381.Shifting-Letters-II/Readme.md @@ -0,0 +1,5 @@ +### 2381.Shifting-Letters-II + +这是一道非常明显考察差分数组的题目。我们维护一个差分数组diff[i]表示从i开始之后的每一个元素将如何变化。如果对于区间[a,b]内的字符都要增1,那么我们只需要记```diff[a]+=1, diff[b+1]-=1```.我们将所有的区间都用diff处理之后,再从前往后计算diff的前缀和,所得的`delta[i] = sum(diff[0:i])`就是表示第i个字符最终累积要增加(或者减少)的数目。 + +特别注意,presum_diff[i]可能非常大,需要对26取余,并且我们需要保证是正数,且`s[i]+delta[i]`要折算到[0,25]之内。 From 1bef3e1f1f18ecccab58c804bd59978af6bb7448 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 23 Aug 2022 23:42:33 -0700 Subject: [PATCH 1124/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 15cc8c428..c23b7c2b0 100644 --- a/Readme.md +++ b/Readme.md @@ -225,7 +225,6 @@ 558.Quad-Tree-Intersection (M+) [662.Maximum-Width-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/662.Maximum-Width-of-Binary-Tree) (H-) 742.Closest-Leaf-in-a-Binary-Tree (H) -834.Sum-of-Distances-in-Tree (H) [863.All-Nodes-Distance-K-in-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/863.All-Nodes-Distance-K-in-Binary-Tree) (H-) [958.Check-Completeness-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/blob/master/Tree/954.Check-Completeness-of-a-Binary-Tree/) (M+) 1339. Maximum-Product-of-Splitted-Binary-Tree (TBD) @@ -272,6 +271,8 @@ [428.Serialize-and-Deserialize-N-ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/428.Serialize-and-Deserialize-N-ary-Tree) (H) [431.Encode-N-ary-Tree-to-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/431.Encode-N-ary-Tree-to-Binary-Tree) (H-) [1516.Move-Sub-Tree-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1516.Move-Sub-Tree-of-N-Ary-Tree) (H-) +* ``Re-Root`` +[834.Sum-of-Distances-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/834.Sum-of-Distances-in-Tree) (H) * ``似树非树`` [823](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/823.Binary-Trees-With-Factors), [1902](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order), From 98744fbc4313f0c90f3ebd3bcd7c91d094de26a8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 25 Aug 2022 22:07:14 -0700 Subject: [PATCH 1125/2729] Update 834.Sum-of-Distances-in-Tree.cpp --- .../834.Sum-of-Distances-in-Tree.cpp | 107 ++++++++---------- 1 file changed, 50 insertions(+), 57 deletions(-) diff --git a/Tree/834.Sum-of-Distances-in-Tree/834.Sum-of-Distances-in-Tree.cpp b/Tree/834.Sum-of-Distances-in-Tree/834.Sum-of-Distances-in-Tree.cpp index 28153a953..61d19f686 100644 --- a/Tree/834.Sum-of-Distances-in-Tree/834.Sum-of-Distances-in-Tree.cpp +++ b/Tree/834.Sum-of-Distances-in-Tree/834.Sum-of-Distances-in-Tree.cpp @@ -1,75 +1,68 @@ class Solution { - unordered_map>Children; - vectorSubLeaves; - vectorresults; - + int visited[30005]; + int count[30005]; + vector next[30005]; + vector rets; + int n; public: - vector sumOfDistancesInTree(int N, vector>& edges) + vector sumOfDistancesInTree(int n, vector>& edges) { - SubLeaves.assign(N,0); - results.assign(N,0); - - unordered_map>Map; - for (int i=0; in = n; + rets.resize(n); + for (auto& edge: edges) { - Map[edges[i][0]].insert(edges[i][1]); - Map[edges[i][1]].insert(edges[i][0]); + next[edge[0]].push_back(edge[1]); + next[edge[1]].push_back(edge[0]); } - - queueq; - q.push(0); - while (!q.empty()) - { - int root = q.front(); - q.pop(); - for (auto child:Map[root]) - { - Children[root].insert(child); - Map[child].erase(root); - q.push(child); - } - } - - int root = 0; - int temp = DFS1(root); - int AllSum = DFS2(root); - - results[0] = AllSum; - DFS3(root); - - return results; + + visited[0] = 1; + dfs(0); // Compute the substree sizes + + for (int i=1; i Date: Thu, 25 Aug 2022 22:16:16 -0700 Subject: [PATCH 1126/2729] Update Readme.md --- Tree/834.Sum-of-Distances-in-Tree/Readme.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Tree/834.Sum-of-Distances-in-Tree/Readme.md b/Tree/834.Sum-of-Distances-in-Tree/Readme.md index c59ab515b..e6ce756f8 100644 --- a/Tree/834.Sum-of-Distances-in-Tree/Readme.md +++ b/Tree/834.Sum-of-Distances-in-Tree/Readme.md @@ -2,17 +2,18 @@ 首先回顾一下关于图论的几个概念。树是图的一种,是指没有回路的连通图。对于这种图,任意一个节点都可以当做root从而展开为一棵直观意义上的树。 -本题也是如此,我们可以任意选取一个节点定义为root,然后可以用BFS建立起一个Hash表来代表传统意义上树结构里parent->child的连接关系(注意,因为是树,反向的关系我们不记录在Hash表里)。 +本题中我们可以任意选取一个节点定义为root(比如说0号节点),然后可以用DFS遍历整棵树,可以得到两个信息:每个节点所对应的子树的节点个数(记做count[i]),所有节点到根(0号节点)的距离之和。 -然后我们可以做什么呢?比较容易用递归办到的,就是root到所有子节点的距离之和,标记为f(root)。那么接下来,如何得到一个子节点child到其他所有节点的距离之和呢?难道要以该节点为根重新展开一张树吗?其实我们可以考虑f(parent)和f(child)之间的关系。 +那么接下来,如何得到一个非根节点到其他所有节点的距离之和呢?难道要以该节点为根重新展开一张树吗?这里介绍一种非常常见的“移根”的思想。 -假设已知f(parent),如果我们把起点从parent迁到child的话,那么到所有除child子树之外的节点,距离都增加了1;到所有child子树的节点,距离都减少了1. +我们令f(node)该节点到所有节点的距离之和。假设已知f(parent),我们可以考虑f(parent)和它的一个f(child)之间的关系。我们把根从parent迁到child之后,所有属于child子树的节点离根的距离都减少了1。剩余的其他所有节点,其到根的距离都增加了1. 所以有如下的关系 ``` -f(child) = f(parent)+(除child子树之外所有节点的数目)-(child子树的节点数目) +f(child) = f(parent) - (child子树的节点数目) + (N - child子树的节点数目) ``` 可见,所有的f都可以自上而下通过递归得到。 +类似的思想有一个更常见的题目:求一个数组里每个节点到其他节点的距离之和。如1685,2121. -[Leetcode Link](https://leetcode.com/problems/sum-of-distances-in-tree) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/sum-of-distances-in-tree) From de83a52868e01ed0dd097cfa0b21f3ad6b2a322e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 27 Aug 2022 09:25:03 -0700 Subject: [PATCH 1127/2729] Update range_sum.cpp --- Template/SegmentTree/range_sum.cpp | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/Template/SegmentTree/range_sum.cpp b/Template/SegmentTree/range_sum.cpp index 7e7ad95fe..468288302 100644 --- a/Template/SegmentTree/range_sum.cpp +++ b/Template/SegmentTree/range_sum.cpp @@ -6,11 +6,13 @@ class SegTreeNode SegTreeNode* right = NULL; int start, end; LL info; // the sum value over the range - bool tag; + bool lazy_tag; + LL lazy_val; SegTreeNode(int a, int b, int val) // init for range [a,b] with val { - tag = 0; + lazy_tag = 0; + lazy_val = 0; start = a, end = b; if (a==b) { @@ -28,13 +30,13 @@ class SegTreeNode void pushDown() { - if (tag==1 && left) + if (lazy_tag==1 && left) { - left->info = info; - right->info = info; - left->tag = 1; - right->tag = 1; - tag = 0; + left->info = lazy_val * (left->end - left->start + 1); + right->info = lazy_val * (right->end - right->start + 1); + left->lazy_tag = 1; left->lazy_val = lazy_val; + right->lazy_tag = 1; right->lazy_val = lazy_val; + lazy_tag = 0; lazy_val = 0; } } @@ -45,7 +47,8 @@ class SegTreeNode if (a <= start && end <=b) // completely covered within [a,b] { info = val * (end-start+1); - tag = 1; + lazy_tag = 1; + lazy_val = val; return; } From a062446e58264af6dd0fb39d47c4330a33f25820 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 27 Aug 2022 09:26:09 -0700 Subject: [PATCH 1128/2729] Update 2286.Booking-Concert-Tickets-in-Groups.cpp --- ...2286.Booking-Concert-Tickets-in-Groups.cpp | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp index daec800cc..f5656a2eb 100644 --- a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp +++ b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp @@ -88,15 +88,17 @@ class SegTreeNode class SegTreeNode2 { public: - SegTreeNode2* left = NULL; - SegTreeNode2* right = NULL; + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; int start, end; LL info; // the sum value over the range - bool tag; + bool lazy_tag; + LL lazy_val; - SegTreeNode2(int a, int b, int val) // init for range [a,b] with val + SegTreeNode(int a, int b, int val) // init for range [a,b] with val { - tag = 0; + lazy_tag = 0; + lazy_val = 0; start = a, end = b; if (a==b) { @@ -106,21 +108,21 @@ class SegTreeNode2 int mid = (a+b)/2; if (left==NULL) { - left = new SegTreeNode2(a, mid, val); - right = new SegTreeNode2(mid+1, b, val); + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); info = left->info + right->info; // check with your own logic } } void pushDown() { - if (tag==1 && left) + if (lazy_tag==1 && left) { - left->info = info; - right->info = info; - left->tag = 1; - right->tag = 1; - tag = 0; + left->info = lazy_val * (left->end - left->start + 1); + right->info = lazy_val * (right->end - right->start + 1); + left->lazy_tag = 1; left->lazy_val = lazy_val; + right->lazy_tag = 1; right->lazy_val = lazy_val; + lazy_tag = 0; lazy_val = 0; } } @@ -131,7 +133,8 @@ class SegTreeNode2 if (a <= start && end <=b) // completely covered within [a,b] { info = val * (end-start+1); - tag = 1; + lazy_tag = 1; + lazy_val = val; return; } @@ -144,7 +147,7 @@ class SegTreeNode2 } } - LL queryRange(int a, int b) // query the maximum value within range [a,b] + LL queryRange(int a, int b) // query the sum over range [a,b] { if (b < start || a > end ) { @@ -165,7 +168,6 @@ class SegTreeNode2 return info; // should not reach here } - }; class BookMyShow { From 2d51c718a60dfd2d5b4901116925e1090e8a3504 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 27 Aug 2022 09:27:40 -0700 Subject: [PATCH 1129/2729] Update 2286.Booking-Concert-Tickets-in-Groups.cpp --- .../2286.Booking-Concert-Tickets-in-Groups.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp index f5656a2eb..5d05b6f14 100644 --- a/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp +++ b/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups/2286.Booking-Concert-Tickets-in-Groups.cpp @@ -88,14 +88,14 @@ class SegTreeNode class SegTreeNode2 { public: - SegTreeNode* left = NULL; - SegTreeNode* right = NULL; + SegTreeNode2* left = NULL; + SegTreeNode2* right = NULL; int start, end; LL info; // the sum value over the range bool lazy_tag; LL lazy_val; - SegTreeNode(int a, int b, int val) // init for range [a,b] with val + SegTreeNode2(int a, int b, int val) // init for range [a,b] with val { lazy_tag = 0; lazy_val = 0; @@ -108,8 +108,8 @@ class SegTreeNode2 int mid = (a+b)/2; if (left==NULL) { - left = new SegTreeNode(a, mid, val); - right = new SegTreeNode(mid+1, b, val); + left = new SegTreeNode2(a, mid, val); + right = new SegTreeNode2(mid+1, b, val); info = left->info + right->info; // check with your own logic } } From 068920fadbc31cf28cfbd3086f8563ad26ad7e3d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 27 Aug 2022 10:01:29 -0700 Subject: [PATCH 1130/2729] Create 2380.Time-Needed-to-Rearrange-a-Binary-String.cpp --- ...Time-Needed-to-Rearrange-a-Binary-String.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Others/2380.Time-Needed-to-Rearrange-a-Binary-String/2380.Time-Needed-to-Rearrange-a-Binary-String.cpp diff --git a/Others/2380.Time-Needed-to-Rearrange-a-Binary-String/2380.Time-Needed-to-Rearrange-a-Binary-String.cpp b/Others/2380.Time-Needed-to-Rearrange-a-Binary-String/2380.Time-Needed-to-Rearrange-a-Binary-String.cpp new file mode 100644 index 000000000..c161a9219 --- /dev/null +++ b/Others/2380.Time-Needed-to-Rearrange-a-Binary-String/2380.Time-Needed-to-Rearrange-a-Binary-String.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int secondsToRemoveOccurrences(string s) + { + int n = s.size(); + int ret = 0; + int count = 0; + for (int i=0; i 0) + ret = max(ret+1, count); + } + return ret; + } +}; From ee843957f272ceb08848ed233bf486c0e81b684d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 27 Aug 2022 10:07:29 -0700 Subject: [PATCH 1131/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c23b7c2b0..50c297aae 100644 --- a/Readme.md +++ b/Readme.md @@ -1252,6 +1252,7 @@ [2147.Number-of-Ways-to-Divide-a-Long-Corridor](https://github.com/wisdompeak/LeetCode/tree/master/Others/2147.Number-of-Ways-to-Divide-a-Long-Corridor) (M) [2337.Move-Pieces-to-Obtain-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2337.Move-Pieces-to-Obtain-a-String) (aka. 777.Swap-Adjacent-in-LR-String) (M+) [2359.Find-Closest-Node-to-Given-Two-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2359.Find-Closest-Node-to-Given-Two-Nodes) (M) +[2380.Time-Needed-to-Rearrange-a-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2380.Time-Needed-to-Rearrange-a-Binary-String) (H) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 7f131ba31f8fa3e95a1b0173cfb3b02527356d29 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 27 Aug 2022 10:12:45 -0700 Subject: [PATCH 1132/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/2380.Time-Needed-to-Rearrange-a-Binary-String/Readme.md diff --git a/Others/2380.Time-Needed-to-Rearrange-a-Binary-String/Readme.md b/Others/2380.Time-Needed-to-Rearrange-a-Binary-String/Readme.md new file mode 100644 index 000000000..f78aca7dc --- /dev/null +++ b/Others/2380.Time-Needed-to-Rearrange-a-Binary-String/Readme.md @@ -0,0 +1,9 @@ +### 2380.Time-Needed-to-Rearrange-a-Binary-String + +本题的o(N)解法有着非常高的思维难度。 + +对于任何一个1而言,它的任何一次移动意味着超越了它之前的一个0.因为最终这个1要超越所有它之前的0,假设这些0的数目是count,那么说明这个1最少要移动count次。 + +但是这个1极有可能会被前面的1所阻挡。一旦这个1的前进过程被阻挡到,那么意味着从此后,它的前进只能在前一个1移动一步之后再进行。也就是说,如果前一个1移动了x次到达期待位置,这一个1只能在第x+1步之后才能到达期待位置(也就是前一个1的后一个位置)。所以最终的答案是`max(x+1,count)` + +由此我们可以从前一个1的答案递归出下一个1的答案。最终答案就是最后一个1需要多少步移动到期待位置。 From e8531a184c065b1f76aec2ba77ead4260ed40c47 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 09:33:46 -0700 Subject: [PATCH 1133/2729] Create 2392.Build-a-Matrix-With-Conditions.cpp --- .../2392.Build-a-Matrix-With-Conditions.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 BFS/2392.Build-a-Matrix-With-Conditions/2392.Build-a-Matrix-With-Conditions.cpp diff --git a/BFS/2392.Build-a-Matrix-With-Conditions/2392.Build-a-Matrix-With-Conditions.cpp b/BFS/2392.Build-a-Matrix-With-Conditions/2392.Build-a-Matrix-With-Conditions.cpp new file mode 100644 index 000000000..0029321aa --- /dev/null +++ b/BFS/2392.Build-a-Matrix-With-Conditions/2392.Build-a-Matrix-With-Conditions.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + vectortopo(int k, vector>& conditions) + { + vectorindegree(k+1); + vector>next(k+1); + for (auto& x: conditions) + { + next[x[0]].push_back(x[1]); + indegree[x[1]] += 1; + } + + queueq; + for (int i=1; i<=k; i++) + if (indegree[i]==0) + q.push(i); + + vectorrets; + while (!q.empty()) + { + int cur = q.front(); + q.pop(); + rets.push_back(cur); + for (auto x: next[cur]) + { + indegree[x]--; + if (indegree[x]==0) + q.push(x); + } + } + + if (rets.size() != k) return {}; + + return rets; + } + + vector> buildMatrix(int k, vector>& rowConditions, vector>& colConditions) + { + vectorrow = topo(k, rowConditions); + vectorcol = topo(k, colConditions); + + if (row.empty() || col.empty()) return {}; + + vector>pos(k+1); + for (int i=0; i>matrix(k, vector(k)); + for (int i=1; i<=k; i++) + matrix[pos[i].first][pos[i].second] = i; + + return matrix; + + } +}; From 721dfb13f10a1607f3aef412678f5288e4d133bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 09:34:16 -0700 Subject: [PATCH 1134/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 50c297aae..92a1d9b3f 100644 --- a/Readme.md +++ b/Readme.md @@ -525,6 +525,7 @@ [2127.Maximum-Employees-to-Be-Invited-to-a-Meeting](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2127.Maximum-Employees-to-Be-Invited-to-a-Meeting) (H) [2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph) (M) [2204.Distance-to-a-Cycle-in-Undirected-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph) (M) +[2392.Build-a-Matrix-With-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2392.Build-a-Matrix-With-Conditions) (M+) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From 9bebf8e70e6f518b9a6da28c83eae171dc6d1f1e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 09:49:16 -0700 Subject: [PATCH 1135/2729] Create Readme.md --- BFS/2392.Build-a-Matrix-With-Conditions/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 BFS/2392.Build-a-Matrix-With-Conditions/Readme.md diff --git a/BFS/2392.Build-a-Matrix-With-Conditions/Readme.md b/BFS/2392.Build-a-Matrix-With-Conditions/Readme.md new file mode 100644 index 000000000..19edfa0a8 --- /dev/null +++ b/BFS/2392.Build-a-Matrix-With-Conditions/Readme.md @@ -0,0 +1,7 @@ +### 2392.Build-a-Matrix-With-Conditions + +因为本题只需要在k by k的方阵中填写k个数字,所以我们可以让所有数字都不同行不同列。这样横向的拓扑关系和纵向的拓扑关系可以独立处理,互不干扰。 + +比如说,我们从横向的关系得到必须从左往右填写 a,b,c,d,再从纵向的关系得到必须从上往下填写b,d,c,a,那么我们就可以令a的纵坐标是0,横坐标是3. 以此类推。 + +特别注意,如果想用尽量小的的矩阵来填写k个数字,那么此题难度会很大。比如,如果横向的拓扑关系是a,b,c必须在d的左边,这个时候我们就需要考虑a,b,c是否可以在同一列:但是这一列是否可以装下这么多元素?如果装不下,我们在这一列选填那几个? From 9be7b683a0edd55ef2aa5c080831e23c629a4232 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 09:58:00 -0700 Subject: [PATCH 1136/2729] Update Readme.md --- BFS/2392.Build-a-Matrix-With-Conditions/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BFS/2392.Build-a-Matrix-With-Conditions/Readme.md b/BFS/2392.Build-a-Matrix-With-Conditions/Readme.md index 19edfa0a8..c3ac372e2 100644 --- a/BFS/2392.Build-a-Matrix-With-Conditions/Readme.md +++ b/BFS/2392.Build-a-Matrix-With-Conditions/Readme.md @@ -4,4 +4,4 @@ 比如说,我们从横向的关系得到必须从左往右填写 a,b,c,d,再从纵向的关系得到必须从上往下填写b,d,c,a,那么我们就可以令a的纵坐标是0,横坐标是3. 以此类推。 -特别注意,如果想用尽量小的的矩阵来填写k个数字,那么此题难度会很大。比如,如果横向的拓扑关系是a,b,c必须在d的左边,这个时候我们就需要考虑a,b,c是否可以在同一列:但是这一列是否可以装下这么多元素?如果装不下,我们在这一列选填那几个? +特别注意,如果想用尽量小的的矩阵来填写k个数字,或者填写数字的个数大于矩阵的维度,那么此题难度会很大。比如,如果横向的拓扑关系是a,b,c必须在d的左边,这个时候我们就需要考虑a,b,c是否可以在同一列:但是这一列是否可以装下这么多元素?如果装不下,我们在这一列选填那几个? From 505b760c0c1f79f3d5bd56103f784b1a4f959255 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 14:58:40 -0700 Subject: [PATCH 1137/2729] =?UTF-8?q?Create=202375.Construct-Smallest-Numb?= =?UTF-8?q?er-From-DI-String=E3=80=812375.Construct-Smallest-Number-From-D?= =?UTF-8?q?I-String.cpp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...struct-Smallest-Number-From-DI-String.cpp" | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 "Greedy/2375.Construct-Smallest-Number-From-DI-String\343\200\2012375.Construct-Smallest-Number-From-DI-String.cpp" diff --git "a/Greedy/2375.Construct-Smallest-Number-From-DI-String\343\200\2012375.Construct-Smallest-Number-From-DI-String.cpp" "b/Greedy/2375.Construct-Smallest-Number-From-DI-String\343\200\2012375.Construct-Smallest-Number-From-DI-String.cpp" new file mode 100644 index 000000000..f36f32496 --- /dev/null +++ "b/Greedy/2375.Construct-Smallest-Number-From-DI-String\343\200\2012375.Construct-Smallest-Number-From-DI-String.cpp" @@ -0,0 +1,38 @@ +class Solution { +public: + string smallestNumber(string pattern) + { + pattern = "I" + pattern; + int n = pattern.size(); + vectorarr; + int mx = 0; + + for (int i=0; i=mx+1; k--) + arr.push_back(k); + + mx = mx+count; + + i = j-1; + } + + int mn = INT_MAX; + for (int i=0; i Date: Sun, 28 Aug 2022 15:00:21 -0700 Subject: [PATCH 1138/2729] =?UTF-8?q?Rename=20Greedy/2375.Construct-Smalle?= =?UTF-8?q?st-Number-From-DI-String=E3=80=812375.Construct-Smallest-Number?= =?UTF-8?q?-From-DI-String.cpp=20to=20Greedy/2375.Construct-Smallest-Numbe?= =?UTF-8?q?r-From-DI-String/2375.Construct-Smallest-Number-From-DI-String.?= =?UTF-8?q?cpp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2375.Construct-Smallest-Number-From-DI-String.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename "Greedy/2375.Construct-Smallest-Number-From-DI-String\343\200\2012375.Construct-Smallest-Number-From-DI-String.cpp" => Greedy/2375.Construct-Smallest-Number-From-DI-String/2375.Construct-Smallest-Number-From-DI-String.cpp (100%) diff --git "a/Greedy/2375.Construct-Smallest-Number-From-DI-String\343\200\2012375.Construct-Smallest-Number-From-DI-String.cpp" b/Greedy/2375.Construct-Smallest-Number-From-DI-String/2375.Construct-Smallest-Number-From-DI-String.cpp similarity index 100% rename from "Greedy/2375.Construct-Smallest-Number-From-DI-String\343\200\2012375.Construct-Smallest-Number-From-DI-String.cpp" rename to Greedy/2375.Construct-Smallest-Number-From-DI-String/2375.Construct-Smallest-Number-From-DI-String.cpp From 34b3413baf6c2533f36293317ae8a17654ea006a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 15:01:17 -0700 Subject: [PATCH 1139/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 92a1d9b3f..7f39e816d 100644 --- a/Readme.md +++ b/Readme.md @@ -1122,6 +1122,8 @@ [2350.Shortest-Impossible-Sequence-of-Rolls](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls) (M+) [2365.Task-Scheduler-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2365.Task-Scheduler-II) (M) [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) +* ``DI Sequence`` +[2375.Construct-Smallest-Number-From-DI-String](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/2375.Construct-Smallest-Number-From-DI-String) (M) * ``Smear Top Elements`` [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) From e23f1449f163429d16dde9b8cdab5b972e0eb96d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 15:16:01 -0700 Subject: [PATCH 1140/2729] Create Readme.md --- .../2375.Construct-Smallest-Number-From-DI-String/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md diff --git a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md new file mode 100644 index 000000000..253c665fc --- /dev/null +++ b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md @@ -0,0 +1,5 @@ +### 2375.Construct-Smallest-Number-From-DI-String + +首先我们知道,必须将尽量小的字符放在前面使用。 + +我们将pattern前加上一个“I”,这样pattern的长度就与字符串相等。我们发现,将每个“IDD...D”视作一个section,那么后一个section必然要完全高于前一个section。我们先暂时令第一个字符是0,然后把整个字符串的相对走势都表达出来后,再令最低点是'1',其余位置的字符相应抬高即可。 From 79c929c8b8c462bc4f144c3f1a0cdb8cb3e3f61a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 15:46:49 -0700 Subject: [PATCH 1141/2729] Update 2375.Construct-Smallest-Number-From-DI-String.cpp --- ...nstruct-Smallest-Number-From-DI-String.cpp | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/Greedy/2375.Construct-Smallest-Number-From-DI-String/2375.Construct-Smallest-Number-From-DI-String.cpp b/Greedy/2375.Construct-Smallest-Number-From-DI-String/2375.Construct-Smallest-Number-From-DI-String.cpp index f36f32496..197a61eaf 100644 --- a/Greedy/2375.Construct-Smallest-Number-From-DI-String/2375.Construct-Smallest-Number-From-DI-String.cpp +++ b/Greedy/2375.Construct-Smallest-Number-From-DI-String/2375.Construct-Smallest-Number-From-DI-String.cpp @@ -4,8 +4,9 @@ class Solution { { pattern = "I" + pattern; int n = pattern.size(); - vectorarr; + int mx = 0; + vectorarr; for (int i=0; i=mx+1; k--) + + for (int k= mx+count; k>=mx+1; k--) arr.push_back(k); mx = mx+count; - i = j-1; - } - - int mn = INT_MAX; - for (int i=0; i Date: Sun, 28 Aug 2022 15:47:26 -0700 Subject: [PATCH 1142/2729] Update Readme.md --- Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md index 253c665fc..5d85ff917 100644 --- a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md +++ b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md @@ -2,4 +2,4 @@ 首先我们知道,必须将尽量小的字符放在前面使用。 -我们将pattern前加上一个“I”,这样pattern的长度就与字符串相等。我们发现,将每个“IDD...D”视作一个section,那么后一个section必然要完全高于前一个section。我们先暂时令第一个字符是0,然后把整个字符串的相对走势都表达出来后,再令最低点是'1',其余位置的字符相应抬高即可。 +我们将pattern前加上一个“I”,这样pattern的长度就与字符串相等。我们发现,将每个“IDD...D”视作一个section,那么后一个section必然要完全高于前一个section。我们虚拟地令当前的最大字符是0,然后把整个字符串的相对走势都表达出来后,其余位置的字符相应抬高即可。 From 183b9e24c2dbbb623f6c1523d1c2bec2dfa06930 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 15:48:20 -0700 Subject: [PATCH 1143/2729] Update Readme.md --- Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md index 5d85ff917..3468e97c4 100644 --- a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md +++ b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md @@ -2,4 +2,4 @@ 首先我们知道,必须将尽量小的字符放在前面使用。 -我们将pattern前加上一个“I”,这样pattern的长度就与字符串相等。我们发现,将每个“IDD...D”视作一个section,那么后一个section必然要完全高于前一个section。我们虚拟地令当前的最大字符是0,然后把整个字符串的相对走势都表达出来后,其余位置的字符相应抬高即可。 +我们将pattern前加上一个“I”,这样pattern的长度就与字符串相等。我们发现,将每个“IDD...D”视作一个section,那么后一个section必然要完全高于前一个section。我们虚拟地令当前的最大字符是0,然后把后续整个字符串的相对走势都表达出来后(必然都大于0),得到的就是用1~9组成的字典序最小的字符串。 From 9d660c2f6e520b66ba02c8825fab52f42e6febb4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 15:54:36 -0700 Subject: [PATCH 1144/2729] Create 942.DI-String-Match.cpp --- .../942.DI-String-Match.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Greedy/942.DI-String-Match/942.DI-String-Match.cpp diff --git a/Greedy/942.DI-String-Match/942.DI-String-Match.cpp b/Greedy/942.DI-String-Match/942.DI-String-Match.cpp new file mode 100644 index 000000000..4e85587ba --- /dev/null +++ b/Greedy/942.DI-String-Match/942.DI-String-Match.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector diStringMatch(string pattern) + { + pattern = "I" + pattern; + int n = pattern.size(); + + int mx = -1; + vectorarr; + + for (int i=0; i=mx+1; k--) + arr.push_back(k); + + mx = mx+count; + + i = j-1; + } + + return arr; + } +}; From ffb5b5f2ba0e5b6a1b458835eb1a5101ae083dcf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 15:55:03 -0700 Subject: [PATCH 1145/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7f39e816d..27f8ab9d2 100644 --- a/Readme.md +++ b/Readme.md @@ -1123,6 +1123,7 @@ [2365.Task-Scheduler-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2365.Task-Scheduler-II) (M) [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) * ``DI Sequence`` +[942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [2375.Construct-Smallest-Number-From-DI-String](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/2375.Construct-Smallest-Number-From-DI-String) (M) * ``Smear Top Elements`` [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) From 6c63277341da27fe02ca2f29f30933f5f7950fe7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 15:55:36 -0700 Subject: [PATCH 1146/2729] Update Readme.md --- Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md index 3468e97c4..c7c669ee3 100644 --- a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md +++ b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md @@ -3,3 +3,5 @@ 首先我们知道,必须将尽量小的字符放在前面使用。 我们将pattern前加上一个“I”,这样pattern的长度就与字符串相等。我们发现,将每个“IDD...D”视作一个section,那么后一个section必然要完全高于前一个section。我们虚拟地令当前的最大字符是0,然后把后续整个字符串的相对走势都表达出来后(必然都大于0),得到的就是用1~9组成的字典序最小的字符串。 + +注:本题就是`942. DI String Match`的follow-up From ff9a8427498697577872762380757ab4ed0ee7f7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 15:57:21 -0700 Subject: [PATCH 1147/2729] Create Readme.md --- Greedy/942.DI-String-Match/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/942.DI-String-Match/Readme.md diff --git a/Greedy/942.DI-String-Match/Readme.md b/Greedy/942.DI-String-Match/Readme.md new file mode 100644 index 000000000..b978dc449 --- /dev/null +++ b/Greedy/942.DI-String-Match/Readme.md @@ -0,0 +1,5 @@ +### 942.DI-String-Match + +此题完全可以用`2375.Construct-Smallest-Number-From-DI-String`一样的方法,给出字典序最小的permutation。 + +基本思想是将s的开头加上一个“I”,将s切分为若干"IDD..D"的pattern,每个pattern对应的是一段单调递减的序列。保证序列与序列之间不重合即可。 From e18a4aa134bbe8520f179491a1c5e0a0dff53324 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 16:02:55 -0700 Subject: [PATCH 1148/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 27f8ab9d2..f4e4f798e 100644 --- a/Readme.md +++ b/Readme.md @@ -1124,7 +1124,7 @@ [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) -[2375.Construct-Smallest-Number-From-DI-String](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/2375.Construct-Smallest-Number-From-DI-String) (M) +[2375.Construct-Smallest-Number-From-DI-String](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/2375.Construct-Smallest-Number-From-DI-String) (aka. 484.Find-Permutation)(M) * ``Smear Top Elements`` [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) From e3b837559cdb8a497a9f98d953a5e85c553f3a18 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 16:03:52 -0700 Subject: [PATCH 1149/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index f4e4f798e..669177021 100644 --- a/Readme.md +++ b/Readme.md @@ -1063,7 +1063,6 @@ [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [659.Split-Array-into-Consecutive-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/659.Split-Array-into-Consecutive-Subsequences) (H) -[484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (H) [386.Lexicographical-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/386.Lexicographical-Numbers) (H) 624.Maximum-Distance-in-Arrays (M) [665.Non-decreasing-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/665.Non-decreasing-Array) (H) @@ -1124,7 +1123,8 @@ [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) -[2375.Construct-Smallest-Number-From-DI-String](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/2375.Construct-Smallest-Number-From-DI-String) (aka. 484.Find-Permutation)(M) +[484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) +[2375.Construct-Smallest-Number-From-DI-String](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/2375.Construct-Smallest-Number-From-DI-String) (M) * ``Smear Top Elements`` [2233.Maximum-Product-After-K-Increments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2233.Maximum-Product-After-K-Increments) (M+) [2333.Minimum-Sum-of-Squared-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2333.Minimum-Sum-of-Squared-Difference) (M+) From 5ddc8867e3be636517240b8a005f900f4082edba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 16:04:26 -0700 Subject: [PATCH 1150/2729] Update Readme.md --- Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md index c7c669ee3..b56ae9d3c 100644 --- a/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md +++ b/Greedy/2375.Construct-Smallest-Number-From-DI-String/Readme.md @@ -4,4 +4,4 @@ 我们将pattern前加上一个“I”,这样pattern的长度就与字符串相等。我们发现,将每个“IDD...D”视作一个section,那么后一个section必然要完全高于前一个section。我们虚拟地令当前的最大字符是0,然后把后续整个字符串的相对走势都表达出来后(必然都大于0),得到的就是用1~9组成的字典序最小的字符串。 -注:本题就是`942. DI String Match`的follow-up +注:本题是`942. DI String Match`的follow-up,并且和`484.Find-Permutation`一模一样 From fd4255622da58fd1445002b9869602ba979dd99b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 16:05:38 -0700 Subject: [PATCH 1151/2729] Update Readme.md --- Greedy/484.Find-Permutation/Readme.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Greedy/484.Find-Permutation/Readme.md b/Greedy/484.Find-Permutation/Readme.md index 1b973b5f4..0112a5f21 100644 --- a/Greedy/484.Find-Permutation/Readme.md +++ b/Greedy/484.Find-Permutation/Readme.md @@ -1,10 +1,7 @@ ### 484.Find-Permutation -需要人工分析出最优的策略。 +本题本质和`2375.Construct-Smallest-Number-From-DI-String`一模一样。 -以“下拐点”为分界点将s序列分为若干个II...IIDD...DD的组合。对于每个II...IIDD...DD,可以知道最优方法是:将除最后一个I之外的所有I对应一个递增数列,剩下的一个I和所有的D对应一个递减数列,且递减数列的最小值是那个递增数列最大值加1。更有用的是,可以知道,所有的递增数列的值都是和它的index值是对应的`results[i]=i+1`。 +基本思想是将s的开头加上一个“I”,将s切分为若干"IDD..D"的pattern,每个pattern对应的是一段单调递减的序列。保证序列与序列之间不重合即可。 -那么s的位数和results的位数不一样怎么办?一个简单的方法是`s.insert(s.begin(),s[0])`,这样s和results的元素数目就是一致的,且各个位置都适用同样的代码语句。 - - -[Leetcode Link](https://leetcode.com/problems/find-permutation) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/find-permutation) From adf2d4409740136d52978165f4930912dfe834e2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Aug 2022 16:06:00 -0700 Subject: [PATCH 1152/2729] Update 484.Find-Permutation.cpp --- .../484.Find-Permutation.cpp | 36 ++++++++----------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/Greedy/484.Find-Permutation/484.Find-Permutation.cpp b/Greedy/484.Find-Permutation/484.Find-Permutation.cpp index f6567cc9d..59a1e4beb 100644 --- a/Greedy/484.Find-Permutation/484.Find-Permutation.cpp +++ b/Greedy/484.Find-Permutation/484.Find-Permutation.cpp @@ -1,31 +1,25 @@ class Solution { public: - vector findPermutation(string s) + vector findPermutation(string pattern) { - s.insert(s.begin(),s[0]); - int N=s.size(); - vectorresults(N,0); + pattern = "I" + pattern; + int n = pattern.size(); - int left=0; - int right=0; + int mx = 0; + vectorarr; - while (right=mx+1; k--) + arr.push_back(k); + mx = mx+count; + i = j-1; } - return results; - + return arr; } }; From 47f20e54ed647a2918ae423e257b55c97553380f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Aug 2022 00:30:51 -0700 Subject: [PATCH 1153/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 669177021..879a10a5d 100644 --- a/Readme.md +++ b/Readme.md @@ -519,6 +519,7 @@ [1203.Sort-Items-by-Groups-Respecting-Dependencies](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1203.Sort-Items-by-Groups-Respecting-Dependencies) (H) [1462.Course-Schedule-IV](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1462.Course-Schedule-IV) (M) [1591.Strange-Printer-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1591.Strange-Printer-II) (H-) +[1632.Rank-Transform-of-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1632.Rank-Transform-of-a-Matrix) (H) [1857.Largest-Color-Value-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1857.Largest-Color-Value-in-a-Directed-Graph) (H-) [2050.Parallel-Courses-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2050.Parallel-Courses-III) (M+) [2115.Find-All-Possible-Recipes-from-Given-Supplies](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2115.Find-All-Possible-Recipes-from-Given-Supplies) (M) From d16412c690b8a66c1bb6a24da2b1a3c4c944cd9d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Aug 2022 00:49:46 -0700 Subject: [PATCH 1154/2729] Update 2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp --- ...istance-to-a-Cycle-in-Undirected-Graph.cpp | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp b/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp index a990c4739..12f143180 100644 --- a/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp +++ b/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph/2204.Distance-to-a-Cycle-in-Undirected-Graph.cpp @@ -23,19 +23,15 @@ class Solution { while (!q.empty()) { - int len = q.size(); - while (len--) + int cur = q.front(); + q.pop(); + rets[cur] = -1; + for (int nxt: next[cur]) { - int cur = q.front(); - q.pop(); - rets[cur] = -1; - for (int nxt: next[cur]) - { - degree[nxt]--; - if (degree[nxt]==1) - q.push(nxt); - } - } + degree[nxt]--; + if (degree[nxt]==1) + q.push(nxt); + } } while (!q.empty()) q.pop(); From cf7c1722e4c7feae62a3ffe25568dbac8a56245d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 Aug 2022 00:12:22 -0700 Subject: [PATCH 1155/2729] Update 2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp --- .../2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp b/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp index 36b4f7ca4..79f61561c 100644 --- a/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp +++ b/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet/2271.Maximum-White-Tiles-Covered-by-a-Carpet.cpp @@ -15,9 +15,12 @@ class Solution { { while (j= tiles[j][1]) j++; - int len = presum[j-1] - (i==0?0:presum[i-1]); + int len = 0; + if (j>i) + len += presum[j-1] - (i==0?0:presum[i-1]); if (j Date: Wed, 31 Aug 2022 23:54:28 -0700 Subject: [PATCH 1156/2729] Create 2386.Find-the-K-Sum-of-an-Array.cpp --- .../2386.Find-the-K-Sum-of-an-Array.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Priority_Queue/2386.Find-the-K-Sum-of-an-Array/2386.Find-the-K-Sum-of-an-Array.cpp diff --git a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/2386.Find-the-K-Sum-of-an-Array.cpp b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/2386.Find-the-K-Sum-of-an-Array.cpp new file mode 100644 index 000000000..91093e27e --- /dev/null +++ b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/2386.Find-the-K-Sum-of-an-Array.cpp @@ -0,0 +1,34 @@ +using LL = long long; +using PLI = pair; +class Solution { +public: + long long kSum(vector& nums, int k) + { + LL sum = 0; + for (int x: nums) + if (x>0) sum += x; + if (k==1) return sum; + + for (int& x: nums) + x = abs(x); + sort(nums.begin(), nums.end()); + + priority_queue, greater<>>pq; + pq.push({nums[0],0}); + + for (int t=0; t Date: Wed, 31 Aug 2022 23:54:53 -0700 Subject: [PATCH 1157/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 879a10a5d..33bb1a85b 100644 --- a/Readme.md +++ b/Readme.md @@ -408,6 +408,7 @@ [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) [2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) +[2386.Find-the-K-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2386.Find-the-K-Sum-of-an-Array) (H+) * ``Sort+PQ`` [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) From 0ff03564875bc54f98030eb4d60a4902d11a8593 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Sep 2022 00:51:41 -0700 Subject: [PATCH 1158/2729] Create Readme.md --- .../2386.Find-the-K-Sum-of-an-Array/Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md diff --git a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md new file mode 100644 index 000000000..163d4dfa4 --- /dev/null +++ b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md @@ -0,0 +1,21 @@ +### 2386.Find-the-K-Sum-of-an-Array + +这是一道真正的Hard。 + +#### 第一步:转化为求一个数组的第k小序列和。 +显然,本题最大sum的序列就是将数组里所有的正数都取出来,对应的是MaxSum。次大的sum值必然是在这个序列的基础上减去一个已经存在的正数,或者加上一个还未入队的负数。同理,第k大的sum值也必然是从这个序列里减去若干个已经存在的正数,或者加上若干个还未入队的负数。因为减去正数等于减去它的绝对值,加上负数也等于减去它的绝对值,所以第k大的sum值,等价于在MaxSum的基础上减去若干个nums里元素的绝对值。故我们只要在nums的绝对值数组里挑出第k小的序列和即可。 + +#### 第二步:构造一个正数数组的从小到大所有的序列和。 +这里直接说明构造的步骤。空集必然对应最小的序列和,我们单独处理。然后 +1. 将`{nums[0], 0}`放入一个小顶堆中(即优先弹出最小值的优先队列)。 +2. 如果从PQ里弹出的是`{sum, i}`,那么将`{sum-nums[i]+nums[i+1], i+1}`和`{sum+nums[i+1], i+1}`加入PQ中(记做操作1和操作2) +3. PQ里第k-1个弹出的sum就是该正数数组里第k大的序列和 + +#### 第三步:证明这个构造方法的正确性 +首先,我们要证明这个构造方法覆盖了所有的子序列。这个直观上不难理解。我们考虑,如果已经生成了所有以nums[0],nums[1],... nums[i-1]结尾的子序列,那么能否通过之前定义的方法,生成所有以nums[i]结尾的子序列呢?假设某个以nums[i]结尾的子序列,它的倒数第二个元素是任意的nums[k],那么我们必然可以通过一个以nums[k]结尾的子序列做一次操作2,再反复进行操作1,就可以得到。 + +其次,我们要证明这个构造方法不会产生重复的子序列。这个也显然,对于任意形如`{X,X,...,X,nums[k],nums[i]}`的序列,如果`k+1==i`,那么它必然唯一由形如`{X,X,...,X,nums[k]}`的子序列通过一次操作2得到;如果`k+1!=i`,那么它必然唯一由形如`{X,X,...,X,nums[k],nums[i-1]}`的子序列通过一次操作1得到。 + +最后,我们要证明这个构造方法生成的子序列是按照和递增的。这个证明很简洁。假设某个序列A小于序列B,但是B先从队列里弹出,这可能吗?注意,这意味着B在队列里的时候A一定还没有加入队列里(否则PQ会优先弹出A)。既然A不在队列里,说明A的前驱状态A'(上一段证明了存在唯一的A')也必然不会在队列里,因为A'是小于A的,A'在队列的话更会比B优先弹出,从而导致将A也被导入队列里。同理证明,A'的前驱序列A''也不会在队列里,A''的前驱序列也不会在队列里... 但是所有的序列都是从{nums[0]}开始的,难道这个序列也从未加入过队列吗?从而引发矛盾。 + +综上,我们证明了这种构造方法一定会一个不漏、一个也不重复地、按从小到大的顺序弹出所有的子序列之和。显然第k-1个弹出来的就是第k小的子序列之和(考虑空集)。 From 7b3982a3066d47c8afee7faf15ec6077ebe94c65 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Sep 2022 00:53:42 -0700 Subject: [PATCH 1159/2729] Update Readme.md --- Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md index 163d4dfa4..ffe485b60 100644 --- a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md +++ b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md @@ -8,7 +8,7 @@ #### 第二步:构造一个正数数组的从小到大所有的序列和。 这里直接说明构造的步骤。空集必然对应最小的序列和,我们单独处理。然后 1. 将`{nums[0], 0}`放入一个小顶堆中(即优先弹出最小值的优先队列)。 -2. 如果从PQ里弹出的是`{sum, i}`,那么将`{sum-nums[i]+nums[i+1], i+1}`和`{sum+nums[i+1], i+1}`加入PQ中(记做操作1和操作2) +2. 如果从PQ里弹出的是`{sum, i}`(其中sum必然是某个以i结尾的子序列之和),那么将`{sum-nums[i]+nums[i+1], i+1}`和`{sum+nums[i+1], i+1}`加入PQ中(记做操作1和操作2) 3. PQ里第k-1个弹出的sum就是该正数数组里第k大的序列和 #### 第三步:证明这个构造方法的正确性 From 54b72af85bd680aae878c32a6f65e1d476f33107 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Sep 2022 00:53:56 -0700 Subject: [PATCH 1160/2729] Update Readme.md --- Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md index ffe485b60..1ea84f6dd 100644 --- a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md +++ b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md @@ -8,7 +8,7 @@ #### 第二步:构造一个正数数组的从小到大所有的序列和。 这里直接说明构造的步骤。空集必然对应最小的序列和,我们单独处理。然后 1. 将`{nums[0], 0}`放入一个小顶堆中(即优先弹出最小值的优先队列)。 -2. 如果从PQ里弹出的是`{sum, i}`(其中sum必然是某个以i结尾的子序列之和),那么将`{sum-nums[i]+nums[i+1], i+1}`和`{sum+nums[i+1], i+1}`加入PQ中(记做操作1和操作2) +2. 如果从PQ里弹出的是`{sum, i}`(其中sum必然是某个以nums[i]结尾的子序列之和),那么将`{sum-nums[i]+nums[i+1], i+1}`和`{sum+nums[i+1], i+1}`加入PQ中(记做操作1和操作2) 3. PQ里第k-1个弹出的sum就是该正数数组里第k大的序列和 #### 第三步:证明这个构造方法的正确性 From 0a9fedaf2beb363cbccd2f693ea0053d15dab79f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Sep 2022 00:56:48 -0700 Subject: [PATCH 1161/2729] Update Readme.md --- Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md index 1ea84f6dd..6af40ed7e 100644 --- a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md +++ b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md @@ -2,7 +2,7 @@ 这是一道真正的Hard。 -#### 第一步:转化为求一个数组的第k小序列和。 +#### 第一步:转化为求一个正数数组的第k小序列和。 显然,本题最大sum的序列就是将数组里所有的正数都取出来,对应的是MaxSum。次大的sum值必然是在这个序列的基础上减去一个已经存在的正数,或者加上一个还未入队的负数。同理,第k大的sum值也必然是从这个序列里减去若干个已经存在的正数,或者加上若干个还未入队的负数。因为减去正数等于减去它的绝对值,加上负数也等于减去它的绝对值,所以第k大的sum值,等价于在MaxSum的基础上减去若干个nums里元素的绝对值。故我们只要在nums的绝对值数组里挑出第k小的序列和即可。 #### 第二步:构造一个正数数组的从小到大所有的序列和。 From 5684b52448eb7e02d48563cd40ead20f10e13a6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Sep 2022 00:59:03 -0700 Subject: [PATCH 1162/2729] Update Readme.md --- Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md index 6af40ed7e..e971398f2 100644 --- a/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md +++ b/Priority_Queue/2386.Find-the-K-Sum-of-an-Array/Readme.md @@ -3,7 +3,7 @@ 这是一道真正的Hard。 #### 第一步:转化为求一个正数数组的第k小序列和。 -显然,本题最大sum的序列就是将数组里所有的正数都取出来,对应的是MaxSum。次大的sum值必然是在这个序列的基础上减去一个已经存在的正数,或者加上一个还未入队的负数。同理,第k大的sum值也必然是从这个序列里减去若干个已经存在的正数,或者加上若干个还未入队的负数。因为减去正数等于减去它的绝对值,加上负数也等于减去它的绝对值,所以第k大的sum值,等价于在MaxSum的基础上减去若干个nums里元素的绝对值。故我们只要在nums的绝对值数组里挑出第k小的序列和即可。 +显然,本题最大sum的序列S就是将数组里所有的正数都取出来,对应的是MaxSum。次大的sum值必然是在这个序列S的基础上减去一个已经存在的正数,或者加上一个还未入队的负数。同理,第k大的sum值也必然是从这个序列S里减去若干个已经存在的正数,或者加上若干个还未入队的负数。因为减去正数等于减去它的绝对值,加上负数也等于减去它的绝对值,所以第k大的sum值,等价于在S(即MaxSum)的基础上减去若干个nums里元素的绝对值。故我们只要在nums的绝对值数组里挑出第k小的序列和即可。 #### 第二步:构造一个正数数组的从小到大所有的序列和。 这里直接说明构造的步骤。空集必然对应最小的序列和,我们单独处理。然后 From 15214e18202104c483601df15d2fe5c9db2f3122 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Sep 2022 13:33:24 -0700 Subject: [PATCH 1163/2729] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 2bf955870..67c9b9ef7 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -83,7 +83,7 @@ class SegTreeNode int main() { - SegTreeNode* root = new SegTreeNode(0, length-1); + SegTreeNode* root = new SegTreeNode(0, length-1, 0); for (auto& update: updates) { From f36b73eb61eed5eeadf94d4564cf32103d888a8a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Sep 2022 13:35:13 -0700 Subject: [PATCH 1164/2729] Create 2398.Maximum-Number-of-Robots-Within-Budget_v2.cpp --- ...imum-Number-of-Robots-Within-Budget_v2.cpp | 129 ++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v2.cpp diff --git a/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v2.cpp b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v2.cpp new file mode 100644 index 000000000..fc037f313 --- /dev/null +++ b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v2.cpp @@ -0,0 +1,129 @@ +using LL = long long; + +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MIN; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + +class Solution { + SegTreeNode* root; +public: + int maximumRobots(vector& chargeTimes, vector& runningCosts, long long budget) + { + vector>robots; + int n = chargeTimes.size(); + + root = new SegTreeNode(0, n-1, 0); + for (int i=0; iupdateRange(i, i, chargeTimes[i]); + + LL left = 0, right = n; + while (left < right) + { + LL mid = right-(right-left)/2; + if (isOK(mid, chargeTimes, runningCosts, budget)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool isOK(LL k, vector& chargeTimes, vector& runningCosts, long long budget) + { + LL n = chargeTimes.size(); + LL sum = 0; + + for (int i=0; i=k-1) + { + LL ret = root->queryRange(i-k+1, i) + (LL)k * sum; + if (ret <= budget) return true; + sum -= runningCosts[i-k+1]; + } + } + + return false; + } +}; From b67fc2c9ab87e3893615bd45597831f1d5043e24 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Sep 2022 13:36:11 -0700 Subject: [PATCH 1165/2729] Create 2398.Maximum-Number-of-Robots-Within-Budget_v1.cpp --- ...imum-Number-of-Robots-Within-Budget_v1.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v1.cpp diff --git a/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v1.cpp b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v1.cpp new file mode 100644 index 000000000..1a7f7843a --- /dev/null +++ b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v1.cpp @@ -0,0 +1,43 @@ +using LL = long long; +class Solution { +public: + int maximumRobots(vector& chargeTimes, vector& runningCosts, long long budget) + { + vector>robots; + int n = chargeTimes.size(); + + LL left = 0, right = n; + while (left < right) + { + LL mid = right-(right-left)/2; + if (isOK(mid, chargeTimes, runningCosts, budget)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool isOK(LL k, vector& chargeTimes, vector& runningCosts, long long budget) + { + LL n = chargeTimes.size(); + LL sum = 0; + multisetSet; + + for (int i=0; i=k-1) + { + LL ret = *(Set.rbegin()) + (LL)k * sum; + if (ret <= budget) return true; + sum -= runningCosts[i-k+1]; + Set.erase(Set.find(chargeTimes[i-k+1])); + } + } + + return false; + } +}; From c8fc02694e7c4be83622689975defdc206226476 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Sep 2022 13:40:47 -0700 Subject: [PATCH 1166/2729] Create 2398.Maximum-Number-of-Robots-Within-Budget_v3.cpp --- ...imum-Number-of-Robots-Within-Budget_v3.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v3.cpp diff --git a/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v3.cpp b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v3.cpp new file mode 100644 index 000000000..14eebf7da --- /dev/null +++ b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/2398.Maximum-Number-of-Robots-Within-Budget_v3.cpp @@ -0,0 +1,47 @@ +using LL = long long; +class Solution { +public: + int maximumRobots(vector& chargeTimes, vector& runningCosts, long long budget) + { + vector>robots; + int n = chargeTimes.size(); + + LL left = 0, right = n; + while (left < right) + { + LL mid = right-(right-left)/2; + if (isOK(mid, chargeTimes, runningCosts, budget)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool isOK(LL k, vector& chargeTimes, vector& runningCosts, long long budget) + { + LL n = chargeTimes.size(); + LL sum = 0; + dequedq; + + for (int i=0; i=k-1) + { + LL ret = chargeTimes[dq.front()] + (LL)k * sum; + if (ret <= budget) return true; + sum -= runningCosts[i-k+1]; + + } + } + + return false; + } +}; From 22f22b7ab085781a6dec615f18e507d731544ff4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Sep 2022 13:41:12 -0700 Subject: [PATCH 1167/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 33bb1a85b..f10946d69 100644 --- a/Readme.md +++ b/Readme.md @@ -392,6 +392,7 @@ [1562.Find-Latest-Group-of-Size-M](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1562.Find-Latest-Group-of-Size-M) (H) [1696.Jump-Game-VI](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1696.Jump-Game-VI) (M+) [1776.Car-Fleet-II](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1776.Car-Fleet-II) (H) +[2398.Maximum-Number-of-Robots-Within-Budget](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2398.Maximum-Number-of-Robots-Within-Budget) (H-) #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) From 0f50067a8aa8645ab1639557633d5d0b5f8b0f2b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Sep 2022 13:53:49 -0700 Subject: [PATCH 1168/2729] Create Readme.md --- Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md diff --git a/Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md new file mode 100644 index 000000000..9f6e6e913 --- /dev/null +++ b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md @@ -0,0 +1,5 @@ +### 2398.Maximum-Number-of-Robots-Within-Budget + +很明显,budget越多,能够跑的机器就越多,这是一个单调的过程。所以我们用二分法来试探最大的机器数目。 + +如果确定了一个长度,我们就跑一遍滑窗,需要计算每个时刻滑窗内的元素之和与元素最大值。显然,用单调deque是解sliding window maximum的固定套路。 From 83bd16f8df1181af205946140e090f20170429a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Sep 2022 13:54:42 -0700 Subject: [PATCH 1169/2729] Update Readme.md --- Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md index 9f6e6e913..e19b01e58 100644 --- a/Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md +++ b/Deque/2398.Maximum-Number-of-Robots-Within-Budget/Readme.md @@ -2,4 +2,6 @@ 很明显,budget越多,能够跑的机器就越多,这是一个单调的过程。所以我们用二分法来试探最大的机器数目。 -如果确定了一个长度,我们就跑一遍滑窗,需要计算每个时刻滑窗内的元素之和与元素最大值。显然,用单调deque是解sliding window maximum的固定套路。 +如果确定了一个长度,我们就跑一遍滑窗,需要计算每个时刻滑窗内的元素之和与元素最大值。显然,用单调deque是解sliding window maximum的固定套路,时间复杂度是o(n)。 + +此题如果用一个有序容器(比如说multiset),结果会超时。另外,用线段树也是一个可行的选择。 From 560eaa4f1912b39d6f1895de9e6edb659f3325a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 00:18:51 -0700 Subject: [PATCH 1170/2729] Create 2402.Meeting-Rooms-III.cpp --- .../2402.Meeting-Rooms-III.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Priority_Queue/2402.Meeting-Rooms-III/2402.Meeting-Rooms-III.cpp diff --git a/Priority_Queue/2402.Meeting-Rooms-III/2402.Meeting-Rooms-III.cpp b/Priority_Queue/2402.Meeting-Rooms-III/2402.Meeting-Rooms-III.cpp new file mode 100644 index 000000000..8c28b53bb --- /dev/null +++ b/Priority_Queue/2402.Meeting-Rooms-III/2402.Meeting-Rooms-III.cpp @@ -0,0 +1,46 @@ +using LL = long long; +using PLI = pair; +class Solution { +public: + int mostBooked(int n, vector>& meetings) + { + priority_queue, greater<>>busy; + priority_queue, greater<>>free; + for (int i=0; icount(n); + + for (int i=0; i Date: Sun, 4 Sep 2022 00:19:50 -0700 Subject: [PATCH 1171/2729] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index f10946d69..3e1a6f82a 100644 --- a/Readme.md +++ b/Readme.md @@ -405,11 +405,13 @@ [1705.Maximum-Number-of-Eaten-Apples](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1705.Maximum-Number-of-Eaten-Apples) (M+) [1792.Maximum-Average-Pass-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1792.Maximum-Average-Pass-Ratio) (M+) [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) +[2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) +[2386.Find-the-K-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2386.Find-the-K-Sum-of-an-Array) (H+) +* ``Dual PQ`` [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) -[2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) -[2386.Find-the-K-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2386.Find-the-K-Sum-of-an-Array) (H+) +[2402.Meeting-Rooms-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2402.Meeting-Rooms-III) (M+) * ``Sort+PQ`` [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) From 0ff06724e17999fed51de93e8fae0e3354c39c2d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 00:21:01 -0700 Subject: [PATCH 1172/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3e1a6f82a..78253b9af 100644 --- a/Readme.md +++ b/Readme.md @@ -404,10 +404,10 @@ [1642.Furthest-Building-You-Can-Reach](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1642.Furthest-Building-You-Can-Reach) (H-) [1705.Maximum-Number-of-Eaten-Apples](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1705.Maximum-Number-of-Eaten-Apples) (M+) [1792.Maximum-Average-Pass-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1792.Maximum-Average-Pass-Ratio) (M+) -[1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) [2386.Find-the-K-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2386.Find-the-K-Sum-of-an-Array) (H+) * ``Dual PQ`` +[1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) From 09927fd0cc6b48cbbafcedd6ec7c3ea8ab7fea57 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 00:36:27 -0700 Subject: [PATCH 1173/2729] Create Readme.md --- Priority_Queue/2402.Meeting-Rooms-III/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Priority_Queue/2402.Meeting-Rooms-III/Readme.md diff --git a/Priority_Queue/2402.Meeting-Rooms-III/Readme.md b/Priority_Queue/2402.Meeting-Rooms-III/Readme.md new file mode 100644 index 000000000..13648f39d --- /dev/null +++ b/Priority_Queue/2402.Meeting-Rooms-III/Readme.md @@ -0,0 +1,7 @@ +### 2402.Meeting-Rooms-III + +此题和1882和1942非常类似,需要使用到两个优先队列,简单模拟这个过程即可。 + +我们设计busy的优先队列,里面放置正在使用的会议室,按照它们available的时间排序。另外设计free的优先队列,里面放置当前闲置的会议室,按照id的排序。 + +我们将meeting排序后,对于当前待安排的会议,我们查看busy里的会议室,将那些已经available的会议室释放出来加入free队列。我们先试图在free队列里捞一个id最小的,并将这个会议室再加入busy队列(重新设置available的时间)。如果当前free队列为空,我们就需要等待busy里的第一个会议室的available time,然后将其重置available后再次加入busy。 From 3ebf81dffbe4875bbc5c51a6449373b42189a970 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 10:22:30 -0700 Subject: [PATCH 1174/2729] Update Readme.md --- .../Readme.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Deque/862.Shortest-Subarray-with-Sum-at-Least-K/Readme.md b/Deque/862.Shortest-Subarray-with-Sum-at-Least-K/Readme.md index 37505fedb..9d8d26427 100644 --- a/Deque/862.Shortest-Subarray-with-Sum-at-Least-K/Readme.md +++ b/Deque/862.Shortest-Subarray-with-Sum-at-Least-K/Readme.md @@ -20,16 +20,14 @@ 3.在map删除所有大于preSum[i]的键 ``` -#### 解法2 -上述的解法复杂度是o(NlogN),但实际上还有更好的o(N)的解法. +#### 解法2:单调队列 +上述的解法复杂度是o(NlogN),但实际上还有更好的o(N)的解法.我们基于nums的前缀和数组presum,维护一个双端队列q,保持队列里面的元素是递增的。我们每处理一个新的presum[i],希望在队列里查看最近的j,使得`presum[i]-presum[j]>=k`. 显然我们希望j的位置尽量靠后,同时presum[j]的数值尽量小。 -我们维护一个双端队列q,里面存储的q[j]表示的是一个递增的index的序列.同时要保证presum[q[j]]也是递增的.是不是有点绕? +我们假想,presum的前若干个元素本身就是递增的,那么我们就可以照单全收都放入deque里面。此时如果新元素presum[i]比队尾元素(记做j)要小,那么我们就可以把队尾元素j去掉。这是因为从此以后,presum[j]都不会是最优解所对应的区间左端点。考察上面式子的被减数,这个presum[j]相比于presum[i]而言既“老”又“大”,选j永远不如选i。 -假设我们现在处理A[i],其对应的前缀和是presum[i],那么我们想在这个队列里面找到一个位置j,恰好使得```presum[q[j]]+K<=presum[i]```,那么队列中的q[0]~q[j]这些index都是满足at least K条件的位置,我们可以找其中最大的一个,比如说q[j'],就能使得subarray长度i-q[j']是最小的.接下来的操作很重要,我们可以将q[0]到q[j']都从队列前端弹出.因为以后的i会更大,如果它在队列中找到的满足at least K条件的左边界位置比q[j']小的话,不会比已经得到的result更好.所以任何早于q[j']的队列元素对以后的搜索都没有帮助. +同时针对新加入的presum[i],我们考察队首元素(也记做j),观察是否满足`presum[i]-presum[j]>=k`。如果是的话,显然`[j+1,i]`就是一个合法的解。注意,此时我们就可以将j弹出了。因为我们不需要j再与其他位置(指i之后的)匹配合法的区间了,因为即使存在,那样的区间长度也会更长。 -接下来,我们需要将presum[i]的信息加入这个队列.我们的策略是不断在后端弹出元素,直到```presum[q.back()] Date: Sun, 4 Sep 2022 11:07:03 -0700 Subject: [PATCH 1175/2729] Update 862.Shortest-Subarray-with-Sum-at-Least-K_v2.cpp --- ...ortest-Subarray-with-Sum-at-Least-K_v2.cpp | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/Deque/862.Shortest-Subarray-with-Sum-at-Least-K/862.Shortest-Subarray-with-Sum-at-Least-K_v2.cpp b/Deque/862.Shortest-Subarray-with-Sum-at-Least-K/862.Shortest-Subarray-with-Sum-at-Least-K_v2.cpp index bfd952ca1..509d46a7f 100644 --- a/Deque/862.Shortest-Subarray-with-Sum-at-Least-K/862.Shortest-Subarray-with-Sum-at-Least-K_v2.cpp +++ b/Deque/862.Shortest-Subarray-with-Sum-at-Least-K/862.Shortest-Subarray-with-Sum-at-Least-K_v2.cpp @@ -1,25 +1,29 @@ +using LL = long long; class Solution { public: - int shortestSubarray(vector& A, int K) + int shortestSubarray(vector& nums, int k) { - int N = A.size(); - vectorpresum(N+1,0); - for (int i=0; iq; - int result = INT_MAX; - for (int i=0; i<=N; i++) + int n = nums.size(); + vectorpresum(n+1); + for (int i=0; idq; + for (int i=0; i<=n; i++) { - while (q.size()>0 && presum[q.front()]+K<=presum[i]) - { - result = min(result,i-q.front()); - q.pop_front(); + while (!dq.empty() && presum[dq.back()] >= presum[i]) + dq.pop_back(); + + while (!dq.empty() && presum[i]-presum[dq.front()] >= k) { + ret = min(ret, i-dq.front()); + dq.pop_front(); } - while (q.size()>0 && presum[q.back()]>=presum[i]) - q.pop_back(); - q.push_back(i); + + dq.push_back(i); } - return result==INT_MAX? -1:result; - + + if (ret == INT_MAX) return -1; + else return ret; } }; From ee09d3ff84f40667f6029e672b8e86c83852077c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 11:38:38 -0700 Subject: [PATCH 1176/2729] Update 1499.Max-Value-of-Equation.cpp --- .../1499.Max-Value-of-Equation.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp b/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp index 07705a718..dd8216c34 100644 --- a/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp +++ b/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp @@ -9,13 +9,15 @@ class Solution { while (q.size()>0 && points[q.front()][0] < points[i][0]-k) q.pop_front(); - if (q.size() > 0) - ret = max(ret, -points[q.front()][0]+points[q.front()][1] + points[i][0]+points[i][1]); - - while (q.size()>0 && -points[q.back()][0]+points[q.back()][1] < -points[i][0]+points[i][1]) + while (q.size()>0 && -points[q.back()][0]+points[q.back()][1] < -points[i][0]+points[i][1]) q.pop_back(); q.push_back(i); + if (q.size() > 0) + ret = max(ret, -points[q.front()][0]+points[q.front()][1] + points[i][0]+points[i][1]); + + + } return ret; From 876a522087f205ede62fb4311020302fbcc8bf99 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 11:39:10 -0700 Subject: [PATCH 1177/2729] Update 1499.Max-Value-of-Equation.cpp --- .../1499.Max-Value-of-Equation.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp b/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp index dd8216c34..e8b6fdacf 100644 --- a/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp +++ b/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp @@ -6,20 +6,20 @@ class Solution { dequeq; for (int i=0; i0 && points[q.front()][0] < points[i][0]-k) + while (q.size()>0 && points[q.front()][0] < points[i][0]-k) { q.pop_front(); + } - while (q.size()>0 && -points[q.back()][0]+points[q.back()][1] < -points[i][0]+points[i][1]) + while (q.size()>0 && -points[q.back()][0]+points[q.back()][1] < -points[i][0]+points[i][1]) { q.pop_back(); + } + q.push_back(i); - if (q.size() > 0) + if (q.size() > 0) { ret = max(ret, -points[q.front()][0]+points[q.front()][1] + points[i][0]+points[i][1]); - - - + } } return ret; - } }; From b89c27d8dceb9dcd96b1d9e649092ee5b67a57ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 11:39:22 -0700 Subject: [PATCH 1178/2729] Update 1499.Max-Value-of-Equation.cpp --- Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp b/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp index e8b6fdacf..d18832742 100644 --- a/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp +++ b/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp @@ -10,7 +10,7 @@ class Solution { q.pop_front(); } - while (q.size()>0 && -points[q.back()][0]+points[q.back()][1] < -points[i][0]+points[i][1]) { + while (q.size()>0 && -points[q.back()][0]+points[q.back()][1] < -points[i][0]+points[i][1]) { q.pop_back(); } From b4c29c41e7ec6eb49c40addc5279f9579a176d92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 12:15:37 -0700 Subject: [PATCH 1179/2729] Create 2397.Maximum-Rows-Covered-by-Columns.cpp --- .../2397.Maximum-Rows-Covered-by-Columns.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns/2397.Maximum-Rows-Covered-by-Columns.cpp diff --git a/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns/2397.Maximum-Rows-Covered-by-Columns.cpp b/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns/2397.Maximum-Rows-Covered-by-Columns.cpp new file mode 100644 index 000000000..5c3c25cea --- /dev/null +++ b/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns/2397.Maximum-Rows-Covered-by-Columns.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int maximumRows(vector>& mat, int cols) + { + int m = mat.size(); + int n = mat[0].size(); + + vectornums; + for (int i=0; i> 2) / c) | r; + } + + return ret; + + } +}; From 9bedf95bc575df5f9bff9184d5364148f675a4dd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 12:16:05 -0700 Subject: [PATCH 1180/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 78253b9af..cd585e8a1 100644 --- a/Readme.md +++ b/Readme.md @@ -830,6 +830,7 @@ [1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) (M) [2151.Maximum-Good-People-Based-on-Statements](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements) (M+) +[2397.Maximum-Rows-Covered-by-Columns](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns) (M) * ``Meet in the Middle`` [1755.Closest-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1755.Closest-Subsequence-Sum) (H) [2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) From dbd1f07697ca29a9b72d6e2ece77c12a7debd8cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 12:21:51 -0700 Subject: [PATCH 1181/2729] Create Readme.md --- .../2397.Maximum-Rows-Covered-by-Columns/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns/Readme.md diff --git a/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns/Readme.md b/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns/Readme.md new file mode 100644 index 000000000..f6696b6d6 --- /dev/null +++ b/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns/Readme.md @@ -0,0 +1,5 @@ +### 2397.Maximum-Rows-Covered-by-Columns + +考虑到总的列数不超过12,枚举所有的列的选择都是可行的。对于一种固定的列的组合,我们记成二进制数state,先排除掉那些bit 1的个数不等于cols的。然后我们只需要查看每一行对应的二进制数row是否是state的子集即可,即`(state&row) == row`. 我们最后选择一个能cover最多row的state。 + +此外,我们可以用gosper's hack来提高效率,只枚举那些bit 1的个数等于cols的state。 From 68a82d7cd27ee696ac193ad0424464d35ca6a152 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 15:10:41 -0700 Subject: [PATCH 1182/2729] Create 2401.Longest-Nice-Subarray.cpp --- .../2401.Longest-Nice-Subarray.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Two_Pointers/2401.Longest-Nice-Subarray/2401.Longest-Nice-Subarray.cpp diff --git a/Two_Pointers/2401.Longest-Nice-Subarray/2401.Longest-Nice-Subarray.cpp b/Two_Pointers/2401.Longest-Nice-Subarray/2401.Longest-Nice-Subarray.cpp new file mode 100644 index 000000000..3e5e26a51 --- /dev/null +++ b/Two_Pointers/2401.Longest-Nice-Subarray/2401.Longest-Nice-Subarray.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int longestNiceSubarray(vector& nums) + { + int count = 0; + int j = 0; + int ret = 0; + for (int i=0; i Date: Sun, 4 Sep 2022 15:11:07 -0700 Subject: [PATCH 1183/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index cd585e8a1..7b82d6490 100644 --- a/Readme.md +++ b/Readme.md @@ -45,6 +45,7 @@ [2024.Maximize-the-Confusion-of-an-Exam](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2024.Maximize-the-Confusion-of-an-Exam) (M) [424.Longest-Repeating-Character-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/424.Longest-Repeating-Character-Replacement) (H-) [2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) +[2401.Longest-Nice-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2401.Longest-Nice-Subarray) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 9fae4c3374f9bca697964cc4094c779990769d37 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 15:17:09 -0700 Subject: [PATCH 1184/2729] Create Readme.md --- Two_Pointers/2401.Longest-Nice-Subarray/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2401.Longest-Nice-Subarray/Readme.md diff --git a/Two_Pointers/2401.Longest-Nice-Subarray/Readme.md b/Two_Pointers/2401.Longest-Nice-Subarray/Readme.md new file mode 100644 index 000000000..a8fdfb47d --- /dev/null +++ b/Two_Pointers/2401.Longest-Nice-Subarray/Readme.md @@ -0,0 +1,5 @@ +### 2401.Longest-Nice-Subarray + +本题的本质就是找一段最长区间,使得这个区间内每个bit位上最多只出现一个1. 这其实就是和`003.Longest-Substring-Without-Repeating-Character`一样的思想。 + +我们可以开一个长度为32的数组来记录频次,但是更精彩的做法就是用一个二进制数count本身来记录。count的每个bit上就记录了该位置出现了0次或者1次的1。只要`(count & nums[j])==0`,那么意味着没有任何一个bit位上的1出现了超过1次,于是滑窗的右边界就可以不断右移。如果右移受挫,那么此时`[i,j-1]`就是以i开头的、符合条件的最长区间。接下来我们只要移动左指针i,将nums[i]从count里移出,那么就可以继续尝试移动右指针了。 From 6baf02b755954fb94581882471aa207f63472cf8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 15:17:59 -0700 Subject: [PATCH 1185/2729] Update Readme.md --- Two_Pointers/2401.Longest-Nice-Subarray/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Two_Pointers/2401.Longest-Nice-Subarray/Readme.md b/Two_Pointers/2401.Longest-Nice-Subarray/Readme.md index a8fdfb47d..8b8127119 100644 --- a/Two_Pointers/2401.Longest-Nice-Subarray/Readme.md +++ b/Two_Pointers/2401.Longest-Nice-Subarray/Readme.md @@ -2,4 +2,4 @@ 本题的本质就是找一段最长区间,使得这个区间内每个bit位上最多只出现一个1. 这其实就是和`003.Longest-Substring-Without-Repeating-Character`一样的思想。 -我们可以开一个长度为32的数组来记录频次,但是更精彩的做法就是用一个二进制数count本身来记录。count的每个bit上就记录了该位置出现了0次或者1次的1。只要`(count & nums[j])==0`,那么意味着没有任何一个bit位上的1出现了超过1次,于是滑窗的右边界就可以不断右移。如果右移受挫,那么此时`[i,j-1]`就是以i开头的、符合条件的最长区间。接下来我们只要移动左指针i,将nums[i]从count里移出,那么就可以继续尝试移动右指针了。 +我们可以开一个长度为32的数组来记录每个bit位上出现1的频次,但是更精彩的做法就是用一个二进制数count本身来记录。count的每个bit可以记录该位置出现了0次或者1次的1。只要`(count & nums[j])==0`,那么意味着没有任何一个bit位上的1出现了超过1次,于是滑窗的右边界就可以不断右移。反之,就意味着不能继续右移,那么此时`[i,j-1]`就是以i开头的、符合条件的最长区间。接下来我们只要移动左指针i,将nums[i]从count里移出,那么就可以继续尝试移动右指针了。 From f7440ffeee7ed9f964feb72ab44441e6cfcfff41 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 22:12:02 -0700 Subject: [PATCH 1186/2729] Update 373.Find-K-Pairs-with-Smallest-Sums.cpp --- .../373.Find-K-Pairs-with-Smallest-Sums.cpp | 56 ++++++++----------- 1 file changed, 23 insertions(+), 33 deletions(-) diff --git a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp index 9cc7fbfe6..8172d0f02 100644 --- a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp +++ b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp @@ -1,45 +1,35 @@ -class Solution { - struct cmp - { - bool operator()(paira,pairb) - { - return a.first>b.first; - } - }; +using AI3 = array; +class Solution { public: - vector> kSmallestPairs(vector& nums1, vector& nums2, int k) + vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { - priority_queue,vector>,cmp>q; - int M=nums1.size(); - int N=nums2.size(); - vector>results; - if (M==0 || N==0) return results; - - auto used=vector>(M,vector(N,0)); - q.push({nums1[0]+nums2[0],0}); - used[0][0]=1; + priority_queue, greater<>>pq; + int m=nums1.size(); + int n=nums2.size(); + vector>rets; - int count=0; - while (count0) + vector>visited(m,vector(n,0)); + pq.push({nums1[0]+nums2[0], 0, 0}); + visited[0][0]=1; + + while (rets.size() < k && pq.size()>0) { - int m=q.top().second/N; - int n=q.top().second%N; - results.push_back({nums1[m],nums2[n]}); - count++; - q.pop(); - - if (m+1 Date: Sun, 4 Sep 2022 23:09:35 -0700 Subject: [PATCH 1187/2729] Update 373.Find-K-Pairs-with-Smallest-Sums.cpp --- .../373.Find-K-Pairs-with-Smallest-Sums.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp index 8172d0f02..4d4237982 100644 --- a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp +++ b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/373.Find-K-Pairs-with-Smallest-Sums.cpp @@ -8,9 +8,10 @@ class Solution { int n=nums2.size(); vector>rets; - vector>visited(m,vector(n,0)); + set>Set; pq.push({nums1[0]+nums2[0], 0, 0}); - visited[0][0]=1; + Set.insert({0,0}); + while (rets.size() < k && pq.size()>0) { @@ -18,15 +19,15 @@ class Solution { pq.pop(); rets.push_back({nums1[i], nums2[j]}); - if (i+1 Date: Sun, 4 Sep 2022 23:10:58 -0700 Subject: [PATCH 1188/2729] Update Readme.md --- Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md index ee5e98eca..214c27264 100644 --- a/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md +++ b/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums/Readme.md @@ -7,6 +7,8 @@ #### 解法1:BFS+PQ 用BFS的方法进行搜索。每次弹出一个PQ里最小的元素,然后新加入该元素相邻(右边和下边)的两个元素。最先弹出的k个元素就是答案。 +注意搜索的过程中需要去重。去重得用map,因为用visited数组的话需要开辟太大的空间。 + #### 解法2:binary search + sorted matrix property 此题和378, 668, 719, 1918都是一样的套路。 From 951b87a399432f7a69f11d28486afb010ecfad95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 23:12:02 -0700 Subject: [PATCH 1189/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7b82d6490..b92aa0684 100644 --- a/Readme.md +++ b/Readme.md @@ -397,6 +397,7 @@ #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) +[373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [871.Minimum-Number-of-Refueling-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/871.Minimum-Number-of-Refueling-Stops) (H-) [1057.Campus-Bikes](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1057.Campus-Bikes) (H-) From e0240a68509e85326a04af5d4d2ef916796f286a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Sep 2022 23:38:12 -0700 Subject: [PATCH 1190/2729] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index 9cd05886a..534f6b472 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -1,9 +1,8 @@ -typedef long long ll; - +using LL = long long; main() { // compute all C(n,m) saved in comb - ll comb[1000][1000]; + long long comb[1000][1000]; for (int i = 0; i <= n; ++i) { comb[i][i] = comb[i][0] = 1; @@ -16,7 +15,7 @@ main() } // Compute C(n,m) on demand -ll help(int n, int m) +long long help(int n, int m) { long long cnt = 1; for(int i = 0; i < m; i++) From 71e5a09e61dd850e6710f2fa18efac890e29739f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 5 Sep 2022 00:03:18 -0700 Subject: [PATCH 1191/2729] Create 2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v1.cpp --- ...ch-a-Position-After-Exactly-k-Steps_v1.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v1.cpp diff --git a/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v1.cpp b/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v1.cpp new file mode 100644 index 000000000..2a703eee9 --- /dev/null +++ b/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v1.cpp @@ -0,0 +1,25 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int numberOfWays(int startPos, int endPos, int k) + { + LL offset = k; + + if (abs(endPos-startPos)>k) return 0; + + vector>dp(k+1, vector(2*k+10, 0)); + dp[0][0+offset] = 1; + + for (int t=1; t<=k; t++) + for (int p = -k; p<=k; p++) + { + if (p-1 >= -k) + dp[t][p+offset] = (dp[t][p+offset] + dp[t-1][p-1+offset]) % M; + if (p+1 <= k) + dp[t][p+offset] = (dp[t][p+offset] + dp[t-1][p+1+offset]) % M; + } + + return dp[k][abs(endPos - startPos) + offset]; + } +}; From f7e85bf50439c39691ffb7bc3fea1eb40c1e6be7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 5 Sep 2022 00:04:04 -0700 Subject: [PATCH 1192/2729] Create 2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v2.cpp --- ...ch-a-Position-After-Exactly-k-Steps_v2.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v2.cpp diff --git a/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v2.cpp b/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v2.cpp new file mode 100644 index 000000000..52f9c75dc --- /dev/null +++ b/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps_v2.cpp @@ -0,0 +1,30 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL comb[1005][1005]; +public: + int numberOfWays(int startPos, int endPos, int k) + { + int diff = abs(endPos-startPos); + if (diff > k) return 0; + + if ((diff + k)%2==1) return 0; + + int a = (k+diff)/2; + int b = (k-diff)/2; + + return C(k,a); + } + + LL C(int m, int n) + { + if (comb[m][n]!=0) return comb[m][n]; + if (n==0) return 1; + if (m==n) return 1; + + LL ret = C(m-1, n-1) + C(m-1, n); + comb[m][n] = ret % M; + + return comb[m][n]; + } +}; From fe7b4c5a641edb4a4ce072b62ebc831782857143 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 5 Sep 2022 00:04:43 -0700 Subject: [PATCH 1193/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b92aa0684..9cfd7e0a9 100644 --- a/Readme.md +++ b/Readme.md @@ -1059,6 +1059,7 @@ [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) [1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony](https://github.com/wisdompeak/LeetCode/tree/master/Math/1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony) (H) [2221.Find-Triangular-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Math/2221.Find-Triangular-Sum-of-an-Array) (M) +[2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps) (M+) * ``Numerical Theory`` [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) [365.Water-and-Jug-Problem](https://github.com/wisdompeak/LeetCode/tree/master/Math/365.Water-and-Jug-Problem) (H) From a9ef0a978df64d82bc016886b2a100062eb1a7ef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 5 Sep 2022 10:17:44 -0700 Subject: [PATCH 1194/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/Readme.md diff --git a/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/Readme.md b/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/Readme.md new file mode 100644 index 000000000..5af454938 --- /dev/null +++ b/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/Readme.md @@ -0,0 +1,9 @@ +### 2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps + +#### 解法1:常规DP +本题常规的解法是DP。我们令dp[t][p]表示第t步的时候移动到p的位置有多少种方案。显然我们有```dp[t][p] = dp[t-1][p-1] + dp[t1][p+1]```. + +这里我们需要注意的是startPos和endPos的绝对位置对于我们没有用处,我们只关心最终的相对移动,即`|endPos-startPos|`.我们在计算dp的循环里,p的范围应该是[-k,k]. + +#### 解法2:组合数 +我们令`d=|endPos-startPos|`,那么我们知道,为了通过k步的移动、最终偏移d的位置,需要前进a步且后退b步,且`a+b=k`,其中a就是`(d+k)/2`,其中`d+k`必须能被2整除。这样的话,本题就是求在k步移动里如何安排其中的a步前进。顾方案数就是comb(k,a)。我们可以利用组合数的递推公式`comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]`求解。 From 41062af1364a45ad71f9ecd7c7e65ee9ca2348c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 7 Sep 2022 05:04:20 -0700 Subject: [PATCH 1195/2729] Update Readme.md --- .../903.Valid-Permutations-for-DI-Sequence/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence/Readme.md b/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence/Readme.md index 2a9487c5b..4791b21c5 100644 --- a/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence/Readme.md +++ b/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence/Readme.md @@ -10,7 +10,7 @@ S = "#"+S; 我们考虑在往第i位上填数时,显然应该受到S[i]的影响。 -S[i]为“I”的时候,说明要求第i位上的数字要比第i-1位上的数字大。那么第i-1位上可以是什么呢?因为第i位上是j,那么第i-1位上只能是1~j-1.所以 +S[i]为“I”的时候,说明要求第i位上的数字要比第i-1位上的数字大。那么第i-1位上可以是什么呢?因为第i位上是j,那么第i-1位上只能是0~j-1.所以 ```cpp if (S[i]=='I') for (int k = 0; k Date: Sat, 10 Sep 2022 15:00:14 -0700 Subject: [PATCH 1196/2729] Update Readme.md --- Dynamic_Programming/096.Unique-Binary-Search-Trees/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/096.Unique-Binary-Search-Trees/Readme.md b/Dynamic_Programming/096.Unique-Binary-Search-Trees/Readme.md index 73a02f203..9eff6c5b3 100644 --- a/Dynamic_Programming/096.Unique-Binary-Search-Trees/Readme.md +++ b/Dynamic_Programming/096.Unique-Binary-Search-Trees/Readme.md @@ -1,6 +1,6 @@ ### 096.Unique-Binary-Search-Trees -首先我们考虑根节点的选择。如果我们选择数字k作为根节点,那么左子树必然由节点1~k-1组成,左子树必然由节点k+1~n组成。接下来左右子树的构建就是一个递归问题。构建完左右子树之后,以k为根节点的BST的个数就是左子树个数乘以右子树个数(两两组合)。 +首先我们考虑根节点的选择。如果我们选择数字k作为根节点,那么左子树必然由节点`1~k-1`组成,左子树必然由节点`k+1~n`组成。接下来左右子树的构建就是一个递归问题。构建完左右子树之后,以k为根节点的BST的个数就是左子树个数乘以右子树个数(两两组合)。 我们可以用dp的解法。令dp[k]表示给定n个节点可以构成多少个BST。根据上面的思路,我们先loop作为根节点的数值,然后递归调用dp ```cpp From 4e681926b87dfe8d8a83c59ca6fc3e13e8a5e0f4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 09:41:05 -0700 Subject: [PATCH 1197/2729] Delete 2272.Substring-With-Largest-Variance.cpp --- .../2272.Substring-With-Largest-Variance.cpp | 52 ------------------- 1 file changed, 52 deletions(-) delete mode 100644 Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance.cpp diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance.cpp b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance.cpp deleted file mode 100644 index 7b91e9785..000000000 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance.cpp +++ /dev/null @@ -1,52 +0,0 @@ -class Solution { -public: - int largestVariance(string s) - { - vectorcount(26,0); - for (auto x: s) - count[x-'a']++; - - int ret = 0; - int n = s.size(); - for (int i=0; i<26; i++) - for (int j=0; j<26; j++) - { - if (i==j) continue; - if (count[i]==0 || count[j]==0) continue; - vectorarr(n, 0); - for (int k=0; k&nums) - { - int n = nums.size(); - vectordp(n); - int curSum = 0; - - for (int i = 0; i < n; i++) - { - curSum = max(curSum+nums[i], nums[i]); - dp[i] = curSum; - } - - curSum = 0; - int ret = 0; - for (int i=n-1; i>=0; i--) - { - curSum = max(curSum+nums[i], nums[i]); - if (nums[i]==-1) - ret = max(ret, curSum + dp[i] - nums[i]); - } - return ret; - } -}; From 2522f5dd0531196147ff28040b216d78cccc50df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 09:42:22 -0700 Subject: [PATCH 1198/2729] Rename 2272.Substring-With-Largest-Variance_v2.cpp to 2272.Substring-With-Largest-Variance_v1.cpp --- ...ariance_v2.cpp => 2272.Substring-With-Largest-Variance_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2272.Substring-With-Largest-Variance/{2272.Substring-With-Largest-Variance_v2.cpp => 2272.Substring-With-Largest-Variance_v1.cpp} (100%) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v1.cpp similarity index 100% rename from Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp rename to Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v1.cpp From 520b8f990bcd05dfd95e2066af71edfc71820bbd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 09:42:45 -0700 Subject: [PATCH 1199/2729] Create 2272.Substring-With-Largest-Variance_v2.cpp --- ...272.Substring-With-Largest-Variance_v2.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp new file mode 100644 index 000000000..a0626d730 --- /dev/null +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int largestVariance(string s) + { + int n = s.size(); + map>pos; + for (int i=0; i Date: Sun, 11 Sep 2022 09:58:27 -0700 Subject: [PATCH 1200/2729] Update Readme.md --- .../Readme.md | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md index fcfaa211b..2b5a22746 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md @@ -4,12 +4,9 @@ 于是我们就想到了穷举本题中的最大频次字符x和最小频次字母y。这样的话,我们需要在原字符串里面找一个滑窗,使得x的频次与y的频次之差最大,而其他字母都没有任何作用。这就联想到,如果将x的字符都替换为1,y的字符都替换为-1,其他字符都替换为0,那么不就是变成了寻找```max subarray sum```的题目了吗? -但是注意,这里有一点不同,根据题意,我们想要找的subarray必须至少包含一个-1. 传统的kadane算法,我们很有可能找出只有+1的subarray。那么怎么办呢?有两种方法。 +但是注意,这里有一点不同,根据题意,我们想要找的subarray必须至少包含一个-1. 传统的kadane算法,我们很有可能找出只有+1的subarray。不过解决方法和kadane的思想差不多。 #### 解法1 -我们可以找那个-1为突破口。根据Kadane的思想,我们找到以每个元素为结尾的最大subarray sum记做dp1[i],那么反过来走一遍就可以得到以每个元素为开头的最大subarray sum记做dp2[i]。那么我们再遍历所有的-1元素i,那么dp1[i]+dp2[i]-nums[i]必然是包含了至少一个-1的max subarray sum。我们再全局找一个最大值即可。 - -#### 解法2 我们依然按照kadane算法的思路,但是设置两个临时变量:curSum0表示以当前元素为结尾、不包含-1的最大subarray sum,另外用curSum1表示以当前元素为结尾、已经包含-1的最大subarray sum。转移方程如下: ```cpp for (int i = 0; i < n; i++) @@ -29,3 +26,18 @@ } ``` 特别注意,curSum0的初始值可以是0,但是curSum1的初始值必须设置为INT_MIN. + +这样,总的时间复杂度是o(256n). + +#### 解法2 +我们发现在上面的表达式里,当nums[i]不是1也不是-1的时候,curSum0和curSum1都没有更新,循环是空跑的。所以我们其实只需要关心那些nums[i]非0的位置。 + +我们提前将所有是+1的位置放在数组pos0里,所有是-1的位置放在数组pos1里,分别用指针i和j来定位这两个数组元素。每次我们比较pos0[i]和pos1[j]哪个更小,前者更小的话,我们就知道pos0[i]这个位置上有一个+1,按照之前的第一个分支去更新curSum0和curSum1,然后自增i. 反之后面更小的话,我们就知道pos1[j]这个位置上有一个-1,就按照之前的第一个分支去更新curSum0和curSum1,别忘了自增j。 + +注意i和j可能会有其中某一个先走到尽头。如果其中一个走到尽头,那么我们必然移动另一个指针。 + +这样的时间复杂度是多少?看上去仍然是是o(256n),但事实上,我们每固定了一个最大频次的字符a,其他所有字符都被看做为最小频次的字符,且只访问了一次。所以时间复杂度优化到了o(26n). + + + + From 6ef8dbdd7871828eef227944beaf9e8d894c24be Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 09:59:29 -0700 Subject: [PATCH 1201/2729] Update 2272.Substring-With-Largest-Variance_v2.cpp --- ...272.Substring-With-Largest-Variance_v2.cpp | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp index a0626d730..043e7ad71 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp @@ -13,25 +13,24 @@ class Solution { for (auto& [b, pos1]: pos) { if (a==b) continue; - cout< Date: Sun, 11 Sep 2022 10:14:37 -0700 Subject: [PATCH 1202/2729] Create 2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp --- ...ntervals-Into-Minimum-Number-of-Groups.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp diff --git a/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp new file mode 100644 index 000000000..15d9c9a0b --- /dev/null +++ b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minGroups(vector>& intervals) + { + priority_queue, greater<>>pq; + + sort(intervals.begin(), intervals.end()); + + int ret = 0; + + for (int i=0; i= intervals[i][0]) + { + pq.push(intervals[i][1]); + } + else + { + pq.pop(); + pq.push(intervals[i][1]); + } + + ret = max(ret, (int)pq.size()); + } + + return ret; + } +}; From 55f1f5931c3a0b362b8be21840a3b0c7d1f977e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 10:15:07 -0700 Subject: [PATCH 1203/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9cfd7e0a9..9abb2ca65 100644 --- a/Readme.md +++ b/Readme.md @@ -422,6 +422,7 @@ [1383.Maximum-Performance-of-a-Team](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1383.Maximum-Performance-of-a-Team) (M+) [1834.Single-Threaded-CPU](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1834.Single-Threaded-CPU) (M) [1851.Minimum-Interval-to-Include-Each-Query](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1851.Minimum-Interval-to-Include-Each-Query) (H) +[2406.Divide-Intervals-Into-Minimum-Number-of-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups) (M+) * ``Arrangement with Stride`` [767.Reorganize-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/767.Reorganize-String) (M+) [1054.Distant-Barcodes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1054.Distant-Barcodes) (M+) From 7fa69272a2ef0cf1592e9d0f7fd40c6cb1e55e2c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 10:29:36 -0700 Subject: [PATCH 1204/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/Readme.md diff --git a/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/Readme.md b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/Readme.md new file mode 100644 index 000000000..867ed51ab --- /dev/null +++ b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/Readme.md @@ -0,0 +1,13 @@ +### 2406.Divide-Intervals-Into-Minimum-Number-of-Groups + +此题和`253.Meeting-Rooms-II`一模一样。 + +#### 解法1:PQ贪心 +我们将所有的会议按照开始时间排序。对于会议1而言,它占用了一个房间,那么该房间必然在某个t时刻(也就是该会议结束时间)之后才有空。然后我们查看下一个会议的开始时间,如果它在t之后,那么它就可以继续用那个房间;否则只好单开一个房间,这就意味着目前有两个房间正在被使用,我们需要了解的依然是它们各自available的时刻,那个先结束就可以更早地被重复利用。显然,我们就需要一个PQ来盛装所有正在被使用的房间,按照结束时间从早到晚排序。 + +所以基本的算法思想就是:对于下一个会议,查看PQ里是否有房间可以释放使用。是的话就PQ弹出该房间,并重置结束时刻再放入PQ;否则就往PQ里新增一个房间。整个过程中PQ.size()的最大值就是答案。 + +#### 解法2:扫描线 +利用扫描线算法可以轻松地得到最多有多少个区间同时存在。 + +这里需要注意的是有的区间的左右端点是重合的。所以我们要记录在任意时刻的共存区间的最大值。 From 0a4744200c01b337f065cf0670298c8ecaf61656 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 10:41:33 -0700 Subject: [PATCH 1205/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/Readme.md b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/Readme.md index 867ed51ab..f430d8846 100644 --- a/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/Readme.md +++ b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/Readme.md @@ -10,4 +10,4 @@ #### 解法2:扫描线 利用扫描线算法可以轻松地得到最多有多少个区间同时存在。 -这里需要注意的是有的区间的左右端点是重合的。所以我们要记录在任意时刻的共存区间的最大值。 +这里需要注意的是此题允许的那个区间的左右端点是重合的。如果我们在某一个时刻累加所有的新增会议和结束会议,那么可能会得到互相抵消的结果。解决方案很巧妙,我们将所有的双闭区间处理为左闭右开的区间。对于[left,right],我们在`left`时刻加入会议,在`right+1`时刻退出会议即可。 From 8fa0324a15149a84294328d560b560fde81a32d0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 10:42:01 -0700 Subject: [PATCH 1206/2729] Create 2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v2.cpp --- ...rvals-Into-Minimum-Number-of-Groups_v2.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v2.cpp diff --git a/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v2.cpp b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v2.cpp new file mode 100644 index 000000000..564b86952 --- /dev/null +++ b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minMeetingRooms(vector>& intervals) + { + mapMap; // {time, diff} + for (auto& interval: intervals) + { + Map[interval[0]]+=1; + Map[interval[1]+1]-=1; + } + + int sum = 0; + int ret = 0; + for (auto& [time, diff]: Map) + { + sum += diff; + ret = max(ret, sum); + } + return ret; + } +}; From ddd6d8cb70db07630b95f02fe992643d15a37c23 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 10:42:13 -0700 Subject: [PATCH 1207/2729] Rename 2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp to 2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v1.cpp --- ...=> 2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/{2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp => 2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v1.cpp} (100%) diff --git a/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp b/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v1.cpp similarity index 100% rename from Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups.cpp rename to Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups/2406.Divide-Intervals-Into-Minimum-Number-of-Groups_v1.cpp From 46129090d139de763fe4cf768c9e4ea9ec21c987 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 10:43:57 -0700 Subject: [PATCH 1208/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9abb2ca65..1c2e19ece 100644 --- a/Readme.md +++ b/Readme.md @@ -415,6 +415,7 @@ [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) [2402.Meeting-Rooms-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2402.Meeting-Rooms-III) (M+) * ``Sort+PQ`` +[253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) [857.Minimum-Cost-to-Hire-K-Workers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers) (H) From 5d24ad6b9c9ed2cce0aabb22d0bb0cb90926454d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 11:20:43 -0700 Subject: [PATCH 1209/2729] Create 2407.Longest-Increasing-Subsequence-II.cpp --- ...2407.Longest-Increasing-Subsequence-II.cpp | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 Segment_Tree/2407.Longest-Increasing-Subsequence-II/2407.Longest-Increasing-Subsequence-II.cpp diff --git a/Segment_Tree/2407.Longest-Increasing-Subsequence-II/2407.Longest-Increasing-Subsequence-II.cpp b/Segment_Tree/2407.Longest-Increasing-Subsequence-II/2407.Longest-Increasing-Subsequence-II.cpp new file mode 100644 index 000000000..2688003fe --- /dev/null +++ b/Segment_Tree/2407.Longest-Increasing-Subsequence-II/2407.Longest-Increasing-Subsequence-II.cpp @@ -0,0 +1,103 @@ +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MIN; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + +class Solution { +public: + int lengthOfLIS(vector& nums, int k) + { + int x = *max_element(nums.begin(), nums.end()); + SegTreeNode* root = new SegTreeNode(0, x, 0); + + int ret = 0; + + for (auto x: nums) + { + int len = root->queryRange(max(0, x-k), max(0, x-1)); + root->updateRange(x, x , len+1); + ret = max(ret, 1+len); + } + + return ret; + + } +}; From 0c5663bc0510f17357931f938d723b72cbafdacf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 11:21:13 -0700 Subject: [PATCH 1210/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1c2e19ece..068912233 100644 --- a/Readme.md +++ b/Readme.md @@ -288,6 +288,7 @@ [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2286.Booking-Concert-Tickets-in-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups) (H-) +[2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 5417c1d2029570576d2fbd22a386d34b9138804c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 11:40:05 -0700 Subject: [PATCH 1211/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Segment_Tree/2407.Longest-Increasing-Subsequence-II/Readme.md diff --git a/Segment_Tree/2407.Longest-Increasing-Subsequence-II/Readme.md b/Segment_Tree/2407.Longest-Increasing-Subsequence-II/Readme.md new file mode 100644 index 000000000..454ff5cd4 --- /dev/null +++ b/Segment_Tree/2407.Longest-Increasing-Subsequence-II/Readme.md @@ -0,0 +1,15 @@ +### 2407.Longest-Increasing-Subsequence-II + +本题思考的切入点其实是DP。对于`nums[i]=x`,我们需要检查i之前的所有位置j,如果有`y=nums[j]`的值满足`[x-k,x-1]`之间,那么就有`dp[i]=max(dp[j]+1)`。显然这是一个N^2的解法,该如何改进呢? + +我们可以发现,在索引上,j的位置是不确定的,但是在值域上y的范围是连续的。我们是否可以将求dp[j]转变为求dp[y]呢? + +对于一个连续的区间的最大值,我们有两个想法:线段树求区间最值,或者双端队列求sliding window max。在本题里,随着i的变化,x不是单调的,所以[x-k,x-1]也不是单向移动的sliding window。所以这道题的解题工具就是线段树。 + +此时我们再观察所有元素的值域范围是0到1e5,这就意味着在内存里开辟这么大的线段树是完全可行的。对于线段树的叶子节点v,我们存储以v为结尾的、符合条件的subsequence有多少。注意,v是指数值,而不是index。 + +所以我们的算法就是反复做两步操作: +1. 对于当前`nums[i]=x`,我们在线段树里寻找[x-k,x-1]里最大值len +2. 于是我们可以对线段树的节点x更新为1+len。 + +最终答案就是整棵线段树里叶子节点的最大值。 From 4d39d86214c928c2f4e0b336c950dc15b72a8795 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 14:38:38 -0700 Subject: [PATCH 1212/2729] Update 774.Minimize-Max-Distance-to-Gas-Station_pq.cpp --- ...Minimize-Max-Distance-to-Gas-Station_pq.cpp | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station/774.Minimize-Max-Distance-to-Gas-Station_pq.cpp b/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station/774.Minimize-Max-Distance-to-Gas-Station_pq.cpp index 4b8a13df6..4bfa71ae2 100644 --- a/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station/774.Minimize-Max-Distance-to-Gas-Station_pq.cpp +++ b/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station/774.Minimize-Max-Distance-to-Gas-Station_pq.cpp @@ -2,17 +2,25 @@ class Solution { public: double minmaxGasDist(vector& stations, int K) { + double ub = double(stations.back()-stations[0]) / (K + 1); + priority_queue>pq; for (int i=1; i0) { double space = pq.top().first; - int insertNum = pq.top().second; + int parts = pq.top().second; pq.pop(); - pq.push({space*insertNum/(insertNum+1),insertNum+1}); + pq.push({space*parts/(parts+1), parts+1}); + K--; } return pq.top().first; From 7e2a7a933c912deae2cab52f53e96167e75fb65f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 14:51:03 -0700 Subject: [PATCH 1213/2729] Update Readme.md --- .../Readme.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station/Readme.md b/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station/Readme.md index 282a76dd1..77d1db14a 100644 --- a/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station/Readme.md +++ b/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station/Readme.md @@ -2,15 +2,13 @@ #### 解法1:贪心法 -贪心法有非常巧妙的思想,这里用到了pq. +贪心法有非常巧妙的思想,这里用到了大顶堆的优先对了. 队列里放置的是`{space, parts}`,表示有连续parts个长度为space的区间。注意,`space*parts`其实代表的一定是某两个加油站之间的距离。最开始时,我们放入所有的`{stations[i]-stations[i-1], 1}`。 -首先我们将所有老加油站之间的间隔距离放入pq,默认是大顶堆,这些老加油站的间隔都没有新加油站插入。那么,对于队首的这个间距最大,说明我们要对其下手,先尝试将这个间距除以2,这里除以2表明原本是没有新加油站的,现在加入一个。然后将这个新间隔放入队列。 +如果我们还有增加加油站的名额,那么必然是对PQ的队首元素`{space, parts}`操作,试图将当前全局最大的这个space降下来。我们只需要试图在`space*parts`这个区段里再增加一个。于是我们弹出队首元素之后,再往PQ里放入`{space*parts/(parts+1), parts+1}`即可。 -每次我们取队首元素,总是得到的是(当前最大的)某两个老加油站之间的新间隔,以及这两个老加油站之间插入的新加油站数量m。我们需要做的,是重新规划这两个老加油站之间的间隔,改成插入的新加油站数量为m+1. +重复上述过程,直至我们用完了所有新增加油站的配额。此时队首元素的space,就是当前最大的新加油站的间距。 -重复上述过程,直至加入新加油站的总是达到了K。此时队首的老加油站之间的新间距,就是整体最大的间距。 - -这个方法非常巧妙,只可惜仍然超时。 +这个方法非常巧妙,只可惜仍然超时。这里有一个改进的方法。我们可以知道,如果所有的旧加油站不存在的话,那么我们直接可以得到最优的最大间距,即平分整个数轴,得到`ub = (stations.back()-stations[0])/(K+1)`。现在由于这些旧加油站的存在,可以帮助我们将最大间距变得更小。所以对于任意两个旧加油站之间的dist,我们至少应该拆分为`dist/ub`个parts,使得细分的space先一步到位直接逼近ub,也就是提前预定了一些新加油站的数目。这样可以提高效率,避免对新加油站一个一个的配置。 #### 解法2:二分法 @@ -21,4 +19,4 @@ 最后知道二分的搜索精度小于1e-6. -[Leetcode Link](https://leetcode.com/problems/minimize-max-distance-to-gas-station) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/minimize-max-distance-to-gas-station) From e508d144f8e89416683cbd35940543b7616245bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Sep 2022 23:36:43 -0700 Subject: [PATCH 1214/2729] Update 2272.Substring-With-Largest-Variance_v1.cpp --- ...272.Substring-With-Largest-Variance_v1.cpp | 68 +++++++------------ 1 file changed, 24 insertions(+), 44 deletions(-) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v1.cpp b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v1.cpp index 9180ed22d..a6128c3ff 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v1.cpp +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v1.cpp @@ -2,54 +2,34 @@ class Solution { public: int largestVariance(string s) { - vectorcount(26,0); - for (auto x: s) - count[x-'a']++; - - int ret = 0; int n = s.size(); - for (int i=0; i<26; i++) - for (int j=0; j<26; j++) - { - if (i==j) continue; - if (count[i]==0 || count[j]==0) continue; - vectorarr(n, 0); - for (int k=0; k&nums) - { - int n = nums.size(); - int curSum0 = 0; - int curSum1 = INT_MIN/2; + unordered_setSet(s.begin(), s.end()); + int ret = 0; - - for (int i = 0; i < n; i++) - { - if (nums[i]==1) - { - curSum1 = curSum1+nums[i]; - curSum0 = max(curSum0+nums[i], nums[i]); - } - else if (nums[i] == -1) + + for (auto a: Set) + for (auto b: Set) { - curSum1 = max(nums[i], max(curSum0, curSum1)+nums[i]); - curSum0 = 0; + if (a==b) continue; + int curSum0 = 0, curSum1 = INT_MIN/2; + + for (int i=0; i Date: Sun, 11 Sep 2022 23:42:23 -0700 Subject: [PATCH 1215/2729] Update 2272.Substring-With-Largest-Variance_v2.cpp --- ...272.Substring-With-Largest-Variance_v2.cpp | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp index 043e7ad71..142b2e978 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/2272.Substring-With-Largest-Variance_v2.cpp @@ -3,25 +3,26 @@ class Solution { int largestVariance(string s) { int n = s.size(); - map>pos; + unordered_map>Map; for (int i=0; i Date: Tue, 13 Sep 2022 00:03:51 -0700 Subject: [PATCH 1216/2729] Update Readme.md --- Greedy/1536.Minimum-Swaps-to-Arrange-a-Binary-Grid/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/1536.Minimum-Swaps-to-Arrange-a-Binary-Grid/Readme.md b/Greedy/1536.Minimum-Swaps-to-Arrange-a-Binary-Grid/Readme.md index 22c6e6bbe..c4f323fb0 100644 --- a/Greedy/1536.Minimum-Swaps-to-Arrange-a-Binary-Grid/Readme.md +++ b/Greedy/1536.Minimum-Swaps-to-Arrange-a-Binary-Grid/Readme.md @@ -2,7 +2,7 @@ 本题先进行一下转换。将每行末尾的零的个数统计一下,得到数组zeros,即zeros[i]表示第i行末尾的零的个数。我们的目标是将zeros通过adjacent swap操作,变成一个数组target,其中target[i]>=n-1-i. 求最小的操作数。 -我们首先考虑target[0],它的要求最高(需要有n-1个零)。我们考察所有的行,看看有哪些满足条件。加入有a和b两行满足条件,即zeros[a]>=n-1,zeros[b]>=n-1,那么我们应该选择将哪一行挪到第0行的位置上来呢?我们不妨举个例子: +我们首先考虑target[0],它的要求最高(需要有n-1个零)。我们考察所有的行,看看有哪些满足条件。假如有a和b两行满足条件,即zeros[a]>=n-1,zeros[b]>=n-1,那么我们应该选择将哪一行挪到第0行的位置上来呢?我们不妨举个例子: ``` X X X a X b X ``` From cbed4da31ad1fc86c219f165fdd5e8cb781d5ba5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 15 Sep 2022 06:39:34 -0700 Subject: [PATCH 1217/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 068912233..954874fd9 100644 --- a/Readme.md +++ b/Readme.md @@ -994,7 +994,7 @@ [400.n-th-digit](https://github.com/wisdompeak/LeetCode/tree/master/Math/400.n-th-digit) (M) [441.Arranging-Coins](https://github.com/wisdompeak/LeetCode/tree/master/Math/441.Arranging-Coins) (M-) [628.Maximum-Product-of-Three-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Math/628.Maximum-Product-of-Three-Numbers) (M) -[672.Bulb-Switcher-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/672.Bulb-Switcher-II) (H) +[672.Bulb-Switcher-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/672.Bulb-Switcher-II) (H) [754.Reach-a-Number](https://github.com/wisdompeak/LeetCode/tree/master/Math/754.Reach-a-Number) (H) [829.Consecutive-Numbers-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Math/829.Consecutive-Numbers-Sum) (M) [878.Nth-Magical-Number](https://github.com/wisdompeak/LeetCode/tree/master/Math/878.Nth-Magical-Number) (M+) From 4c9122962443e4db832e58cf7951c3bc10c528a0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 15 Sep 2022 08:03:21 -0700 Subject: [PATCH 1218/2729] Update 087.Scramble-String.cpp --- .../087.Scramble-String.cpp | 59 ++++++++++++++----- 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/Recursion/087.Scramble-String/087.Scramble-String.cpp b/Recursion/087.Scramble-String/087.Scramble-String.cpp index a9a6c2a8a..854ab8ba1 100644 --- a/Recursion/087.Scramble-String/087.Scramble-String.cpp +++ b/Recursion/087.Scramble-String/087.Scramble-String.cpp @@ -1,25 +1,54 @@ class Solution { + int memo[31][31][31]; + int n; + string s1, s2; public: - bool isScramble(string s1, string s2) + bool isScramble(string s1, string s2) { - int n=s1.size(); - if (n==1) return (s1==s2); + n = s1.size(); + this->s1 = s1; + this->s2 = s2; - string temp1=s1; - sort(temp1.begin(),temp1.end()); - string temp2=s2; - sort(temp2.begin(),temp2.end()); - if (temp1!=temp2) - return false; + for (int i=0; i Date: Thu, 15 Sep 2022 08:06:18 -0700 Subject: [PATCH 1219/2729] Update Readme.md --- Recursion/087.Scramble-String/Readme.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Recursion/087.Scramble-String/Readme.md b/Recursion/087.Scramble-String/Readme.md index 141cd3ee6..7ee134fde 100644 --- a/Recursion/087.Scramble-String/Readme.md +++ b/Recursion/087.Scramble-String/Readme.md @@ -1,12 +1,13 @@ ### 087.Scramble-String -基本的思想就是:在S1上找到一个切割点,左边长度为i, 右边长为len - i。 有2种情况表明它们是IsScramble +本题的数据规模不大,所以暴力递归即可。基本的思想就是:在S1上找到一个切割点,左边长度为i, 右边长为len - i。 有2种情况表明它们是IsScramble -(1). S1的左边和S2的左边是IsScramble, S1的右边和S2的右边是IsScramble +(1) S1的左边和S2的左边是IsScramble, S1的右边和S2的右边是IsScramble -(2). S1的左边和S2的右边是IsScramble, S1的右边和S2的左边是IsScramble (实际上是交换了S1的左右子树) +(2) S1的左边和S2的右边是IsScramble, S1的右边和S2的左边是IsScramble (实际上是交换了S1的左右子树) -我们可以在递归中加适当的剪枝:在进入递归前,先把2个字符串排序,再比较,如果不相同,则直接退出掉。 +我们可以在递归中加适当的剪枝:在进入递归前,先直接比较2个字符串,如果相同则直接返回true。 +另外,本题需要记忆化以提高效率。 -[Leetcode Link](https://leetcode.com/problems/scramble-string) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/scramble-string) From ff6e9f7df7498d7982d1d381e47ddd7472c4c661 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Sep 2022 14:44:38 -0700 Subject: [PATCH 1220/2729] Create 2411.Smallest-Subarrays-With-Maximum-Bitwise-OR.cpp --- ...lest-Subarrays-With-Maximum-Bitwise-OR.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR.cpp diff --git a/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR.cpp b/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR.cpp new file mode 100644 index 000000000..10660406a --- /dev/null +++ b/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector smallestSubarrays(vector& nums) + { + int n = nums.size(); + int j = n-1; + vectorrets(n); + vectorcount(32); + for (int i=n-1; i>=0; i--) + { + for (int k=0; k<32; k++) + count[k] += ((nums[i]>>k)&1); + + + while (j>i && isOK(nums[j], count)) + { + for (int k=0; k<32; k++) + count[k] -= ((nums[j]>>k)&1); + j--; + } + + rets[i] = j-i+1; + } + return rets; + + } + + bool isOK(int num, vector&count) + { + for (int k=0; k<32; k++) + { + if (count[k] > 0 && (count[k] - ((num>>k)&1) <= 0)) + return false; + } + return true; + } +}; From 80d1e6511da630e9d32c934d799d174c70dd10f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Sep 2022 14:45:51 -0700 Subject: [PATCH 1221/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 954874fd9..cd9f2c86c 100644 --- a/Readme.md +++ b/Readme.md @@ -46,6 +46,7 @@ [424.Longest-Repeating-Character-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/424.Longest-Repeating-Character-Replacement) (H-) [2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) [2401.Longest-Nice-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2401.Longest-Nice-Subarray) (H-) +[2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 878ee1d296efe5feefeb9bc41a489abff937f5f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Sep 2022 15:10:52 -0700 Subject: [PATCH 1222/2729] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md diff --git a/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md b/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md new file mode 100644 index 000000000..4939f9b7f --- /dev/null +++ b/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md @@ -0,0 +1,19 @@ +### 2411.Smallest-Subarrays-With-Maximum-Bitwise-OR + +我们设想,对于i而言,如果将这个区间的右边界j设置为n-1,那么必然能够得到Maximum Bitwise OR,记做OrSum. 我们该如何减小这个区间但是又不影响OrSum的值呢?最基本的想法就是,先尝试看看去掉nums[j],答案还是OrSum吗?我们如何验证呢,是将[i,j-1]区间内的所有元素再做一遍OR操作吗?显然这个效率太低了。 + +我们这样思考:如果去掉nums[j]对于OrSum没有影响,说明对于nums[j]里某个是1的bit位而言,nums[i:j-1]里必然已经有至少一个元素在该bit位上是1了。 这就提示我们需要统计一下nums[i:j]里面在每个bit位上的1的总个数。如果对于某个bit位,区间[i,j]里面有三个1,且nums[j]本身就是1,那么如果把j刨除这个区间后,OR[i:j-1]在这个bit位上不受影响。再比如,如果对于某个bit位,区间[i,j]里面只有一个1,且nums[j]本身就是1,那么如果把j刨除这个区间后,OrSum[i:j-1]在这个bit位上就是0了,显然就不会是maximum Bitwise OR了,所以我们不能将j排除。 + +所以如果我们已知一个区间[i:j]能够得到关于i的maximum bitwise or,并且有如上的count计数器(记录32个bit位里的1的个数),那么能否缩小右区间的范围j,就看 +```cpp +for (int k=0; k<32; k++) +{ + if (count[k]==1 && ((nums[j]>>k)&1) { + return false; + } +} +return true; +``` +根据以上的check函数,我们就可以一路缩小j,直至得到关于i的最小的subarray。 + +那么此时我们想得到关于i-1的答案,是否需要重新将j放回n-1的位置,重复以上的步骤呢?其实不必。因为我们已知[j+1:n-1]的各个位置上的1bit都完全与[i:j]区间重复了。因为[i:j]的存在,[j+1:n-1]这部分区间对于i-1而言也是没有用的。所以当我们考察i-1的答案时,不需要重置j,直接继承i对应的区间右端点即可。 From d8b707386712ad778140ffc8de1b8d129aabdc61 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Sep 2022 15:11:48 -0700 Subject: [PATCH 1223/2729] Update Readme.md --- .../2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md b/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md index 4939f9b7f..ebac0080d 100644 --- a/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md +++ b/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR/Readme.md @@ -2,7 +2,7 @@ 我们设想,对于i而言,如果将这个区间的右边界j设置为n-1,那么必然能够得到Maximum Bitwise OR,记做OrSum. 我们该如何减小这个区间但是又不影响OrSum的值呢?最基本的想法就是,先尝试看看去掉nums[j],答案还是OrSum吗?我们如何验证呢,是将[i,j-1]区间内的所有元素再做一遍OR操作吗?显然这个效率太低了。 -我们这样思考:如果去掉nums[j]对于OrSum没有影响,说明对于nums[j]里某个是1的bit位而言,nums[i:j-1]里必然已经有至少一个元素在该bit位上是1了。 这就提示我们需要统计一下nums[i:j]里面在每个bit位上的1的总个数。如果对于某个bit位,区间[i,j]里面有三个1,且nums[j]本身就是1,那么如果把j刨除这个区间后,OR[i:j-1]在这个bit位上不受影响。再比如,如果对于某个bit位,区间[i,j]里面只有一个1,且nums[j]本身就是1,那么如果把j刨除这个区间后,OrSum[i:j-1]在这个bit位上就是0了,显然就不会是maximum Bitwise OR了,所以我们不能将j排除。 +我们这样思考:如果去掉nums[j]对于OrSum没有影响,说明对于nums[j]里某个是1的bit位而言,nums[i:j-1]里必然已经有至少一个元素在该bit位上是1了。 这就提示我们需要统计一下nums[i:j]里面在每个bit位上的1的总个数。举个例子:如果对于某个bit位,区间[i:j]里面有三个1,且nums[j]本身就是1,那么如果把j刨除这个区间后,OR[i:j-1]在这个bit位上不受影响。再比如,如果对于某个bit位,区间[i:j]里面只有一个1,且nums[j]本身就是1,那么如果把j刨除这个区间后,OrSum[i:j-1]在这个bit位上就是0了,显然就不会是maximum Bitwise OR了,所以我们不能将j排除。 所以如果我们已知一个区间[i:j]能够得到关于i的maximum bitwise or,并且有如上的count计数器(记录32个bit位里的1的个数),那么能否缩小右区间的范围j,就看 ```cpp From d82c53e2ea19523983eb03f642eeb44073fe1c1b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Sep 2022 20:15:55 -0700 Subject: [PATCH 1224/2729] Create 2412.Minimum-Money-Required-Before-Transactions.cpp --- ...mum-Money-Required-Before-Transactions.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Greedy/2412.Minimum-Money-Required-Before-Transactions/2412.Minimum-Money-Required-Before-Transactions.cpp diff --git a/Greedy/2412.Minimum-Money-Required-Before-Transactions/2412.Minimum-Money-Required-Before-Transactions.cpp b/Greedy/2412.Minimum-Money-Required-Before-Transactions/2412.Minimum-Money-Required-Before-Transactions.cpp new file mode 100644 index 000000000..f1fc09b03 --- /dev/null +++ b/Greedy/2412.Minimum-Money-Required-Before-Transactions/2412.Minimum-Money-Required-Before-Transactions.cpp @@ -0,0 +1,32 @@ +using LL = long long; +class Solution { +public: + long long minimumMoney(vector>& transactions) + { + + sort(transactions.begin(), transactions.end(), [](vector&a, vector&b){return a[1] Date: Sat, 17 Sep 2022 20:16:22 -0700 Subject: [PATCH 1225/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index cd9f2c86c..4f50f878b 100644 --- a/Readme.md +++ b/Readme.md @@ -1189,6 +1189,7 @@ [1996.The-Number-of-Weak-Characters-in-the-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1996.The-Number-of-Weak-Characters-in-the-Game) (M+) [2250.Count-Number-of-Rectangles-Containing-Each-Point](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point) (H-) [2343.Query-Kth-Smallest-Trimmed-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2343.Query-Kth-Smallest-Trimmed-Number) (H-) +[2412.Minimum-Money-Required-Before-Transactions](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2412.Minimum-Money-Required-Before-Transactions) (H-) * ``Indexing Sort`` [041.First-Missing-Positive](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/041.First-Missing-Positive/Readme.md) (H) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 28c3a0ad958ae5623596dcb3dbd3042ab9105df6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Sep 2022 20:41:37 -0700 Subject: [PATCH 1226/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/2412.Minimum-Money-Required-Before-Transactions/Readme.md diff --git a/Greedy/2412.Minimum-Money-Required-Before-Transactions/Readme.md b/Greedy/2412.Minimum-Money-Required-Before-Transactions/Readme.md new file mode 100644 index 000000000..9729dcac1 --- /dev/null +++ b/Greedy/2412.Minimum-Money-Required-Before-Transactions/Readme.md @@ -0,0 +1,11 @@ +### 2412.Minimum-Money-Required-Before-Transactions + +本题在排序的时候会有这么几点思路:应该把cost大的放在前面,这样提高门槛,从而就对初始资金的要求更高。也应该把净亏损最大的放在前面,这样让手头的现金尽早为负,从而也不得不提升初始资金。那么我们如何平衡这两者的关系呢?事实上,强行从这方面想并不可行。 + +我们考虑将所有交易分成两大类。 + +首先,对于能够有净赚的交易,必然会使得手头的现金越来越宽裕。所以为了提高初始难度,必然要把这些能净赚的项目放在最后去做。同时,对于这些净赚的项目,我们必然要把cost最高的放第一个。因为我们把门槛低的先做的话,会使得手头的资金得到增长,可能会更轻松地跨越原本门槛更高的其他交易。所以我们将所有净赚的交易按照cost降序排列:如果我们能有资本启动第一个项目,那么其他项目自然也能完成。我们记第一个项目的门槛是 maxCostForNetGain. + +其次,对于净亏的交易,我们该如何安排呢?因为是净亏,所以越做资本越少,等到做最后一个交易之前,资本是历史上的最低点。我们要增加难度的话,需要将在这个历史最低点之后,跟上一个门槛比较高的交易。这个差值是全局最大的挑战。我们来分析一下这个时刻:假设我们挑选最后一个交易的净亏项目是`(cost, back)`,那么在它之前,我们的总资产,即净亏总额是`totalLoss - (back-cost)`,注意这是一个负数,且totalLoss是所有亏损交易的总净亏额。此时我们想要从净亏跳跃至能够着cost的门槛,其中的差距是`diff = cost - (totalLoss - (back-cost)) = back - totalLoss`. 我们发现,`totalLoss`是一个常量,所以要最大化`diff`,只需要寻找`back`最大的交易即可。 + +于是依次类推,对于倒数第二个净亏交易,我们也选剩下的里面`back`最大的...所以我们对于所有的净亏交易,只要按照back递增排序即可。然后对于所有的净赚交易,按照cost递减排序即可。 From dff4abfbf462fca3b7d3f098b97df84021633fe9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Sep 2022 21:01:37 -0700 Subject: [PATCH 1227/2729] Update 2412.Minimum-Money-Required-Before-Transactions.cpp --- .../2412.Minimum-Money-Required-Before-Transactions.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Greedy/2412.Minimum-Money-Required-Before-Transactions/2412.Minimum-Money-Required-Before-Transactions.cpp b/Greedy/2412.Minimum-Money-Required-Before-Transactions/2412.Minimum-Money-Required-Before-Transactions.cpp index f1fc09b03..1f0b5bfbc 100644 --- a/Greedy/2412.Minimum-Money-Required-Before-Transactions/2412.Minimum-Money-Required-Before-Transactions.cpp +++ b/Greedy/2412.Minimum-Money-Required-Before-Transactions/2412.Minimum-Money-Required-Before-Transactions.cpp @@ -3,7 +3,6 @@ class Solution { public: long long minimumMoney(vector>& transactions) { - sort(transactions.begin(), transactions.end(), [](vector&a, vector&b){return a[1] Date: Sun, 18 Sep 2022 12:17:21 -0700 Subject: [PATCH 1228/2729] Update and rename 156.Binary Tree Upside Down.cpp to 156.Binary-Tree-Upside-Down.cpp --- .../156.Binary Tree Upside Down.cpp | 44 ------------------- .../156.Binary-Tree-Upside-Down.cpp | 30 +++++++++++++ 2 files changed, 30 insertions(+), 44 deletions(-) delete mode 100644 Tree/156.Binary-Tree-Upside-Down/156.Binary Tree Upside Down.cpp create mode 100644 Tree/156.Binary-Tree-Upside-Down/156.Binary-Tree-Upside-Down.cpp diff --git a/Tree/156.Binary-Tree-Upside-Down/156.Binary Tree Upside Down.cpp b/Tree/156.Binary-Tree-Upside-Down/156.Binary Tree Upside Down.cpp deleted file mode 100644 index e6199ab46..000000000 --- a/Tree/156.Binary-Tree-Upside-Down/156.Binary Tree Upside Down.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* upsideDownBinaryTree(TreeNode* root) - { - if (root==NULL) return NULL; - - if (root->left==NULL) - return root; - else - { - TreeNode* nextRoot = root->left; - TreeNode* nextRootAlien = new TreeNode(root->left->val); - nextRootAlien->right = root; - nextRootAlien->left = root->right; - root->left=NULL; - root->right=NULL; - return DFS(nextRoot,nextRootAlien); - } - } - - TreeNode* DFS(TreeNode* root, TreeNode* rootAlien) - { - if (root->left==NULL) - return rootAlien; - else - { - TreeNode* nextRoot = root->left; - TreeNode* nextRootAlien = new TreeNode(root->left->val); - nextRootAlien->right = rootAlien; - nextRootAlien->left = root->right; - return DFS(nextRoot,nextRootAlien); - } - - } -}; diff --git a/Tree/156.Binary-Tree-Upside-Down/156.Binary-Tree-Upside-Down.cpp b/Tree/156.Binary-Tree-Upside-Down/156.Binary-Tree-Upside-Down.cpp new file mode 100644 index 000000000..be8711117 --- /dev/null +++ b/Tree/156.Binary-Tree-Upside-Down/156.Binary-Tree-Upside-Down.cpp @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* upsideDownBinaryTree(TreeNode* root) + { + if (root==NULL) return NULL; + if (root->left==NULL && root->right==NULL) return root; + + TreeNode* head = upsideDownBinaryTree(root->left); + TreeNode* node = head; + + while (node->right!=NULL) + node=node->right; + + node->left = root->right; + node->right = root; + root->left=NULL; + root->right=NULL; + + return head; + } +}; From 06e55b3f8c68feaf864ba1ee2570788ad5c6ba69 Mon Sep 17 00:00:00 2001 From: Xiao Sun Date: Sun, 18 Sep 2022 17:02:13 -0400 Subject: [PATCH 1229/2729] Update 1778.Shortest-Path-in-a-Hidden-Grid.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 起始点是500, 数据范围是 1<= i , j <= 500, 所以最大点可能是[999,999],但是因为最大点还需要检测边界,所以需要1001的长度(OJ Case 36)。 把矩阵改成1001之后提示stackoverflow, 把 dir 和 move 拉出去就可以通过了。 --- .../1778.Shortest-Path-in-a-Hidden-Grid.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/DFS/1778.Shortest-Path-in-a-Hidden-Grid/1778.Shortest-Path-in-a-Hidden-Grid.cpp b/DFS/1778.Shortest-Path-in-a-Hidden-Grid/1778.Shortest-Path-in-a-Hidden-Grid.cpp index 10cf6e11f..607d96ac8 100644 --- a/DFS/1778.Shortest-Path-in-a-Hidden-Grid/1778.Shortest-Path-in-a-Hidden-Grid.cpp +++ b/DFS/1778.Shortest-Path-in-a-Hidden-Grid/1778.Shortest-Path-in-a-Hidden-Grid.cpp @@ -12,17 +12,17 @@ typedef pair PII; class Solution { - int grid[1000][1000]; - int visited[1000][1000]; - int visited2[1000][1000]; + int grid[1001][1001]; + int visited[1001][1001]; + int visited2[1001][1001]; + vector dir{{-1,0},{1,0},{0,-1},{0,1}}; + vector move{'U','D','L','R'}; public: int findShortestPath(GridMaster &master) { visited[500][500] = 1; dfs(500, 500, master); - - auto dir = vector({{-1,0},{1,0},{0,-1},{0,1}}); - + queueq; q.push({500,500}); visited2[500][500]=1; @@ -56,8 +56,6 @@ class Solution { void dfs(int i, int j, GridMaster &master) { - auto dir = vector({{-1,0},{1,0},{0,-1},{0,1}}); - vector move({'U','D','L','R'}); grid[i][j] = 1; From ad4fec3b25ef0ad194a6cb88f7c7c774d36231c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 15:09:59 -0700 Subject: [PATCH 1230/2729] Update Readme.md --- .../2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md b/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md index 7b9964bac..9121b75cd 100644 --- a/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md +++ b/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid/Readme.md @@ -2,6 +2,6 @@ 此题是1944的升级版,区别在于本题允许存在相同的元素。 -基本思路是一致的。我们从左往右维护一个严格单调递减的栈。如果有新元素nums[i]大于等于栈顶元素,意味着这个栈顶元素今后的视线都会被nums[i]遮住再也看不到其他。所以将栈顶元素的计数器加1之后,就可以将这个栈顶元素移除了。 +基本思路是一致的。我们从左往右维护一个严格单调递减的栈。如果有新元素nums[i]大于等于栈顶元素,意味着这个栈顶元素今后的视线都会被nums[i]遮住再也看不到其他。所以将栈顶元素的计数器加1之后(对应的是它能看到nums[i]),就可以将这个栈顶元素移除了。 当该退栈的元素都拿走之后,此时的栈顶元素(如果存在)必然大于nums[i],理论上需要将这个栈顶元素的计时器也加1. 但是这里有一个特例,比如```3,1,1```。第二个1会把第一个1弹出再入栈,但是注意3虽然大于第二个1,可它是看不到第二个1的。因此,如果新元素nums[i]如果从栈顶刚弹出了与自己相同的元素,那么它就不能再被此时栈顶的大元素的计数器所加1(虽然大于nums[i]). From 8e6c01025ff6e40c5499034f2ada5c88f15b4f6c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 19:24:17 -0700 Subject: [PATCH 1231/2729] Create 2416.Sum-of-Prefix-Scores-of-Strings.cpp --- .../2416.Sum-of-Prefix-Scores-of-Strings.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Trie/2416.Sum-of-Prefix-Scores-of-Strings/2416.Sum-of-Prefix-Scores-of-Strings.cpp diff --git a/Trie/2416.Sum-of-Prefix-Scores-of-Strings/2416.Sum-of-Prefix-Scores-of-Strings.cpp b/Trie/2416.Sum-of-Prefix-Scores-of-Strings/2416.Sum-of-Prefix-Scores-of-Strings.cpp new file mode 100644 index 000000000..addabe4c5 --- /dev/null +++ b/Trie/2416.Sum-of-Prefix-Scores-of-Strings/2416.Sum-of-Prefix-Scores-of-Strings.cpp @@ -0,0 +1,57 @@ +class Solution { + class TrieNode + { + public: + TrieNode* next[26]; + int count; + TrieNode() + { + for (int i=0; i<26; i++) + next[i] = NULL; + count = 0; + } + }; +public: + TrieNode* root; + + void insert(string word) + { + TrieNode* node=root; + for (int i=0; inext[ch-'a']==NULL) + node->next[ch-'a']=new TrieNode(); + int prevCount = node->count; + node=node->next[ch-'a']; + node->count += 1; + } + } + + vector sumPrefixScores(vector& words) + { + root = new TrieNode(); + + for (string& word: words) + insert(word); + + int n = words.size(); + vectorrets(n); + + for (int i=0; inext[ch-'a']==NULL) + break; + node = node->next[ch-'a']; + sum += node->count; + } + rets[i] = sum; + } + + return rets; + } +}; From a99a245014c0db3a99f834c844e961791963d10c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 19:24:42 -0700 Subject: [PATCH 1232/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4f50f878b..890392c03 100644 --- a/Readme.md +++ b/Readme.md @@ -575,6 +575,7 @@ [1268.Search-Suggestions-System](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1268.Search-Suggestions-System) (H-) 1032. Stream of Characters (TBD) [1858.Longest-Word-With-All-Prefixes](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1858.Longest-Word-With-All-Prefixes) (M) +[2416.Sum-of-Prefix-Scores-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2416.Sum-of-Prefix-Scores-of-Strings) (M) * ``Trie and XOR`` [421.Maximum-XOR-of-Two-Numbers-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/421.Maximum-XOR-of-Two-Numbers-in-an-Array) (H-) [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) From 1b647a9af1e1b18e13f0e898719924c59e4b1f01 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 19:40:46 -0700 Subject: [PATCH 1233/2729] Create Readme.md --- Trie/2416.Sum-of-Prefix-Scores-of-Strings/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Trie/2416.Sum-of-Prefix-Scores-of-Strings/Readme.md diff --git a/Trie/2416.Sum-of-Prefix-Scores-of-Strings/Readme.md b/Trie/2416.Sum-of-Prefix-Scores-of-Strings/Readme.md new file mode 100644 index 000000000..1b6fb0621 --- /dev/null +++ b/Trie/2416.Sum-of-Prefix-Scores-of-Strings/Readme.md @@ -0,0 +1,3 @@ +### 2416.Sum-of-Prefix-Scores-of-Strings + +常规的字典树的应用。在建树的时候,我们给每个节点node标记一个count,表示从root->node的这条路径是多少个word的前缀。在查询的时候,我们在字典树里遍历word的前缀,所到之处的count就是当前前缀的score了。 From 78a0da3e90eb79b7cec4340501c0e492ff32ccc0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 20:00:32 -0700 Subject: [PATCH 1234/2729] Update 2416.Sum-of-Prefix-Scores-of-Strings.cpp --- .../2416.Sum-of-Prefix-Scores-of-Strings.cpp | 58 ++++++++----------- 1 file changed, 24 insertions(+), 34 deletions(-) diff --git a/Trie/2416.Sum-of-Prefix-Scores-of-Strings/2416.Sum-of-Prefix-Scores-of-Strings.cpp b/Trie/2416.Sum-of-Prefix-Scores-of-Strings/2416.Sum-of-Prefix-Scores-of-Strings.cpp index addabe4c5..2dfee6d00 100644 --- a/Trie/2416.Sum-of-Prefix-Scores-of-Strings/2416.Sum-of-Prefix-Scores-of-Strings.cpp +++ b/Trie/2416.Sum-of-Prefix-Scores-of-Strings/2416.Sum-of-Prefix-Scores-of-Strings.cpp @@ -9,49 +9,39 @@ class Solution { for (int i=0; i<26; i++) next[i] = NULL; count = 0; - } - }; -public: - TrieNode* root; - - void insert(string word) - { - TrieNode* node=root; - for (int i=0; inext[ch-'a']==NULL) - node->next[ch-'a']=new TrieNode(); - int prevCount = node->count; - node=node->next[ch-'a']; - node->count += 1; } - } - - vector sumPrefixScores(vector& words) - { - root = new TrieNode(); - - for (string& word: words) - insert(word); - - int n = words.size(); - vectorrets(n); + }; +public: + vector sumPrefixScores(vector& words) { + TrieNode* root = new TrieNode(); - for (int i=0; inext[ch-'a']==NULL) + node->next[ch-'a'] = new TrieNode(); + node = node->next[ch-'a']; + node->count += 1; + } + } + + vectorrets; + for (auto& word: words) + { + TrieNode* node = root; + int score = 0; + for (char ch: word) + { + if (node->next[ch-'a'] == NULL) break; node = node->next[ch-'a']; - sum += node->count; + score += node->count; } - rets[i] = sum; + rets.push_back(score); } - return rets; + return rets; } }; From 75665c62ca53db54c2c985fd990f8fb5f565856e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 20:50:15 -0700 Subject: [PATCH 1235/2729] Create 2355.Maximum-Number-of-Books-You-Can-Take.cpp --- ...5.Maximum-Number-of-Books-You-Can-Take.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Stack/2355.Maximum-Number-of-Books-You-Can-Take/2355.Maximum-Number-of-Books-You-Can-Take.cpp diff --git a/Stack/2355.Maximum-Number-of-Books-You-Can-Take/2355.Maximum-Number-of-Books-You-Can-Take.cpp b/Stack/2355.Maximum-Number-of-Books-You-Can-Take/2355.Maximum-Number-of-Books-You-Can-Take.cpp new file mode 100644 index 000000000..906d42e69 --- /dev/null +++ b/Stack/2355.Maximum-Number-of-Books-You-Can-Take/2355.Maximum-Number-of-Books-You-Can-Take.cpp @@ -0,0 +1,33 @@ +using LL = long long; +class Solution { +public: + long long maximumBooks(vector& books) + { + int n = books.size(); + vectordp(n); + stackstk; + + LL ret = 0; + for (int i=0; i books[i]-(i-stk.top())) + stk.pop(); + + if (!stk.empty()) + { + LL d = i - stk.top(); + dp[i] = dp[stk.top()] + ((LL)books[i] + (LL)books[i] - d + 1) * d /2; + } + else + { + LL d = min(i + 1, books[i]); + dp[i] = ((LL)books[i] + (LL)books[i] - d + 1) * d /2; + } + stk.push(i); + + ret = max(ret, dp[i]); + } + + return ret; + } +}; From 9b94c3ef54205b3d4c7f0712f0f0d5eba5e4a29b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 20:50:46 -0700 Subject: [PATCH 1236/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 890392c03..8ee98531e 100644 --- a/Readme.md +++ b/Readme.md @@ -365,6 +365,7 @@ [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) +[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) [1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) From 6a2772598b6566f8ded14b7b8b6f77723a371415 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 22:32:08 -0700 Subject: [PATCH 1237/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md diff --git a/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md b/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md new file mode 100644 index 000000000..2f1fe57d9 --- /dev/null +++ b/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md @@ -0,0 +1,13 @@ +### 2355.Maximum-Number-of-Books-You-Can-Take + +我们令dp[i]表示以i为结尾的区间所能获得的最大值。显然在这个区间里,位置i处一定会取满books[i]。 + +然后在dp[i]的前提下,我们考察i-1的位置。如果`books[i-1]>=books[i]-1`,那么意味着无法取满books[i-1],且显然,该位置的取值决定于`books[i]-1`. 类似地,在i-2处,如果`books[i-2]>=books[i]-2`,那么该位置能取的最大值是由books[i]-2决定的。依次往前类推,我们会经历一段逐个减1的等差数列。直至我们发现某处`books[j]i)如果依赖于dp[i],那么即`dp[k] = dp[i] + [i+1:k]的等差数列之和`,不需要再计算任何i之前的东西。相反,如果dp[k]不依赖于dp[i],那么意味着在i的位置上没有取满,自然[j+1:i-1]区间内也不会取满(因为这个区间的books值都高于以books[i]开始从后往前的等差序列)。 + +所以我们就可以设计一个单调栈。当考察新元素books[i]时,对于栈顶元素j,如果`books[j]>=books[i]-(i-j)`的话,就可以不断退栈: +1. 如果剩余有栈顶元素j,那么`dp[i] = dp[j] + area`,其中area是长度为`L = i-j`,最后一个元素是books[i],公差为1的等差数列之和。于是根据等差数列的求和公式`area = (books[i]-L+1 + books[i]) * L /2`. +2. 如果剩余没有栈顶元素,那么直接有`dp[i] = area`,其中area(可能)是长度为i+1,最后一个元素是books[i],公差为1的等差数列之和。特别注意,等差数列的第一个元素不能小于1。所以,这个等差数列的实际长度应该是`L = min(i+1, heights[i])`. 于是根据等差数列的求和公式`area = (books[i]-L+1 + books[i]) * L /2`. + +最后返回的是全局dp[i]的最大值。 From 868181f91d0328ca3c033ba0a1780ffb2a0de488 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 22:33:12 -0700 Subject: [PATCH 1238/2729] Update Readme.md --- Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md b/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md index 2f1fe57d9..62844fd6d 100644 --- a/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md +++ b/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md @@ -2,7 +2,7 @@ 我们令dp[i]表示以i为结尾的区间所能获得的最大值。显然在这个区间里,位置i处一定会取满books[i]。 -然后在dp[i]的前提下,我们考察i-1的位置。如果`books[i-1]>=books[i]-1`,那么意味着无法取满books[i-1],且显然,该位置的取值决定于`books[i]-1`. 类似地,在i-2处,如果`books[i-2]>=books[i]-2`,那么该位置能取的最大值是由books[i]-2决定的。依次往前类推,我们会经历一段逐个减1的等差数列。直至我们发现某处`books[j] books[i]-1`,根据规则意味着无法取满books[i-1],且显然,该位置的取值决定于`books[i]-1`. 类似地,在i-2处,如果`books[i-2] > books[i]-2`,那么该位置能取的最大值是由books[i]-2决定的。依次往前类推,我们会经历一段逐个减1的等差数列。直至我们发现某处`books[j] <= books[i]-(i-j)`,那么我们势必会在j处取books[j],于是自然就有`dp[i] = dp[j] + 长度为i-j且公差为1的等差数列之和`. 那么对于每个i,我们是否都要靠上述的方法逐一回溯之前的index来确定j的位置呢?实际上,当我们针对某个i确定了j之后,books[j+1:i-1]内的这些元素都可以舍弃不看了。因为未来的任何dp[k](其中k>i)如果依赖于dp[i],那么即`dp[k] = dp[i] + [i+1:k]的等差数列之和`,不需要再计算任何i之前的东西。相反,如果dp[k]不依赖于dp[i],那么意味着在i的位置上没有取满,自然[j+1:i-1]区间内也不会取满(因为这个区间的books值都高于以books[i]开始从后往前的等差序列)。 From ccb98911ebeada88d4a22ba45d67567f6057940e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Sep 2022 22:34:21 -0700 Subject: [PATCH 1239/2729] Update Readme.md --- Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md b/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md index 62844fd6d..336508368 100644 --- a/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md +++ b/Stack/2355.Maximum-Number-of-Books-You-Can-Take/Readme.md @@ -6,7 +6,7 @@ 那么对于每个i,我们是否都要靠上述的方法逐一回溯之前的index来确定j的位置呢?实际上,当我们针对某个i确定了j之后,books[j+1:i-1]内的这些元素都可以舍弃不看了。因为未来的任何dp[k](其中k>i)如果依赖于dp[i],那么即`dp[k] = dp[i] + [i+1:k]的等差数列之和`,不需要再计算任何i之前的东西。相反,如果dp[k]不依赖于dp[i],那么意味着在i的位置上没有取满,自然[j+1:i-1]区间内也不会取满(因为这个区间的books值都高于以books[i]开始从后往前的等差序列)。 -所以我们就可以设计一个单调栈。当考察新元素books[i]时,对于栈顶元素j,如果`books[j]>=books[i]-(i-j)`的话,就可以不断退栈: +所以我们就可以设计一个单调栈。当考察新元素books[i]时,对于栈顶元素j,如果`books[j] > books[i]-(i-j)`的话,就可以不断退栈: 1. 如果剩余有栈顶元素j,那么`dp[i] = dp[j] + area`,其中area是长度为`L = i-j`,最后一个元素是books[i],公差为1的等差数列之和。于是根据等差数列的求和公式`area = (books[i]-L+1 + books[i]) * L /2`. 2. 如果剩余没有栈顶元素,那么直接有`dp[i] = area`,其中area(可能)是长度为i+1,最后一个元素是books[i],公差为1的等差数列之和。特别注意,等差数列的第一个元素不能小于1。所以,这个等差数列的实际长度应该是`L = min(i+1, heights[i])`. 于是根据等差数列的求和公式`area = (books[i]-L+1 + books[i]) * L /2`. From e5aa6c5e10068aaf9f8d3c1fd14c94ac37a237cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 13:36:49 -0700 Subject: [PATCH 1240/2729] Create 2421.Number-of-Good-Paths.cpp --- .../2421.Number-of-Good-Paths.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths.cpp diff --git a/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths.cpp b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths.cpp new file mode 100644 index 000000000..105b1c4df --- /dev/null +++ b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths.cpp @@ -0,0 +1,66 @@ +class Solution { + vectorFather; + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (x>e [100005]; + + int numberOfGoodPaths(vector& vals, vector>& edges) + { + int n = vals.size(); + Father.resize(n); + for (int i=0; i>val2idx; + for (int i=0; iValSet(vals.begin(), vals.end()); + for (int v: ValSet) + { + for (auto& [v,x]: e[v]) + { + if (FindFather(v)!=FindFather(x)) + Union(v,x); + } + + unordered_mapcount; + for (auto idx: val2idx[v]) + { + int root = FindFather(idx); + count[root]++; + } + + ret += val2idx[v].size(); + for (auto& [v, num]: count) + ret += num*(num-1)/2; + } + + return ret; + + } +}; From af8f0f4a882c0d84a73c1b6148a58eec450f3e37 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 13:42:42 -0700 Subject: [PATCH 1241/2729] Update Readme.md --- Readme.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index 8ee98531e..382925549 100644 --- a/Readme.md +++ b/Readme.md @@ -918,15 +918,17 @@ [1202.Smallest-String-With-Swaps](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1202.Smallest-String-With-Swaps) (M+) [1319.Number-of-Operations-to-Make-Network-Connected](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1319.Number-of-Operations-to-Make-Network-Connected) (M+) [1632.Rank-Transform-of-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1632.Rank-Transform-of-a-Matrix) (H) -[1631.Path-With-Minimum-Effort](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1631.Path-With-Minimum-Effort) (H-) -[1697.Checking-Existence-of-Edge-Length-Limited-Paths](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1697.Checking-Existence-of-Edge-Length-Limited-Paths) (H-) [1724.Checking-Existence-of-Edge-Length-Limited-Paths-II](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1724.Checking-Existence-of-Edge-Length-Limited-Paths-II) (H+) [1722.Minimize-Hamming-Distance-After-Swap-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1722.Minimize-Hamming-Distance-After-Swap-Operations) (M+) -[803.Bricks-Falling-When-Hit](https://github.com/wisdompeak/LeetCode/tree/master/DFS/803.Bricks-Falling-When-Hit) (H) -[1970.Last-Day-Where-You-Can-Still-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1970.Last-Day-Where-You-Can-Still-Cross) (H-) [2076.Process-Restricted-Friend-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2076.Process-Restricted-Friend-Requests) (H-) [2092.Find-All-People-With-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2092.Find-All-People-With-Secret) (H-) [2157.Groups-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2157.Groups-of-Strings) (H) +* ``Union in an order`` +[803.Bricks-Falling-When-Hit](https://github.com/wisdompeak/LeetCode/tree/master/DFS/803.Bricks-Falling-When-Hit) (H) +[1970.Last-Day-Where-You-Can-Still-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1970.Last-Day-Where-You-Can-Still-Cross) (H-) +[1631.Path-With-Minimum-Effort](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1631.Path-With-Minimum-Effort) (H-) +[1697.Checking-Existence-of-Edge-Length-Limited-Paths](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1697.Checking-Existence-of-Edge-Length-Limited-Paths) (H-) +[2421.Number-of-Good-Paths](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2421.Number-of-Good-Paths) (H) * ``Prime Factors`` [952.Largest-Component-Size-by-Common-Factor](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/952.Largest-Component-Size-by-Common-Factor) (H) [1627.Graph-Connectivity-With-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1627.Graph-Connectivity-With-Threshold) (M+) From 2a3b8338ca792d9e3d079185b8ea789ba60d8e6b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 14:11:58 -0700 Subject: [PATCH 1242/2729] Create 2421.Number-of-Good-Paths_v2.cpp --- .../2421.Number-of-Good-Paths_v2.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v2.cpp diff --git a/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v2.cpp b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v2.cpp new file mode 100644 index 000000000..9f7185160 --- /dev/null +++ b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v2.cpp @@ -0,0 +1,48 @@ +class Solution { + vectornext [100005]; + int ans = 0; + int n; + vector vals; +public: + int numberOfGoodPaths(vector& vals, vector>& edges) + { + this->vals = vals; + n = vals.size(); + for (auto& edge: edges) + { + next[edge[0]].push_back(edge[1]); + next[edge[1]].push_back(edge[0]); + } + dfs(0,-1); + return ans + n; + } + + mapdfs(int cur, int parent) + { + mapret; + ret[vals[cur]] += 1; + + for (int child: next[cur]) + { + if (child == parent) continue; + map tmp = dfs(child, cur); + + auto iter = tmp.lower_bound(vals[cur]); + tmp.erase(tmp.begin(), iter); + + if (tmp.size() > ret.size()) + swap(tmp, ret); + + for (auto& [val, count]: tmp) + { + if (ret.find(val)!=ret.end()) + ans += count * ret[val]; + } + + for (auto& [val, count]: tmp) + ret[val] += count; + } + + return ret; + } +}; From 9626949c602f7d6412c2189364f82130184af938 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 14:12:08 -0700 Subject: [PATCH 1243/2729] Rename 2421.Number-of-Good-Paths.cpp to 2421.Number-of-Good-Paths_v1.cpp --- ....Number-of-Good-Paths.cpp => 2421.Number-of-Good-Paths_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Union_Find/2421.Number-of-Good-Paths/{2421.Number-of-Good-Paths.cpp => 2421.Number-of-Good-Paths_v1.cpp} (100%) diff --git a/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths.cpp b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v1.cpp similarity index 100% rename from Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths.cpp rename to Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v1.cpp From 4361a6f6674a5dccabbc45fa2d09b02f096e30d4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 14:32:57 -0700 Subject: [PATCH 1244/2729] Create Readme.md --- Union_Find/2421.Number-of-Good-Paths/Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Union_Find/2421.Number-of-Good-Paths/Readme.md diff --git a/Union_Find/2421.Number-of-Good-Paths/Readme.md b/Union_Find/2421.Number-of-Good-Paths/Readme.md new file mode 100644 index 000000000..ce175f32f --- /dev/null +++ b/Union_Find/2421.Number-of-Good-Paths/Readme.md @@ -0,0 +1,14 @@ +### 2421.Number-of-Good-Paths + +#### 方法1:并查集 +我们看到元素个数是`3e4`,并不是特别好判断对于时间复杂度的要求。但是注意到数值大小的范围是1e5,这就提醒我们可以从数值大小出发。我们不妨尝试从小到大分析这些节点。 + +首先考虑数值为0的节点。多数情况下,它们应该都是离散的点。但是有些时候一些0节点是彼此联通的,那么在这个联通区间内,任意两个节点都是一条合法的path(因为经过的任意节点都是0)。 + +此时我们再考虑数值为1的节点。因为我们此时仅考虑数值是0或1的节点,我们仅限引入那些以1为一个端点、以0或1为另一个端点的边。加入这些边后,那么就可以拓展上面的联通区域。并且我们可以发现,在每个联通区域内,任意两个以1节点为端点的path都是合法的。我们只需要知道此时这些1节点在各自联通区域内的分布数量,就可以算出有多少个这样的path。 + +接下来我们在考虑数值为2的节点。类似地,我们引入所有端点数值不超过2的边,进一步扩展上述的图,有些区域会被进一步联通。在每个联通区域内,任意两个以2节点为端点的path都是合法的。 + +可见,这道题的算法就是并查集,从小到大地引入节点(和相应的边),构建联通关系。 + +为了操作上的方便,我们将所有的edge按照较大的端点分类。比如说e[2],表示所有以(数值)2节点为一端,以0/1/2节点为另一端的边的集合。这样方便我们按顺序往图里加入边。 From 6701bf739f7932ed826baa7ba5a49e2c1f8b4deb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 15:16:03 -0700 Subject: [PATCH 1245/2729] Update Readme.md --- Union_Find/2421.Number-of-Good-Paths/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Union_Find/2421.Number-of-Good-Paths/Readme.md b/Union_Find/2421.Number-of-Good-Paths/Readme.md index ce175f32f..507ba421a 100644 --- a/Union_Find/2421.Number-of-Good-Paths/Readme.md +++ b/Union_Find/2421.Number-of-Good-Paths/Readme.md @@ -12,3 +12,8 @@ 可见,这道题的算法就是并查集,从小到大地引入节点(和相应的边),构建联通关系。 为了操作上的方便,我们将所有的edge按照较大的端点分类。比如说e[2],表示所有以(数值)2节点为一端,以0/1/2节点为另一端的边的集合。这样方便我们按顺序往图里加入边。 + +#### 方法2:DFS +本题其实也可以按照普通的DFS来做。我们任意以某个节点(比如说0号节点)为根,看做一棵rooted tree. 类似于“path in a tree”的思想,对于每个节点node而言,我们想知道以它为turning point的合法path有多少。以此做不重不漏统计。 + +假设对于node而言,某个合法的path的端点数值是x(显然x必须大于等于vals[node]),我们只需要知道有多少条以x为端点、node为终点的合法路径。将它们两两组合即可。(注意实际操作时不是这个逻辑,应该每加入一个child,就算一遍组合)。 From 437c481964db122db4290497b363a8f370b5ed68 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 20:50:35 -0700 Subject: [PATCH 1246/2729] Update Readme.md --- Union_Find/2421.Number-of-Good-Paths/Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Union_Find/2421.Number-of-Good-Paths/Readme.md b/Union_Find/2421.Number-of-Good-Paths/Readme.md index 507ba421a..6612434c3 100644 --- a/Union_Find/2421.Number-of-Good-Paths/Readme.md +++ b/Union_Find/2421.Number-of-Good-Paths/Readme.md @@ -14,6 +14,8 @@ 为了操作上的方便,我们将所有的edge按照较大的端点分类。比如说e[2],表示所有以(数值)2节点为一端,以0/1/2节点为另一端的边的集合。这样方便我们按顺序往图里加入边。 #### 方法2:DFS -本题其实也可以按照普通的DFS来做。我们任意以某个节点(比如说0号节点)为根,看做一棵rooted tree. 类似于“path in a tree”的思想,对于每个节点node而言,我们想知道以它为turning point的合法path有多少。以此做不重不漏统计。 +本题其实也可以按照普通的DFS来做。我们任意以某个节点(比如说0号节点)为根,看做一棵rooted tree. 类似于“path in a tree”的思想,对于每个节点node而言,我们想知道以它为turning point的合法path有多少。以此做不重不漏的统计。 -假设对于node而言,某个合法的path的端点数值是x(显然x必须大于等于vals[node]),我们只需要知道有多少条以x为端点、node为终点的合法路径。将它们两两组合即可。(注意实际操作时不是这个逻辑,应该每加入一个child,就算一遍组合)。 +考虑对于node作为turning point的合法路径,假设其端点数值是x(显然x必须大于等于vals[node]),我们只需要知道每个子树里有多少条以x为端点、node为终点的合法单链(该单链里任何元素都不大于x)。将这些子树的这些单链彼此组合即可。 + +更具体地,对于每个node,我们设计一个数据结构`map ret`,其中key表示子树里节点的数值,val表示该数值的节点(可能有多个)到node的合法单链的数目(合法的意思是沿途的节点数值都小于key)。显然,为了保证单链的合法性,我们只需要在map里保存其中key值大于等于vals[node]的部分。对于node的每个孩子的递归结果`map tmp`,我们最终都要将其merge到node的ret里去。显然在merge前,对于tmp里的每一个key,都有`ans+=tmp[key]*ret[key]`;在merge后,对于tmp里的每一个key,都有`ret[key]+=tmp[key]`. From 493e47177d6be9019b925cae761da983097563ae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 21:26:34 -0700 Subject: [PATCH 1247/2729] Update Readme.md --- Union_Find/2421.Number-of-Good-Paths/Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Union_Find/2421.Number-of-Good-Paths/Readme.md b/Union_Find/2421.Number-of-Good-Paths/Readme.md index 6612434c3..acd7f9803 100644 --- a/Union_Find/2421.Number-of-Good-Paths/Readme.md +++ b/Union_Find/2421.Number-of-Good-Paths/Readme.md @@ -14,8 +14,10 @@ 为了操作上的方便,我们将所有的edge按照较大的端点分类。比如说e[2],表示所有以(数值)2节点为一端,以0/1/2节点为另一端的边的集合。这样方便我们按顺序往图里加入边。 #### 方法2:DFS -本题其实也可以按照普通的DFS来做。我们任意以某个节点(比如说0号节点)为根,看做一棵rooted tree. 类似于“path in a tree”的思想,对于每个节点node而言,我们想知道以它为turning point的合法path有多少。以此做不重不漏的统计。 +本题其实也可以按照普通的DFS来做。我们任意以某个节点(比如说0号节点)为根,看做一棵rooted tree. 类似于“path in a tree”的思想,对于每个节点node而言,我们想知道以它为turning point的合法path有多少(每个path必然有一个turning point和两条单链)。以此做不重不漏的统计。 -考虑对于node作为turning point的合法路径,假设其端点数值是x(显然x必须大于等于vals[node]),我们只需要知道每个子树里有多少条以x为端点、node为终点的合法单链(该单链里任何元素都不大于x)。将这些子树的这些单链彼此组合即可。 +考虑对于node作为turning point的合法路径。假设其端点数值是x(显然x必须大于等于vals[node]),我们只需要知道每个子树里有多少条以x为端点、node为终点的合法单链(该单链里任何元素都不大于x)。将这些不同子树的这些单链之间彼此组合即可。 -更具体地,对于每个node,我们设计一个数据结构`map ret`,其中key表示子树里节点的数值,val表示该数值的节点(可能有多个)到node的合法单链的数目(合法的意思是沿途的节点数值都小于key)。显然,为了保证单链的合法性,我们只需要在map里保存其中key值大于等于vals[node]的部分。对于node的每个孩子的递归结果`map tmp`,我们最终都要将其merge到node的ret里去。显然在merge前,对于tmp里的每一个key,都有`ans+=tmp[key]*ret[key]`;在merge后,对于tmp里的每一个key,都有`ret[key]+=tmp[key]`. +更具体地,对于每个node,我们设计一个数据结构`map count`,其中key表示子树里节点的数值,val表示该数值的节点(可能有多个)到node的合法单链的数目(合法的意思是沿途的节点数值都小于key)。显然,为了保证单链的合法性,我们只需要在map里保存其中key值大于等于vals[node]的部分。对于node的每个孩子的递归结果`map tmp`,我们最终都要将其merge到node的count里去。在merge前,对于tmp里的每一个key,都有`ans+=tmp[key]*count[key]`;在merge后,对于tmp里的每一个key,都有`count[key]+=tmp[key]`. + +此处有一个非常重要的优化技巧。我们在合并tmp与count的时候,遍历的是tmp里面的key。但是如果我们发现count.size()比tmp小的时候,可以先swap(tmp,count),以减少需要遍历的key的数目。 From 9e4d10cf5f8d4d69c4af62539dd4f84e9b890b26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 21:28:20 -0700 Subject: [PATCH 1248/2729] Update 2421.Number-of-Good-Paths_v2.cpp --- .../2421.Number-of-Good-Paths_v2.cpp | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v2.cpp b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v2.cpp index 9f7185160..041500aaa 100644 --- a/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v2.cpp +++ b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v2.cpp @@ -19,8 +19,8 @@ class Solution { mapdfs(int cur, int parent) { - mapret; - ret[vals[cur]] += 1; + mapcount; + count[vals[cur]] += 1; for (int child: next[cur]) { @@ -30,19 +30,19 @@ class Solution { auto iter = tmp.lower_bound(vals[cur]); tmp.erase(tmp.begin(), iter); - if (tmp.size() > ret.size()) - swap(tmp, ret); + if (tmp.size() > count.size()) + swap(tmp, count); - for (auto& [val, count]: tmp) + for (auto& [val, frq]: tmp) { - if (ret.find(val)!=ret.end()) - ans += count * ret[val]; + if (count.find(val)!=count.end()) + ans += frq * count[val]; } - for (auto& [val, count]: tmp) - ret[val] += count; + for (auto& [val, frq]: tmp) + count[val] += frq; } - return ret; + return count; } }; From 1fe6b688f94467675f2fd70a7d4eee4e6bf6e673 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Sep 2022 21:41:34 -0700 Subject: [PATCH 1249/2729] Update 2421.Number-of-Good-Paths_v1.cpp --- .../2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v1.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v1.cpp b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v1.cpp index 105b1c4df..d0b268d3f 100644 --- a/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v1.cpp +++ b/Union_Find/2421.Number-of-Good-Paths/2421.Number-of-Good-Paths_v1.cpp @@ -55,12 +55,11 @@ class Solution { count[root]++; } - ret += val2idx[v].size(); for (auto& [v, num]: count) ret += num*(num-1)/2; } - return ret; + return ret + n; } }; From 657b49180975dadc6413b3fca4cbbb1b543048c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 1 Oct 2022 16:42:21 -0700 Subject: [PATCH 1250/2729] Create 2426.Number-of-Pairs-Satisfying-Inequality.cpp --- ....Number-of-Pairs-Satisfying-Inequality.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality/2426.Number-of-Pairs-Satisfying-Inequality.cpp diff --git a/Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality/2426.Number-of-Pairs-Satisfying-Inequality.cpp b/Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality/2426.Number-of-Pairs-Satisfying-Inequality.cpp new file mode 100644 index 000000000..940818a26 --- /dev/null +++ b/Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality/2426.Number-of-Pairs-Satisfying-Inequality.cpp @@ -0,0 +1,36 @@ +class Solution { + long long ret = 0; + long long diff; +public: + long long numberOfPairs(vector& nums1, vector& nums2, int diff) + { + int n = nums1.size(); + this->diff = diff; + + vectorarr(n); + for (int i=0; i&arr, int a, int b) + { + if (a==b) return; + int mid = a+(b-a)/2; + helper(arr, a, mid); + helper(arr, mid+1, b); + + int i = a; + for (int j=mid+1; j<=b; j++) + { + while (i<=mid && arr[i] <= arr[j]+diff) + i++; + ret += i-a; + } + + inplace_merge(arr.begin()+a, arr.begin()+mid+1, arr.begin()+b+1); + } +}; From d904382f159e26edcdae2ba74d7856656d504b6b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 1 Oct 2022 16:43:09 -0700 Subject: [PATCH 1251/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 382925549..40e096415 100644 --- a/Readme.md +++ b/Readme.md @@ -848,6 +848,7 @@ [327.Count-of-Range-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/327.Count-of-Range-Sum) (H-) [493.Reverse-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/493.Reverse-Pairs) (M+) [1649.Create-Sorted-Array-through-Instructions](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions) (H) +[2426.Number-of-Pairs-Satisfying-Inequality](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality) (H-) #### [String](https://github.com/wisdompeak/LeetCode/tree/master/String) [006.ZigZag-Conversion](https://github.com/wisdompeak/LeetCode/tree/master/String/006.ZigZag-Conversion) (M+) From 271d2c1d770045acb0fe25b5eddaba7564fa33f7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 1 Oct 2022 16:53:59 -0700 Subject: [PATCH 1252/2729] Create Readme.md --- .../2426.Number-of-Pairs-Satisfying-Inequality/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality/Readme.md diff --git a/Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality/Readme.md b/Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality/Readme.md new file mode 100644 index 000000000..40c3eddfd --- /dev/null +++ b/Divide_Conquer/2426.Number-of-Pairs-Satisfying-Inequality/Readme.md @@ -0,0 +1,9 @@ +### 2426.Number-of-Pairs-Satisfying-Inequality + +稍微转化一下题意,令`arr[i] = nums1[i]-nums2[i]`,本题即是求在arr里的index pair {i,j},满足`arr[i] <= arr[j]+diff`. + +显然,本题很像求数组里的“正序对”数目,自然解法和求数组“逆序对”数目也一模一样,就是经典的分治法。和315,327,493,1649属于同一类型。 + +分治法的递归思想:将区间分为前后两部分,各自递归处理,且保持有序。这样,对于后半部分的每一个arr[j],我们很容易知道在前半部分有多少arr[i]满足`arr[i] <= arr[j]+diff`(用一个指针滑动即可)。然后,将区间的前后两部分归并排序使整个区间继续保持有序,返回。 + +仔细体会,为什么这种方法可以对任意的arr[j]可以穷举到每一个符合的arr[i]?核心在于任何一个在j之前的i,必然会在某个区间内满足:i在前半区间,j在后半区间。 From a58e92b92042d71410913824829ec3c1c8e3c99d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Oct 2022 00:47:21 -0700 Subject: [PATCH 1253/2729] Update 677.Map-Sum-Pairs.cpp --- Trie/677.Map-Sum-Pairs/677.Map-Sum-Pairs.cpp | 24 ++++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/Trie/677.Map-Sum-Pairs/677.Map-Sum-Pairs.cpp b/Trie/677.Map-Sum-Pairs/677.Map-Sum-Pairs.cpp index 89aadcedb..6e8852568 100644 --- a/Trie/677.Map-Sum-Pairs/677.Map-Sum-Pairs.cpp +++ b/Trie/677.Map-Sum-Pairs/677.Map-Sum-Pairs.cpp @@ -38,28 +38,22 @@ class MapSum { for (int i=0; inext[ch-'a']==NULL) - node->next[ch-'a']=new TrieNode(); + if (node->next[ch-'a']==NULL) + return 0; node=node->next[ch-'a']; } - int SUM=0; - DFS(node,SUM); - return SUM; + + int Sum=0; + DFS(node,Sum); + return Sum; } - void DFS(TrieNode* node, int & SUM) + void DFS(TrieNode* node, int& sum) { if (node==NULL) return; - SUM+=node->val; + sum+=node->val; for (int i=0; i<26; i++) - DFS(node->next[i],SUM); + DFS(node->next[i],sum); } }; - -/** - * Your MapSum object will be instantiated and called as such: - * MapSum obj = new MapSum(); - * obj.insert(key,val); - * int param_2 = obj.sum(prefix); - */ From 254fc50989e5ef3271c1014e3f3283a3e8245519 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Oct 2022 00:49:50 -0700 Subject: [PATCH 1254/2729] Update Readme.md --- Trie/677.Map-Sum-Pairs/Readme.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Trie/677.Map-Sum-Pairs/Readme.md b/Trie/677.Map-Sum-Pairs/Readme.md index 2d3e70511..2e388dfd0 100644 --- a/Trie/677.Map-Sum-Pairs/Readme.md +++ b/Trie/677.Map-Sum-Pairs/Readme.md @@ -2,7 +2,4 @@ 常规的Trie操作。 -注意,在类的公告区域里定义了```TrieNode* root```之后,在构造函数里就只需要直接```root=TrieNode()```即可,千万不能```TrieNode* root=TrieNode()```。否则会有意想不到的错误。 - - -[Leetcode Link](https://leetcode.com/problems/map-sum-pairs) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/map-sum-pairs) From ae3a1ec65e5ebc101f010b3f66ec3a225833622e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Oct 2022 22:25:54 -0700 Subject: [PATCH 1255/2729] Update Readme.md --- .../2272.Substring-With-Largest-Variance/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md index 2b5a22746..9b3376e01 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md @@ -38,6 +38,12 @@ 这样的时间复杂度是多少?看上去仍然是是o(256n),但事实上,我们每固定了一个最大频次的字符a,其他所有字符都被看做为最小频次的字符,且只访问了一次。所以时间复杂度优化到了o(26n). +补充: +有网友问,我感觉第二种做法不是严格的O(26 * N). https://youtu.be/P6KnO-Dw0Fo?t=2204 即使可以认为b的pos1循环遍26次就是O(N) (e.g. 小x, 小y), 但是a的pos0在内层循环也遍历了26次而不是一次. 所以两者加一起肯定大于o(N)但是小于O(26N) + +答:应该这么理解:当第一个for循环是字母a,那么照你的说法,字母a的所有位置都走了26次,外加其他所有位置都走了一次。当第一个for循环是字母b,同理,字母b的所有位置都走了26次,外加其他所有位置都走了一次。以此类推。把第一个for循环都搞完后,那么每个字母的位置都走了重复26次,外加所有的位置都走了26次。总开销不依然是26N吗? + + From ac3d8809285fb29ec7a528fee8441aadb41b3ae3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Oct 2022 22:38:18 -0700 Subject: [PATCH 1256/2729] Create 2430.Maximum-Deletions-on-a-String.cpp --- .../2430.Maximum-Deletions-on-a-String.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Dynamic_Programming/2430.Maximum-Deletions-on-a-String/2430.Maximum-Deletions-on-a-String.cpp diff --git a/Dynamic_Programming/2430.Maximum-Deletions-on-a-String/2430.Maximum-Deletions-on-a-String.cpp b/Dynamic_Programming/2430.Maximum-Deletions-on-a-String/2430.Maximum-Deletions-on-a-String.cpp new file mode 100644 index 000000000..1c1652845 --- /dev/null +++ b/Dynamic_Programming/2430.Maximum-Deletions-on-a-String/2430.Maximum-Deletions-on-a-String.cpp @@ -0,0 +1,32 @@ +class Solution { + int lcs[4001][4001]; + int dp[4001]; +public: + int deleteString(string s) + { + int n = s.size(); + if (equal(s.begin() + 1, s.end(), s.begin())) + return n; + + for (int i=n-1; i>=0; i--) + for (int j=n-1; j>=i+1; j--) + { + if (s[i]==s[j]) + lcs[i][j] = lcs[i+1][j+1]+1; + } + + + for (int i=n-1; i>=0; i--) + { + dp[i] = 1; + for (int j=i+1; j=j-i) + { + dp[i] = max(dp[i], dp[j]+1); + } + } + } + return dp[0]; + } +}; From 72d75afb0f202b3fa5d3e0c47693246a3060e6b7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Oct 2022 22:39:04 -0700 Subject: [PATCH 1257/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 40e096415..529424cf1 100644 --- a/Readme.md +++ b/Readme.md @@ -691,6 +691,7 @@ [1691.Maximum-Height-by-Stacking-Cuboids](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1691.Maximum-Height-by-Stacking-Cuboids) (H) [2188.Minimum-Time-to-Finish-the-Race](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race) (H-) [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) +[2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) From 6ce07e6ef86e4d50b53b439e657c21797afcfbf7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Oct 2022 22:49:04 -0700 Subject: [PATCH 1258/2729] Create Readme.md --- .../2430.Maximum-Deletions-on-a-String/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2430.Maximum-Deletions-on-a-String/Readme.md diff --git a/Dynamic_Programming/2430.Maximum-Deletions-on-a-String/Readme.md b/Dynamic_Programming/2430.Maximum-Deletions-on-a-String/Readme.md new file mode 100644 index 000000000..e24bfcf9a --- /dev/null +++ b/Dynamic_Programming/2430.Maximum-Deletions-on-a-String/Readme.md @@ -0,0 +1,9 @@ +### 2430.Maximum-Deletions-on-a-String + +因为是一刀一刀地从头开始砍,显然我们会令dp[i]表示以i开头的字符串的maximum deletion。 + +对于状态的转移,我们不难想到尝试它的第一个刀的位置。假设我们想砍在位置j之前,那么就需要查看是否满足[i:j-1]和[j:j+j-i]这两段区间是否相等。如果是的话,就有`dp[i] = d[j]+1`. + +那么如何高效判断这两个分别以i和j开头的区间是否相等呢?我们可以用N^2的时间预处理,先得到任意两个位置i和j的最大公共前缀长度lcs。如果`lcs[i][j] >= j-i`,那么就意味着[i:j-1]和[j:j+j-i]这两段区间必然相等。事实上,对于i而言可能会有多个合适的j,所以`dp[i] = max{d[j]+1}` + +最终返回dp[0]. From 466facad9e14cbdd76f55c2bad9377326b825799 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Oct 2022 20:33:05 -0700 Subject: [PATCH 1259/2729] Create 1224.Maximum-Equal-Frequency.cpp --- .../1224.Maximum-Equal-Frequency.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Others/1224.Maximum-Equal-Frequency/1224.Maximum-Equal-Frequency.cpp diff --git a/Others/1224.Maximum-Equal-Frequency/1224.Maximum-Equal-Frequency.cpp b/Others/1224.Maximum-Equal-Frequency/1224.Maximum-Equal-Frequency.cpp new file mode 100644 index 000000000..0e838c8ff --- /dev/null +++ b/Others/1224.Maximum-Equal-Frequency/1224.Maximum-Equal-Frequency.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + int maxEqualFreq(vector& nums) + { + unordered_mapnum2freq; + for (auto num: nums) + num2freq[num]++; + + unordered_mapfreq2count; + for (auto [num, freq]:num2freq) + freq2count[freq] += 1; + + + for (int i=nums.size()-1; i>=0; i--) + { + if (freq2count.size()==1) + { + auto [freq, count] = *freq2count.begin(); + if (count == 1 || freq == 1) + return i+1; } + else if (freq2count.size()==2) + { + vector>temp(freq2count.begin(), freq2count.end()); + sort(temp.begin(), temp.end()); + + if (temp[1].first == temp[0].first + 1 && temp[1].second == 1) + return i+1; + if (temp[0].first == 1 && temp[0].second == 1) + return i+1; + } + + int x = nums[i]; + int f = num2freq[x]; + + num2freq[x] -= 1; + if (num2freq[x]==0) + num2freq.erase(x); + + freq2count[f] -= 1; + if (freq2count[f] == 0) + freq2count.erase(f); + + if (f-1>0) + freq2count[f-1] += 1; + } + + return 2; + } +}; From 81bd61b556103b77b864c5931de83cdc875b2fb0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Oct 2022 20:35:17 -0700 Subject: [PATCH 1260/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 529424cf1..a663ea4ba 100644 --- a/Readme.md +++ b/Readme.md @@ -150,7 +150,6 @@ [939.Minimum-Area-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Hash/939.Minimum-Area-Rectangle) (M+) 982.Triples-with-Bitwise-AND-Equal-To-Zero (M+) (TBD) [1074.Number-of-Submatrices-That-Sum-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1074.Number-of-Submatrices-That-Sum-to-Target) (M+) -1224.Maximum-Equal-Frequency (H-) [1487.Making-File-Names-Unique](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1487.Making-File-Names-Unique) (M+) [1573.Number-of-Ways-to-Split-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1573.Number-of-Ways-to-Split-a-String) (M) [2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2131.Longest-Palindrome-by-Concatenating-Two-Letter-Words) (M) @@ -1262,6 +1261,7 @@ [927.Three-Equal-Parts](https://github.com/wisdompeak/LeetCode/tree/master/Others/927.Three-Equal-Parts) (M) [978.Longest-Turbulent-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Others/978.Longest-Turbulent-Subarray) (H-) 1183.Maximum-Number-of-Ones (H) +[1224.Maximum-Equal-Frequency](https://github.com/wisdompeak/LeetCode/tree/master/Others/1224.Maximum-Equal-Frequency) (H) (aka. 2423. Remove Letter To Equalize Frequency) [1267.Count-Servers-that-Communicate](https://github.com/wisdompeak/LeetCode/tree/master/Others/1267.Count-Servers-that-Communicate) (M+) [1538.Guess-the-Majority-in-a-Hidden-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1538.Guess-the-Majority-in-a-Hidden-Array) (M+) [1706.Where-Will-the-Ball-Fall](https://github.com/wisdompeak/LeetCode/tree/master/Others/1706.Where-Will-the-Ball-Fall) (M+) From 1e94b26f6fa567a2f825dbfa9995dd1d5aa95cf8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Oct 2022 20:54:59 -0700 Subject: [PATCH 1261/2729] Update 656.Coin-Path.cpp --- Dynamic_Programming/656.Coin-Path/656.Coin-Path.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/656.Coin-Path/656.Coin-Path.cpp b/Dynamic_Programming/656.Coin-Path/656.Coin-Path.cpp index 4a1dadbcf..b567d288a 100644 --- a/Dynamic_Programming/656.Coin-Path/656.Coin-Path.cpp +++ b/Dynamic_Programming/656.Coin-Path/656.Coin-Path.cpp @@ -3,7 +3,7 @@ class Solution { vector cheapestJump(vector& A, int B) { int n=A.size(); - vectordp(n,INT_MAX); + vectordp(N,INT_MAX/2); vectorpath(n,-1); dp[n-1]=A[n-1]; From 6373a0bd10a0175156e818aeb79e47de59d82c0c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Oct 2022 22:08:18 -0700 Subject: [PATCH 1262/2729] Create Readme.md --- Others/1224.Maximum-Equal-Frequency/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/1224.Maximum-Equal-Frequency/Readme.md diff --git a/Others/1224.Maximum-Equal-Frequency/Readme.md b/Others/1224.Maximum-Equal-Frequency/Readme.md new file mode 100644 index 000000000..5567411c7 --- /dev/null +++ b/Others/1224.Maximum-Equal-Frequency/Readme.md @@ -0,0 +1,13 @@ +### 1224.Maximum-Equal-Frequency + +很显然,我们会从最长的前缀(即整个数组)开始,从后往前逐一去除元素。如果某一个前缀,满足去除一个元素就可以使得剩余元素的频次相等的话,就输出该前缀长度。 + +为此,我们可以维护一个频次表记录`freq2count[f] = count`,表示当前频次为f的元素有count个。接下来分情况讨论。 + +如果freq2count里有三种或以上的频次(即三种或以上的key),那么显然不可能通过只删减一个元素就达到频次的种类降为1. + +如果freq2count里只有两种频次,有两种情况是可以实现的。1. 类似于`3,3,3,4,4,4,4`,通过删掉一个较高频次的元素,使得剩下的两种元素频次相同。2. 类似于`1,2,2,2`,较低频次的元素只出现了一次,那么删掉它就只剩下一种元素。 + +如果freq2count里只有一种频次,也有两种情况是可以实现的。1. 类似于`2,3,4`,即freq=1,那么随便哪个元素都可以。2. 类似于`3,3,3`,即count=1,那么随便哪个元素也可以。 + +根本题类似的还有`2423. Remove Letter To Equalize Frequency`. From 5a7e24548ad5f0ebd809ca947899bba7c91daa84 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Oct 2022 23:00:51 -0700 Subject: [PATCH 1263/2729] Update 240.Search a 2D Matrix II.cpp --- .../240.Search-a-2D-Matrix-II/240.Search a 2D Matrix II.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Others/240.Search-a-2D-Matrix-II/240.Search a 2D Matrix II.cpp b/Others/240.Search-a-2D-Matrix-II/240.Search a 2D Matrix II.cpp index 69f535daa..c22be6c0c 100644 --- a/Others/240.Search-a-2D-Matrix-II/240.Search a 2D Matrix II.cpp +++ b/Others/240.Search-a-2D-Matrix-II/240.Search a 2D Matrix II.cpp @@ -17,10 +17,6 @@ class Solution { else if (matrix[i][j]>target) i--; } - - if (i>=0 && j<=N-1) - return true; - else - return false; + return false; } }; From 91e9c7e187fdaac827893ecd7a34887afbf0da22 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Oct 2022 21:09:25 -0700 Subject: [PATCH 1264/2729] Create 2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String.cpp --- ...-the-Lexicographically-Smallest-String.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String.cpp diff --git a/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String.cpp b/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String.cpp new file mode 100644 index 000000000..7499ce26a --- /dev/null +++ b/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + string robotWithString(string s) + { + int n = s.size(); + vectornextSmallest(n,INT_MAX); + char smallest = 'z'+1; + for (int i=n-1; i>=0; i--) + { + smallest = min(smallest, s[i]); + nextSmallest[i] = smallest; + } + + stackst; + string ret; + int i = 0; + while (i Date: Sun, 9 Oct 2022 21:10:04 -0700 Subject: [PATCH 1265/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a663ea4ba..c81a57876 100644 --- a/Readme.md +++ b/Readme.md @@ -319,6 +319,7 @@ [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) From 281d8aa9def3aa046c44b2c6106ec7892115769a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Oct 2022 21:17:34 -0700 Subject: [PATCH 1266/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c81a57876..39e39efed 100644 --- a/Readme.md +++ b/Readme.md @@ -319,7 +319,6 @@ [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) -[2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) @@ -359,6 +358,7 @@ [1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) +[2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) * ``monotonic stack: other usages`` [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) From 4203e711225233c074e21df54b421273348af997 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Oct 2022 21:50:54 -0700 Subject: [PATCH 1267/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/Readme.md diff --git a/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/Readme.md b/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/Readme.md new file mode 100644 index 000000000..942176fdf --- /dev/null +++ b/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/Readme.md @@ -0,0 +1,9 @@ +### 2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String + +翻译一下题目的意思。我们从头到尾扫一遍原串s,依次将每个字符放入一个辅助的栈,但是栈顶的弹出时机可以自定义。问最终从栈弹出的字符串的最小字典序。 + +入手时,我们采用贪心的思想,思考如果s中有一个字符a在位置i处,它一定应该是最终答案的首字符。所以我们在遇到a之前,所有的字符,即`s[0:i-1]`都应该依次存入栈但是不弹出。直至遇到那个a,将其放入栈顶后马上弹出,这样才能得到一个以a开头的最小字典序字符串。 + +此时,我们需要考虑的是s[i+1],并且之前的`s[0:i-1]`逆序存于栈顶。此时我们的两个选择是:立即弹出当前的栈顶元素,或者将s[i+1]压入栈顶(然后立即弹出,或者保留观望)。此时的决策依据显然就是:此时栈顶元素的字符是否够小?如果s[i+1]及其它之后全局最小的字符(假设还是a,位置在j),它比栈顶元素还要小,那么根据贪心的原则,我们必然至少要继续进行入栈的操作,直至遇到s[j]。接下来就是一个入栈+出栈,就将s[j]打印出来。反之,如果s[i+1]及其它之后全局最小的字符,比当前的栈顶元素还要大,那么打印当前的栈顶元素自然是最合算的策略。 + +所以本题需要预处理一个后缀数组nextSmallest,其中nextSmallest[i]表示[i:n-1]里面最小的字符。这样当我们处理到s[i]的时候,就可以用nextSmallest[i]和栈顶元素进行比较,来判断是否要持续入栈,还是可以弹出栈顶元素直接打印。 From a538f42664f9dde03fe82fdfa1eaecf6c39b5e2b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Oct 2022 21:51:30 -0700 Subject: [PATCH 1268/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/Readme.md b/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/Readme.md index 942176fdf..d71bc6ff4 100644 --- a/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/Readme.md +++ b/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String/Readme.md @@ -4,6 +4,6 @@ 入手时,我们采用贪心的思想,思考如果s中有一个字符a在位置i处,它一定应该是最终答案的首字符。所以我们在遇到a之前,所有的字符,即`s[0:i-1]`都应该依次存入栈但是不弹出。直至遇到那个a,将其放入栈顶后马上弹出,这样才能得到一个以a开头的最小字典序字符串。 -此时,我们需要考虑的是s[i+1],并且之前的`s[0:i-1]`逆序存于栈顶。此时我们的两个选择是:立即弹出当前的栈顶元素,或者将s[i+1]压入栈顶(然后立即弹出,或者保留观望)。此时的决策依据显然就是:此时栈顶元素的字符是否够小?如果s[i+1]及其它之后全局最小的字符(假设还是a,位置在j),它比栈顶元素还要小,那么根据贪心的原则,我们必然至少要继续进行入栈的操作,直至遇到s[j]。接下来就是一个入栈+出栈,就将s[j]打印出来。反之,如果s[i+1]及其它之后全局最小的字符,比当前的栈顶元素还要大,那么打印当前的栈顶元素自然是最合算的策略。 +此时,我们需要考虑的是s[i+1],并且注意到之前的`s[0:i-1]`已经逆序存于栈顶。此时我们的两个选择是:立即弹出当前的栈顶元素,或者将s[i+1]压入栈顶(然后立即弹出,或者保留观望)。此时的决策依据显然就是:此时栈顶元素的字符是否够小?如果s[i+1]及其它之后全局最小的字符(假设还是a,位置在j),它比栈顶元素还要小,那么根据贪心的原则,我们必然至少要继续进行入栈的操作,直至遇到s[j]。接下来就是一个入栈+出栈,就将s[j]打印出来。反之,如果s[i+1]及其它之后全局最小的字符,比当前的栈顶元素还要大,那么打印当前的栈顶元素自然是最合算的策略。 所以本题需要预处理一个后缀数组nextSmallest,其中nextSmallest[i]表示[i:n-1]里面最小的字符。这样当我们处理到s[i]的时候,就可以用nextSmallest[i]和栈顶元素进行比较,来判断是否要持续入栈,还是可以弹出栈顶元素直接打印。 From 2fb4e5cb117c9c5c95b06a39e501d16f42c67fcd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Oct 2022 22:57:09 -0700 Subject: [PATCH 1269/2729] Create 2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K.cpp --- ...-in-Matrix-Whose-Sum-Is-Divisible-by-K.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K.cpp diff --git a/Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K.cpp b/Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K.cpp new file mode 100644 index 000000000..b9fd0a9eb --- /dev/null +++ b/Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K.cpp @@ -0,0 +1,37 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int numberOfPaths(vector>& grid, int k) + { + int m = grid.size(), n = grid[0].size(); + vector>>dp(m, vector>(n, vector(k))); + + LL sum = 0; + for (int i=0; i Date: Sun, 9 Oct 2022 23:04:04 -0700 Subject: [PATCH 1270/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 39e39efed..0387a1d3e 100644 --- a/Readme.md +++ b/Readme.md @@ -703,6 +703,7 @@ [1301.Number-of-Paths-with-Max-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1301.Number-of-Paths-with-Max-Score) (M+) [1594.Maximum-Non-Negative-Product-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1594.Maximum-Non-Negative-Product-in-a-Matrix) (M) [2267.Check-if-There-Is-a-Valid-Parentheses-String-Path](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2267.Check-if-There-Is-a-Valid-Parentheses-String-Path) (H-) +[2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K) (M) * ``背包型`` [322.Coin-Change](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/322.Coin-Change) (M) [416.Partition-Equal-Subset-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/416.Partition-Equal-Subset-Sum) (M+) From d58723d8687e25bd98e614865a6f15921b8da6cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Oct 2022 23:11:17 -0700 Subject: [PATCH 1271/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/Readme.md diff --git a/Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/Readme.md b/Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/Readme.md new file mode 100644 index 000000000..e5eae3c2b --- /dev/null +++ b/Dynamic_Programming/2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K/Readme.md @@ -0,0 +1,5 @@ +### 2435.Paths-in-Matrix-Whose-Sum-Is-Divisible-by-K + +非常套路的动态规划。因为最终我们要求路径和恰好是k的倍数,所以在每个中途的点,我们必须考虑当前路径和对k的余数状态。因此我们定义dp[i][j][r]表示从起点到(i,j)有多少条不同路径使得沿途的元素和对k的取模是r。根据套路,`dp[i][j][r] = dp[i-1][j][t] + dp[i][j-1][t]`,其中t必须满足`(t + grid[i][j]) % k = r`. + +最终返回dp[m-1][n-1][0]. From 4b3462472abb420b151f7cc145fda50f3ca28cda Mon Sep 17 00:00:00 2001 From: Yue Wang Date: Thu, 13 Oct 2022 18:53:24 +1300 Subject: [PATCH 1272/2729] Add an AND condition --- .../673.Number-of-Longest-Increasing-Subsequence/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/673.Number-of-Longest-Increasing-Subsequence/Readme.md b/Dynamic_Programming/673.Number-of-Longest-Increasing-Subsequence/Readme.md index 54901a38f..24603d8ea 100644 --- a/Dynamic_Programming/673.Number-of-Longest-Increasing-Subsequence/Readme.md +++ b/Dynamic_Programming/673.Number-of-Longest-Increasing-Subsequence/Readme.md @@ -6,7 +6,7 @@ ```len[i] = max (len[j]+1) for 0<=j Date: Wed, 12 Oct 2022 23:37:59 -0700 Subject: [PATCH 1273/2729] Create 2371.Minimize-Maximum-Value-in-a-Grid.cpp --- .../2371.Minimize-Maximum-Value-in-a-Grid.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Greedy/2371.Minimize-Maximum-Value-in-a-Grid/2371.Minimize-Maximum-Value-in-a-Grid.cpp diff --git a/Greedy/2371.Minimize-Maximum-Value-in-a-Grid/2371.Minimize-Maximum-Value-in-a-Grid.cpp b/Greedy/2371.Minimize-Maximum-Value-in-a-Grid/2371.Minimize-Maximum-Value-in-a-Grid.cpp new file mode 100644 index 000000000..7ed52c187 --- /dev/null +++ b/Greedy/2371.Minimize-Maximum-Value-in-a-Grid/2371.Minimize-Maximum-Value-in-a-Grid.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + vector> minScore(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + vector>arr; + for (int i=0; irows(m,0); + vectorcols(n,0); + + for (int i=0; i Date: Wed, 12 Oct 2022 23:38:29 -0700 Subject: [PATCH 1274/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0387a1d3e..8776a509f 100644 --- a/Readme.md +++ b/Readme.md @@ -1141,6 +1141,7 @@ [2350.Shortest-Impossible-Sequence-of-Rolls](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2350.Shortest-Impossible-Sequence-of-Rolls) (M+) [2365.Task-Scheduler-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2365.Task-Scheduler-II) (M) [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) +[2371.Minimize-Maximum-Value-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2371.Minimize-Maximum-Value-in-a-Grid) (M+) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From 0a8637cf92ba2ef91ad8cafb12f76368601eea93 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 12 Oct 2022 23:42:10 -0700 Subject: [PATCH 1275/2729] Create Readme.md --- Greedy/2371.Minimize-Maximum-Value-in-a-Grid/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Greedy/2371.Minimize-Maximum-Value-in-a-Grid/Readme.md diff --git a/Greedy/2371.Minimize-Maximum-Value-in-a-Grid/Readme.md b/Greedy/2371.Minimize-Maximum-Value-in-a-Grid/Readme.md new file mode 100644 index 000000000..5e0a90e65 --- /dev/null +++ b/Greedy/2371.Minimize-Maximum-Value-in-a-Grid/Readme.md @@ -0,0 +1,3 @@ +### 2371.Minimize-Maximum-Value-in-a-Grid + +将矩阵所有的元素按照从小到大排列。我们依次考察每个元素(i,j),如果第i行和第j列都没有其他元素被考察过的话,那么grid[i][j]就可以赋值为1. 否则,grid[i][j]显然就应该赋值为`max{该行目前赋值过的最大值,该列目前赋值过的最大值}+1`,以保证和该行该列其他元素的大小关系. 所以我们需要额外空间记录rows[i]与cols[j]来实时更新每行每列当前赋值过的最大值。 From f54cc50bc61828fc98afdcbf0cc2ea3da1380687 Mon Sep 17 00:00:00 2001 From: Xiao Sun Date: Fri, 14 Oct 2022 11:29:22 -0400 Subject: [PATCH 1276/2729] Update Readme.md Avoid overwrite. --- Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md index feedb5214..2039724c2 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md @@ -7,7 +7,7 @@ 这就是01背包问题的基本思想。如果dp的空间大小合理,那么我们就可以来解决之前DFS所无法处理的复杂度。基本的模板如下: ``` for (auto x: nums) // 遍历物品 - for (auto s= 0 to sum/2) // 遍历容量 + for (auto s= sum/2 to 0) // 遍历容量 if dp'[s-x] = true dp[s] = true // 如果考察x之前,已经能够凑出s-x,那么加上x这个数字就一定能凑出和为x的subset。 ``` @@ -15,7 +15,7 @@ for (auto x: nums) // 遍历物品 此外还有另外一种dp的写法 ``` for (auto x: nums) // 遍历物品 - for (auto s= 0 to sum/2) // 遍历容量 + for (auto s= sum/2 to 0) // 遍历容量 if dp'[s] = true dp[s+x] = true // 如果考察x之前,已经能够凑出s,那么加上x这个数字就一定能凑出和为s+x的subset。 ``` From 6cd50877ca29fc54a0001ad705bb4447f37bea67 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 08:29:59 -0700 Subject: [PATCH 1277/2729] Create 2438.Range-Product-Queries-of-Powers.cpp --- .../2438.Range-Product-Queries-of-Powers.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Others/2438.Range-Product-Queries-of-Powers/2438.Range-Product-Queries-of-Powers.cpp diff --git a/Others/2438.Range-Product-Queries-of-Powers/2438.Range-Product-Queries-of-Powers.cpp b/Others/2438.Range-Product-Queries-of-Powers/2438.Range-Product-Queries-of-Powers.cpp new file mode 100644 index 000000000..803bd1267 --- /dev/null +++ b/Others/2438.Range-Product-Queries-of-Powers/2438.Range-Product-Queries-of-Powers.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector productQueries(int n, vector>& queries) + { + vectorpowers; + for (int i=0; i<32; i++) + { + if (n%2!=0) + powers.push_back(i); + n/=2; + if (n==0) break; + } + + vectorpresum(powers.size()); + for (int i=0; itwos(32*32,1); + long M = 1e9+7; + for (int i=1; i<32*32; i++) + twos[i] = twos[i-1] * 2 % M; + + vectorrets; + for (auto& query : queries) + { + int l = query[0], r = query[1]; + int diff = presum[r] - (l==0?0:presum[l-1]); + rets.push_back(twos[diff]); + } + return rets; + } +}; From 42a935152702e46e3cb38bb2c4e8533b1ce2d50b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 08:30:26 -0700 Subject: [PATCH 1278/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8776a509f..be8d19873 100644 --- a/Readme.md +++ b/Readme.md @@ -1334,6 +1334,7 @@ [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) [2245.Maximum-Trailing-Zeros-in-a-Cornered-Path](https://github.com/wisdompeak/LeetCode/tree/master/Others/2245.Maximum-Trailing-Zeros-in-a-Cornered-Path) (M) [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) +[2438.Range-Product-Queries-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2438.Range-Product-Queries-of-Powers) (M+) * ``2D Presum`` 1314.Matrix-Block-Sum (M) [1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1292.Maximum-Side-Length-of-a-Square-with-Sum-Less-than-or-Equal-to-Threshold) (H-) From 52727bcb0b89acaeab6ab1305d1518cc6357628e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 08:42:20 -0700 Subject: [PATCH 1279/2729] Create Readme.md --- Others/2438.Range-Product-Queries-of-Powers/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2438.Range-Product-Queries-of-Powers/Readme.md diff --git a/Others/2438.Range-Product-Queries-of-Powers/Readme.md b/Others/2438.Range-Product-Queries-of-Powers/Readme.md new file mode 100644 index 000000000..a7f2f5502 --- /dev/null +++ b/Others/2438.Range-Product-Queries-of-Powers/Readme.md @@ -0,0 +1,5 @@ +### 2438.Range-Product-Queries-of-Powers + +对于区间乘积,虽然我们可以借鉴区间求和的思路,采用前缀积相除的方法。但是本题涉及到对大数取模,应该注意到`(a/b) mod M != (a mod M) / (b mod M)`,而引入逆元的话,又显得比较繁琐。所以这道题的切入点应该在别处。 + +因为所有相乘的元素都是2的幂,显然我们知道这个性质,`2^a * 2^b = 2^(a+b)`,所以可以将区间的乘积转化为“指数”区间的求和,再求一次幂即可。 From cb2bafd76a0310d342be80e877b9ca0d75b910ec Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 09:09:09 -0700 Subject: [PATCH 1280/2729] Create 2439.Minimize-Maximum-of-Array.cpp --- .../2439.Minimize-Maximum-of-Array.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array.cpp diff --git a/Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array.cpp b/Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array.cpp new file mode 100644 index 000000000..c2b663b6d --- /dev/null +++ b/Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minimizeArrayValue(vector& nums) + { + int left = nums[0], right = 1e9; + while (left < right) + { + int mid = left+(right-left)/2; + + long long buff = 0; + int flag = true; + for (int i=0; i mid) + buff -= (x-mid); + else + buff += (mid-x); + if (buff < 0) + { + flag = false; + break; + } + } + + if (flag) + right = mid; + else + left = mid+1; + } + + return left; + + } +}; From 1daa5c9baa84d3ab5dc2a6c318a18714cd0cb40b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 09:09:47 -0700 Subject: [PATCH 1281/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index be8d19873..fac293316 100644 --- a/Readme.md +++ b/Readme.md @@ -113,6 +113,7 @@ [2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2137.Pour-Water-Between-Buckets-to-Make-Water-Levels-Equal) (M) [2141.Maximum-Running-Time-of-N-Computers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2141.Maximum-Running-Time-of-N-Computers) (M+) [2226.Maximum-Candies-Allocated-to-K-Children](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children) (M) +[2439.Minimize-Maximum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2439.Minimize-Maximum-of-Array) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 67f77b81f6589a0432c3ac029a2b86985e1233b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 09:46:48 -0700 Subject: [PATCH 1282/2729] Create Readme.md --- .../2439.Minimize-Maximum-of-Array/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md diff --git a/Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md b/Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md new file mode 100644 index 000000000..e4044f768 --- /dev/null +++ b/Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md @@ -0,0 +1,15 @@ +### 2439.Minimize-Maximum-of-Array + +本题的大体思路就是,如果有一个数字特别大,那么我们希望它能与之前的数字们一起“抹匀”,来尽量减少最大值。由于更靠前的数字,只能与更少数量的伙伴一起“抹匀”,所以最终呈现出来的最优解形态,应该是piece-wise constant的递减数列。这个数列的第一个元素的大小,就是最终答案。 + +那么这个数字最小是什么呢?并不太容易直接求出来。但是如果我们猜测一个,是容易判断它是否成立的。 + +我们首先猜测最终答案是x。明显,这个x必然不会小于nums[0],因为nums[0]没有机会向前分摊数值。如果x>nums[0],那么这意味着后面的元素有机会向nums[0]分摊一些数值,我们记做“缓冲值”:`buff = x-nums[0]`. + +接下来我们看nums[1]。如果`nums[1]>x`,那么不得不让它往前分摊数值,最多能够分摊多少呢?显然就是buff。于是如果`buff> nums[1]-x`,那么就OK,同时`buff-=nums[1]-x`;否则就直接返回失败。反之,如果`nums[1] Date: Sun, 16 Oct 2022 21:40:25 -0700 Subject: [PATCH 1283/2729] Create 2439.Minimize-Maximum-of-Array_v2.cpp --- .../2439.Minimize-Maximum-of-Array_v2.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array_v2.cpp diff --git a/Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array_v2.cpp b/Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array_v2.cpp new file mode 100644 index 000000000..98e5ff552 --- /dev/null +++ b/Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array_v2.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int minimizeArrayValue(vector& nums) + { + long long sum = 0; + long long ret = 0; + for (int i=0; i Date: Sun, 16 Oct 2022 21:40:35 -0700 Subject: [PATCH 1284/2729] Rename 2439.Minimize-Maximum-of-Array.cpp to 2439.Minimize-Maximum-of-Array_v1.cpp --- ...Maximum-of-Array.cpp => 2439.Minimize-Maximum-of-Array_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Binary_Search/2439.Minimize-Maximum-of-Array/{2439.Minimize-Maximum-of-Array.cpp => 2439.Minimize-Maximum-of-Array_v1.cpp} (100%) diff --git a/Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array.cpp b/Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array_v1.cpp similarity index 100% rename from Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array.cpp rename to Binary_Search/2439.Minimize-Maximum-of-Array/2439.Minimize-Maximum-of-Array_v1.cpp From 0c8eddb51593a22254de59fe7e382331812812ad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 21:46:36 -0700 Subject: [PATCH 1285/2729] Update Readme.md --- Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md b/Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md index e4044f768..82f98cfe7 100644 --- a/Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md +++ b/Binary_Search/2439.Minimize-Maximum-of-Array/Readme.md @@ -2,6 +2,8 @@ 本题的大体思路就是,如果有一个数字特别大,那么我们希望它能与之前的数字们一起“抹匀”,来尽量减少最大值。由于更靠前的数字,只能与更少数量的伙伴一起“抹匀”,所以最终呈现出来的最优解形态,应该是piece-wise constant的递减数列。这个数列的第一个元素的大小,就是最终答案。 +#### 解法1:二分搜值 + 那么这个数字最小是什么呢?并不太容易直接求出来。但是如果我们猜测一个,是容易判断它是否成立的。 我们首先猜测最终答案是x。明显,这个x必然不会小于nums[0],因为nums[0]没有机会向前分摊数值。如果x>nums[0],那么这意味着后面的元素有机会向nums[0]分摊一些数值,我们记做“缓冲值”:`buff = x-nums[0]`. @@ -13,3 +15,8 @@ 通过二分搜值的讨论,我们可以很容易求出满足条件的最小值。 注意本题一定有解(什么都不做就可以返回数组最大值),因此二分搜值的收链解就是最优解。 + +#### 解法2:贪心 +本题有直接的贪心策略。我们考虑前i个元素,最优的方案就是将前i个元素的和均匀分配,那么分配之后的最大值就是`ceil(presum[i]/i)`(假设是1-index)。我们考察所有的i,得到的全局最大值就是答案。 + +这种贪心策略看上去并不“严谨”。比如说,如果nums[i]相比于之前的所有元素都小,那么我们其实是无法做到让前i个元素均匀分配的。但是这种情况下,意味着前i-1个元素的均匀分配会产生更大的数值,那个数值会overwirte掉最终的答案,而使得“前i个元素均匀分配”这种实际上无法实现的策略不会干扰最终答案。 From c62495bab1b81b1c43c6c6bdad9e78dccdb14fa8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 22:23:36 -0700 Subject: [PATCH 1286/2729] Create 2440.Create-Components-With-Same-Value.cpp --- ...2440.Create-Components-With-Same-Value.cpp | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 BFS/2440.Create-Components-With-Same-Value/2440.Create-Components-With-Same-Value.cpp diff --git a/BFS/2440.Create-Components-With-Same-Value/2440.Create-Components-With-Same-Value.cpp b/BFS/2440.Create-Components-With-Same-Value/2440.Create-Components-With-Same-Value.cpp new file mode 100644 index 000000000..671b414de --- /dev/null +++ b/BFS/2440.Create-Components-With-Same-Value/2440.Create-Components-With-Same-Value.cpp @@ -0,0 +1,79 @@ +class Solution { +public: + int componentValue(vector& nums, vector>& edges) + { + int n = nums.size(); + if (n==1) return 0; + + vector>next(n); + vectorindegree(n); + + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + indegree[b]++; + indegree[a]++; + } + + int total = accumulate(nums.begin(), nums.end(), 0); + + vectorsums; + for (int s=1; s*s <= total; s++) + { + if (total % s!=0) continue; + sums.push_back(s); + sums.push_back(total/s); + } + sort(sums.begin(), sums.end()); + + for (auto s: sums) + { + vectorin = indegree; + queueq; + vectorvisited(n,0); + vectorsum = nums; + + for (int i=0; i s) + { + flag = false; + break; + } + else if (sum[cur] == s) + sum[cur] = 0; + + for (int nxt: next[cur]) + { + if (visited[nxt]) continue; + sum[nxt] += sum[cur]; + in[nxt]--; + + if (in[nxt]==1) + { + visited[nxt] = 1; + q.push(nxt); + } + } + } + + if (flag) return total/s-1; + } + + return 0; + } +}; From 82cb11dd0c7f8c3947fef83b87ea60e0cbd99609 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 22:24:10 -0700 Subject: [PATCH 1287/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fac293316..465aec53e 100644 --- a/Readme.md +++ b/Readme.md @@ -539,6 +539,7 @@ [2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2192.All-Ancestors-of-a-Node-in-a-Directed-Acyclic-Graph) (M) [2204.Distance-to-a-Cycle-in-Undirected-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph) (M) [2392.Build-a-Matrix-With-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2392.Build-a-Matrix-With-Conditions) (M+) +[2440.Create-Components-With-Same-Value](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2440.Create-Components-With-Same-Value) (H-) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From 3c399dc345d460f24acf243c7172b383d571cf8e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 22:42:07 -0700 Subject: [PATCH 1288/2729] Create Readme.md --- BFS/2440.Create-Components-With-Same-Value/Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 BFS/2440.Create-Components-With-Same-Value/Readme.md diff --git a/BFS/2440.Create-Components-With-Same-Value/Readme.md b/BFS/2440.Create-Components-With-Same-Value/Readme.md new file mode 100644 index 000000000..32ff53f5d --- /dev/null +++ b/BFS/2440.Create-Components-With-Same-Value/Readme.md @@ -0,0 +1,10 @@ +### 2440.Create-Components-With-Same-Value + +假设我们想要把这张图平均分成k份,那么每一份联通块的元素和s我们是知道的。假设我们可以实现这样的拆分,从图中我们显然可以发现,每一份符合条件的联通块必然可以从外往内一点一点剥离下来。这就提示我们可以用拓扑排序的方法。我们记录sum[i]表示从外往内“剥洋葱”的过程中,剥到节点i时所对应的“子树”的节点元素之和。 +1. 如果`sum[i]==s`,那么说明这棵子树就是符合条件的一个联通块,我们就彻底剥离,节点i不传递信息给它的上级。 +2. 如果`sum[i]s`,那么说明这棵子树的元素和太大了,不能构成一个合法的联通块,终止基于s的进一步的尝试。 + +我们重复上述剥洋葱的过程,如果把所有节点都剥完,依然没有报错,那么说明我们恰好把整张图剥离成了一个个元素和为s的子树。 + +显然,拓扑排序的复杂度是o(N)。那么我们需要尝试多少个s呢?s的个数应该是total的因子个数,即sqrt(total)。其中total是整张图的元素之和。综上,总的时间复杂度恰好就是1e6级别。 From 03ad48c2547b2cfa5fa15861b00a1d8bba244b95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 23:54:48 -0700 Subject: [PATCH 1289/2729] Create 2444.Count-Subarrays-With-Fixed-Bounds.cpp --- ...2444.Count-Subarrays-With-Fixed-Bounds.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Greedy/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp diff --git a/Greedy/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp b/Greedy/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp new file mode 100644 index 000000000..d2e050f26 --- /dev/null +++ b/Greedy/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + long long countSubarrays(vector& nums, int minK, int maxK) + { + long long ret = 0; + int prevMin = -1, prevMax = -1, boundary = -1; + for (int i=0; imaxK) + { + boundary = i; + continue; + } + + if (nums[i] == minK) + prevMin = i; + if (nums[i] == maxK) + prevMax = i; + + ret += max(0, min(prevMin, prevMax) - boundary); + } + + return ret; + } +}; From b99507692cd84f91038a712fb33f99c810ac38d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Oct 2022 23:55:25 -0700 Subject: [PATCH 1290/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 465aec53e..774da2b50 100644 --- a/Readme.md +++ b/Readme.md @@ -1144,6 +1144,7 @@ [2365.Task-Scheduler-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2365.Task-Scheduler-II) (M) [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) [2371.Minimize-Maximum-Value-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2371.Minimize-Maximum-Value-in-a-Grid) (M+) +[2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2444.Count-Subarrays-With-Fixed-Bounds) (M+) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From 6df9d3114bf4052a8f258944262eb1b69385d84e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 00:01:35 -0700 Subject: [PATCH 1291/2729] Create Readme.md --- Greedy/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md diff --git a/Greedy/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md b/Greedy/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md new file mode 100644 index 000000000..d3012068e --- /dev/null +++ b/Greedy/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md @@ -0,0 +1,5 @@ +### 2444.Count-Subarrays-With-Fixed-Bounds + +本题的关键是掌握好“数subarray”的诀窍。我们通常都是固定一个端点,查看另一个端点可以在哪些地方。 + +我们考虑如果这个subarray的右边是nums[i],那么这个subarray的左端点之后必须包含至少一个minK和maxK。所以我们只要知道i左边最近的minK和maxK,取两者的较小值j,那么[j:i]就是以i结尾的、最短的符合条件的subarray。左端点从j往左延伸的话,这个subarray依然有效。但是特别注意,左端点不能延伸到非法的区域,即小于minK或者大于maxK的地方,所以实际左端点移动的范围是j-boundary,其中boundary是i之前最近的非法位置。 From e34a1e93b2477f6b06a8dbdae124fadf7046442e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 00:50:16 -0700 Subject: [PATCH 1292/2729] Update Readme.md --- .../952.Largest-Component-Size-by-Common-Factor/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Union_Find/952.Largest-Component-Size-by-Common-Factor/Readme.md b/Union_Find/952.Largest-Component-Size-by-Common-Factor/Readme.md index ffda9c37a..900a56c9f 100644 --- a/Union_Find/952.Largest-Component-Size-by-Common-Factor/Readme.md +++ b/Union_Find/952.Largest-Component-Size-by-Common-Factor/Readme.md @@ -27,9 +27,9 @@ result = max(result,x.second); return result; ``` -这个解法能够AC,但是比其他答案要慢得多.原因是100000以内的质数筛检非常费事.怎么改进呢? +这个解法能够AC,但是比其他答案要慢得多.原因是100000以内的质数有9592个。对于每个nums[i]要check将近10000次,效率很低。 -第二个版本,我们只需要求出sqrt(100000)以内的所有质数Pi,这样预处理的规模就小了很多.但是如果继续按照上面的算法,如何保证得到a的所有质因数Pi并建立联系呢?其实我们只要将a不断除以它在sqrt(100000)以内的所有质因数,如果仍然大于1,那么剩下的必然是它唯一的一个大于sqrt(100000)的质因数.因为任何数不可能含有两个大于sqrt(100000)的质因数的. +第二个版本,我们只需要求出sqrt(100000)以内的所有质数Pi,这样只有70个左右。但是如果继续按照上面的算法,如何保证得到a的所有质因数Pi并建立联系呢?其实我们只要将a不断除以它在sqrt(100000)以内的所有质因数,如果仍然大于1,那么剩下的必然是它唯一的一个大于sqrt(100000)的质因数.因为任何数不可能含有两个大于sqrt(100000)的质因数的. ```cpp vectorprimes = makePrimes(sqrt(100000)); for (auto p:primes) Root[p] = p; @@ -67,4 +67,4 @@ ``` -[Leetcode Link](https://leetcode.com/problems/largest-component-size-by-common-factor) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/largest-component-size-by-common-factor) From 874647c167bfabfc11a7b18f51404f087a6939b0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 00:58:22 -0700 Subject: [PATCH 1293/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 774da2b50..8c5ee4ae2 100644 --- a/Readme.md +++ b/Readme.md @@ -1144,7 +1144,6 @@ [2365.Task-Scheduler-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2365.Task-Scheduler-II) (M) [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) [2371.Minimize-Maximum-Value-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2371.Minimize-Maximum-Value-in-a-Grid) (M+) -[2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2444.Count-Subarrays-With-Fixed-Bounds) (M+) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) @@ -1295,6 +1294,7 @@ [2262.Total-Appeal-of-A-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2262.Total-Appeal-of-A-String) (M+) [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) +[2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 8bb8017f788ae0f32e53c48263c60782b5422567 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 00:59:03 -0700 Subject: [PATCH 1294/2729] Rename Greedy/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp to Others/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp --- .../2444.Count-Subarrays-With-Fixed-Bounds.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Others}/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp (100%) diff --git a/Greedy/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp b/Others/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp similarity index 100% rename from Greedy/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp rename to Others/2444.Count-Subarrays-With-Fixed-Bounds/2444.Count-Subarrays-With-Fixed-Bounds.cpp From df065344b787748a46c593079b8c251bfcbab6a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 00:59:33 -0700 Subject: [PATCH 1295/2729] Rename Greedy/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md to Others/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md --- .../2444.Count-Subarrays-With-Fixed-Bounds/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Others}/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md (100%) diff --git a/Greedy/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md b/Others/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md similarity index 100% rename from Greedy/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md rename to Others/2444.Count-Subarrays-With-Fixed-Bounds/Readme.md From 617d7e7a8767ed2a5eb1277596f13c6ac90c2690 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 01:01:57 -0700 Subject: [PATCH 1296/2729] Update and rename Hash/204.Count-Primes/Readme.md to Math/204.Count-Primes/Readme.md --- {Hash => Math}/204.Count-Primes/Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) rename {Hash => Math}/204.Count-Primes/Readme.md (66%) diff --git a/Hash/204.Count-Primes/Readme.md b/Math/204.Count-Primes/Readme.md similarity index 66% rename from Hash/204.Count-Primes/Readme.md rename to Math/204.Count-Primes/Readme.md index 715e63119..0c048af5a 100644 --- a/Hash/204.Count-Primes/Readme.md +++ b/Math/204.Count-Primes/Readme.md @@ -1,6 +1,6 @@ ### 204.Count-Primes -用倍数筛除法去除所有已知质数的倍数。最高效的容器是bool型的vector +用倍数筛除法去除所有已知质数的倍数。 ```cpp vectorq(n,true); for (x=2; x<=sqrt(n); x++) @@ -14,5 +14,7 @@ for (x=2; x<=sqrt(n); x++) 注意,x的判断范围是从2到sqrt(n)即可,不需要遍历到n。 +埃氏筛的时间复杂度是O(NloglogN) -[Leetcode Link](https://leetcode.com/problems/count-primes) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/count-primes) From f19d4ce303a4b22a68f4ac6fed508939af201d7d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 01:02:35 -0700 Subject: [PATCH 1297/2729] Rename Hash/204.Count-Primes/204.Count Primes.cpp to Math/204.Count-Primes/204.Count Primes.cpp --- {Hash => Math}/204.Count-Primes/204.Count Primes.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Hash => Math}/204.Count-Primes/204.Count Primes.cpp (100%) diff --git a/Hash/204.Count-Primes/204.Count Primes.cpp b/Math/204.Count-Primes/204.Count Primes.cpp similarity index 100% rename from Hash/204.Count-Primes/204.Count Primes.cpp rename to Math/204.Count-Primes/204.Count Primes.cpp From e77b530a59dbe8b86628fd778f0895b1f0fe00cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 01:03:17 -0700 Subject: [PATCH 1298/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8c5ee4ae2..c44fe3ac8 100644 --- a/Readme.md +++ b/Readme.md @@ -135,7 +135,6 @@ [166.Fraction-to-Recurring-Decimal](https://github.com/wisdompeak/LeetCode/tree/master/Hash/166.Fraction-to-Recurring-Decimal) (M) [170.Two-Sum-III-Data-structure-design](https://github.com/wisdompeak/LeetCode/tree/master/Hash/170.Two-Sum-III-Data-structure-design) (M) [392.Is-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Hash/392.Is-Subsequence) (H-) -[204.Count Primes](https://github.com/wisdompeak/LeetCode/tree/master/Hash/204.Count-Primes) (M) [274.H-Index](https://github.com/wisdompeak/LeetCode/tree/master/Hash/274.H-Index) (H) [325.Maximum-Size-Subarray-Sum-Equals-k](https://github.com/wisdompeak/LeetCode/tree/master/Hash/325.Maximum-Size-Subarray-Sum-Equals-k) (M) [409.Longest-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Hash/409.Longest-Palindrome) (M) @@ -1074,6 +1073,7 @@ [2221.Find-Triangular-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Math/2221.Find-Triangular-Sum-of-an-Array) (M) [2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps) (M+) * ``Numerical Theory`` +[204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) [365.Water-and-Jug-Problem](https://github.com/wisdompeak/LeetCode/tree/master/Math/365.Water-and-Jug-Problem) (H) [1808.Maximize-Number-of-Nice-Divisors](https://github.com/wisdompeak/LeetCode/tree/master/Math/1808.Maximize-Number-of-Nice-Divisors) (H-) From bd54a315ad6adeb3b7b8f7273b979908b4756212 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 01:15:09 -0700 Subject: [PATCH 1299/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c44fe3ac8..7a0116864 100644 --- a/Readme.md +++ b/Readme.md @@ -1077,7 +1077,7 @@ [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) [365.Water-and-Jug-Problem](https://github.com/wisdompeak/LeetCode/tree/master/Math/365.Water-and-Jug-Problem) (H) [1808.Maximize-Number-of-Nice-Divisors](https://github.com/wisdompeak/LeetCode/tree/master/Math/1808.Maximize-Number-of-Nice-Divisors) (H-) - +[1819.Number-of-Different-Subsequences-GCDs](https://github.com/wisdompeak/LeetCode/tree/master/Math/1819.Number-of-Different-Subsequences-GCDs) (H-) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) From 8950053f1c6b17718af586e24a49e8b07a544300 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 01:21:43 -0700 Subject: [PATCH 1300/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7a0116864..5ff65e8e4 100644 --- a/Readme.md +++ b/Readme.md @@ -1026,7 +1026,6 @@ [1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Math/1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation) (H) [1969.Minimum-Non-Zero-Product-of-the-Array-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/1969.Minimum-Non-Zero-Product-of-the-Array-Elements) (M+) [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) -[2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) @@ -1078,6 +1077,7 @@ [365.Water-and-Jug-Problem](https://github.com/wisdompeak/LeetCode/tree/master/Math/365.Water-and-Jug-Problem) (H) [1808.Maximize-Number-of-Nice-Divisors](https://github.com/wisdompeak/LeetCode/tree/master/Math/1808.Maximize-Number-of-Nice-Divisors) (H-) [1819.Number-of-Different-Subsequences-GCDs](https://github.com/wisdompeak/LeetCode/tree/master/Math/1819.Number-of-Different-Subsequences-GCDs) (H-) +[2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) From fa039aa3223bf73b31494a35add544bc9aad552f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 01:34:35 -0700 Subject: [PATCH 1301/2729] Create 2344.Minimum-Deletions-to-Make-Array-Divisible.cpp --- ...imum-Deletions-to-Make-Array-Divisible.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Math/2344.Minimum-Deletions-to-Make-Array-Divisible/2344.Minimum-Deletions-to-Make-Array-Divisible.cpp diff --git a/Math/2344.Minimum-Deletions-to-Make-Array-Divisible/2344.Minimum-Deletions-to-Make-Array-Divisible.cpp b/Math/2344.Minimum-Deletions-to-Make-Array-Divisible/2344.Minimum-Deletions-to-Make-Array-Divisible.cpp new file mode 100644 index 000000000..8fa809264 --- /dev/null +++ b/Math/2344.Minimum-Deletions-to-Make-Array-Divisible/2344.Minimum-Deletions-to-Make-Array-Divisible.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minOperations(vector& nums, vector& numsDivide) + { + int x = numsDivide[0]; + + for (int i=1; i Date: Mon, 17 Oct 2022 01:37:14 -0700 Subject: [PATCH 1302/2729] Create Readme.md --- Math/2344.Minimum-Deletions-to-Make-Array-Divisible/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Math/2344.Minimum-Deletions-to-Make-Array-Divisible/Readme.md diff --git a/Math/2344.Minimum-Deletions-to-Make-Array-Divisible/Readme.md b/Math/2344.Minimum-Deletions-to-Make-Array-Divisible/Readme.md new file mode 100644 index 000000000..88b3adf26 --- /dev/null +++ b/Math/2344.Minimum-Deletions-to-Make-Array-Divisible/Readme.md @@ -0,0 +1,3 @@ +### 2344.Minimum-Deletions-to-Make-Array-Divisible + +非常直观。要numsDivide里面所有的元素都能整除x,充要条件就是`gcd(numsDivide)`也能整除x。所以我们将nums里面所有小于gcd的元素拿走即可。 From 6d1379e9b03c0955b957ebdbd96d9cde00974065 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 01:37:39 -0700 Subject: [PATCH 1303/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5ff65e8e4..ea0c20744 100644 --- a/Readme.md +++ b/Readme.md @@ -1078,6 +1078,7 @@ [1808.Maximize-Number-of-Nice-Divisors](https://github.com/wisdompeak/LeetCode/tree/master/Math/1808.Maximize-Number-of-Nice-Divisors) (H-) [1819.Number-of-Different-Subsequences-GCDs](https://github.com/wisdompeak/LeetCode/tree/master/Math/1819.Number-of-Different-Subsequences-GCDs) (H-) [2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) +[2344.Minimum-Deletions-to-Make-Array-Divisible](https://github.com/wisdompeak/LeetCode/tree/master/Math/2344.Minimum-Deletions-to-Make-Array-Divisible) (E) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) From e66838175fbf4ede7538cca77c7c548c688c45e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Oct 2022 23:14:45 -0700 Subject: [PATCH 1304/2729] Update 1140.Stone-Game-II.cpp --- .../1140.Stone-Game-II/1140.Stone-Game-II.cpp | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/Recursion/1140.Stone-Game-II/1140.Stone-Game-II.cpp b/Recursion/1140.Stone-Game-II/1140.Stone-Game-II.cpp index 19d3fea5d..0fd95d70d 100644 --- a/Recursion/1140.Stone-Game-II/1140.Stone-Game-II.cpp +++ b/Recursion/1140.Stone-Game-II/1140.Stone-Game-II.cpp @@ -1,28 +1,30 @@ class Solution { - int dp[101][101]; - int sufsum[101]; + int dp[101][101]; + int suf[101]; + public: int stoneGameII(vector& piles) { int n = piles.size(); - for (int i=0; i<=100; i++) - for (int j=0; j<=100; j++) - dp[i][j] = 0; - sufsum[n] = 0; + suf[n] = 0; for (int i=n-1; i>=0; i--) - sufsum[i] = sufsum[i+1]+piles[i]; + suf[i] = suf[i+1]+piles[i]; + return solve(0, 1, piles); } - + int solve(int i, int M, vector& piles) { if (i==piles.size()) return 0; - if (dp[i][M]!=0) return dp[i][M]; - + if (dp[i][M]!=0) + return dp[i][M]; + + int sum = 0; for (int x=1; x<=2*M; x++) { - if (i+x>piles.size()) break; - dp[i][M] = max(dp[i][M], sufsum[i] - solve(i+x, max(x,M), piles)); + if (i+x-1>=piles.size()) break; + sum += piles[i+x-1]; + dp[i][M] = max(dp[i][M], sum + suf[i+x] - solve(i+x, max(x,M), piles)); } return dp[i][M]; } From 5f5b180ba4f39fb9dcbeed674cbe294f6d1d170d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Oct 2022 00:08:54 -0700 Subject: [PATCH 1305/2729] Create 2345.Finding-the-Number-of-Visible-Mountains.cpp --- ...inding-the-Number-of-Visible-Mountains.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Greedy/2345.Finding-the-Number-of-Visible-Mountains/2345.Finding-the-Number-of-Visible-Mountains.cpp diff --git a/Greedy/2345.Finding-the-Number-of-Visible-Mountains/2345.Finding-the-Number-of-Visible-Mountains.cpp b/Greedy/2345.Finding-the-Number-of-Visible-Mountains/2345.Finding-the-Number-of-Visible-Mountains.cpp new file mode 100644 index 000000000..b913c51eb --- /dev/null +++ b/Greedy/2345.Finding-the-Number-of-Visible-Mountains/2345.Finding-the-Number-of-Visible-Mountains.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int visibleMountains(vector>& peaks) + { + sort(peaks.begin(), peaks.end(), [](vector&a, vector&b){ + int l1=a[0]-a[1], r1=a[0]+a[1]; + int l2=b[0]-b[1], r2=b[0]+b[1]; + if (l1!=l2) return l1r2; + }); + + int n = peaks.size(); + int rightMost = -1; + int ret = 0; + for (int i=0; i0 && peaks[i]==peaks[i-1]) continue; + if (peaks[i][0]+peaks[i][1] > rightMost) + { + rightMost = peaks[i][0]+peaks[i][1]; + if (i==n-1 || peaks[i]!=peaks[i+1]) + ret++; + } + } + + return ret; + } +}; From 37dec0282a23339089f1c8eb464dc989ae1ee8f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Oct 2022 00:09:25 -0700 Subject: [PATCH 1306/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ea0c20744..795ee99d1 100644 --- a/Readme.md +++ b/Readme.md @@ -1201,6 +1201,7 @@ [2250.Count-Number-of-Rectangles-Containing-Each-Point](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point) (H-) [2343.Query-Kth-Smallest-Trimmed-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2343.Query-Kth-Smallest-Trimmed-Number) (H-) [2412.Minimum-Money-Required-Before-Transactions](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2412.Minimum-Money-Required-Before-Transactions) (H-) +[2345.Finding-the-Number-of-Visible-Mountains](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2345.Finding-the-Number-of-Visible-Mountains) (H-) * ``Indexing Sort`` [041.First-Missing-Positive](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/041.First-Missing-Positive/Readme.md) (H) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 8f6c1a8fc7c0879428f72fc220d74699af74cf54 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Oct 2022 12:13:04 -0700 Subject: [PATCH 1307/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2345.Finding-the-Number-of-Visible-Mountains/Readme.md diff --git a/Greedy/2345.Finding-the-Number-of-Visible-Mountains/Readme.md b/Greedy/2345.Finding-the-Number-of-Visible-Mountains/Readme.md new file mode 100644 index 000000000..72a6d08e9 --- /dev/null +++ b/Greedy/2345.Finding-the-Number-of-Visible-Mountains/Readme.md @@ -0,0 +1,9 @@ +### 2345.Finding-the-Number-of-Visible-Mountains + +本题的突破点在于这个发现:如果三角形A的左端点早于三角形B的左端点,那么A一定不会被B覆盖。所以将所有的三角形按照左端点排序,那我们能看到的三角形的顺序一定不会违反这个序列。 + +接下来思考,虽然A不会被B覆盖,但是B依然可能会被A覆盖。如何判定呢?其实就取决于A的右端点是否足够远。如果A的右端点足够远,那么它有可能还会覆盖后续的若干个三角形。 + +所以基本思想就是,将所有三角形按照左端点排序,遍历每个三角形的时候维护当前最远的右端点的位置far。任何新的三角形的右端点的位置如果在far前面,就说明它是会被前面的三角形所覆盖的。 + +本题的corner case是,如果有两个三角形的左端点相同,那如何排序?不难想到,我们先处理右端点更远的,这样就保证它能把其他的三角形给遮盖了。 From 1afb6ebdc337d841f9d68aa4344ea68e4d201b83 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 10:29:34 -0700 Subject: [PATCH 1308/2729] Update Readme.md --- Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md index 6ad7847fb..09890e3db 100644 --- a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md +++ b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md @@ -1,5 +1,7 @@ ### 2366.Minimum-Replacements-to-Sort-the-Array +#### 解法1 + 我们从后往前看,对于最后一个数,我们肯定不会拆分。一旦将其拆分的话变小的话,那么前面的数就有更大的概率需要拆得更小。 接着假设最后一个数是x,倒数第二个数是y。如果y小于等于x,那么最后两个元素已经是递增关系,y就不用拆分了,理由同上。如果y大于x,那么就必须拆分y,那么怎么拆分呢? @@ -21,3 +23,6 @@ p <= (x-d) / (k+1) 此时这是不是最优的操作呢?并不是。如果`d2 < x2`,其实我们可以将k个x2里面的一部分(而不是整体)拿出1来再贡献给d2,必然可以使得d2再拉至于x2-1平齐的高度。这是因为之前我们知道,如果k个x2每人都再贡献1出来,会导致`d2`会比`x2-1`还大。所以这意味着,如果贡献出部分的1出来,就能让`d2`与`x2-1`持平。在这种情况下,`x2-1`就是拆分出来的k+1份里的最小值。 于是,这个回合结束我们将nums[i]赋值为`x2`(如果`d2==x2`)或者`x2-1`(如果`d2 Date: Sun, 23 Oct 2022 10:30:40 -0700 Subject: [PATCH 1309/2729] Update Readme.md --- Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md index 09890e3db..040c70502 100644 --- a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md +++ b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/Readme.md @@ -25,4 +25,4 @@ p <= (x-d) / (k+1) 于是,这个回合结束我们将nums[i]赋值为`x2`(如果`d2==x2`)或者`x2-1`(如果`d2 Date: Sun, 23 Oct 2022 10:33:15 -0700 Subject: [PATCH 1310/2729] Create 2366.Minimum-Replacements-to-Sort-the-Array_v2.cpp --- ...imum-Replacements-to-Sort-the-Array_v2.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Greedy/2366.Minimum-Replacements-to-Sort-the-Array/2366.Minimum-Replacements-to-Sort-the-Array_v2.cpp diff --git a/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/2366.Minimum-Replacements-to-Sort-the-Array_v2.cpp b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/2366.Minimum-Replacements-to-Sort-the-Array_v2.cpp new file mode 100644 index 000000000..e68e842b5 --- /dev/null +++ b/Greedy/2366.Minimum-Replacements-to-Sort-the-Array/2366.Minimum-Replacements-to-Sort-the-Array_v2.cpp @@ -0,0 +1,28 @@ +using LL = long long; +class Solution { +public: + long long minimumReplacement(vector& nums) + { + LL ret = 0; + for (int i = nums.size()-2; i>=0; i--) + { + LL x = nums[i+1]; + LL y = nums[i]; + if (y<=x) continue; + + if (y%x==0) + { + ret += y/x-1; + nums[i] = x; + } + else + { + int k = y/x+1; + ret += y/x; + nums[i] = y/k; + } + } + + return ret; + } +}; From 45d30b709f6dde23a0cffb0226cc18ce7505e95a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 11:14:22 -0700 Subject: [PATCH 1311/2729] Create 2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp --- ...r-of-Operations-to-Make-Arrays-Similar.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp diff --git a/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp b/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp new file mode 100644 index 000000000..35ba72b92 --- /dev/null +++ b/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp @@ -0,0 +1,56 @@ +using LL = long long; +class Solution { +public: + long long makeSimilar(vector& nums, vector& target) + { + vectorodd1, odd2, even1, even2; + for (auto x: nums) + { + if (x%2==0) + even1.push_back(x); + else + odd1.push_back(x); + } + for (auto x: target) + { + if (x%2==0) + even2.push_back(x); + else + odd2.push_back(x); + } + auto [ret1, buff1] = helper(even1, even2); + auto [ret2, buff2] = helper(odd1, odd2); + return ret1 + ret2 - abs(buff1)/2; + } + + pair helper(vector&nums, vector&target) + { + sort(target.begin(), target.end()); + sort(nums.begin(), nums.end()); + + LL buff = 0; + LL ret = 0; + for (int i=0; i= 0) + { + if (buff < 0) + diff = max(0LL, diff + buff); + ret += diff / 2; + } + else + { + if (buff > 0) + diff = min(0LL, diff + buff); + ret += abs(diff) / 2; + } + buff += y-x; + } + + return {ret, buff}; + } + +}; From 77503dedd8f844a3b55adaca0908fc57a8256335 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 11:19:25 -0700 Subject: [PATCH 1312/2729] Update 115.Distinct-Subsequences.cpp --- .../115.Distinct-Subsequences/115.Distinct-Subsequences.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Dynamic_Programming/115.Distinct-Subsequences/115.Distinct-Subsequences.cpp b/Dynamic_Programming/115.Distinct-Subsequences/115.Distinct-Subsequences.cpp index e4266191e..dfba2ce32 100644 --- a/Dynamic_Programming/115.Distinct-Subsequences/115.Distinct-Subsequences.cpp +++ b/Dynamic_Programming/115.Distinct-Subsequences/115.Distinct-Subsequences.cpp @@ -20,10 +20,9 @@ class Solution { for (int j=1; j<=n; j++) { if (s[i]==t[j]) - dp[i][j] = dp[i-1][j] + dp[i-1][j-1]; + dp[i][j] = min(LLONG_MAX/2, dp[i-1][j] + dp[i-1][j-1]); else dp[i][j] = dp[i-1][j]; - //cout< Date: Sun, 23 Oct 2022 11:22:05 -0700 Subject: [PATCH 1313/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 795ee99d1..bad089cdf 100644 --- a/Readme.md +++ b/Readme.md @@ -1145,6 +1145,7 @@ [2365.Task-Scheduler-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2365.Task-Scheduler-II) (M) [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) [2371.Minimize-Maximum-Value-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2371.Minimize-Maximum-Value-in-a-Grid) (M+) +[2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar) (M+) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From b4ca3f7c86bd10347d4b4d6b8328f163f0ca87f7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 12:06:45 -0700 Subject: [PATCH 1314/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/Readme.md diff --git a/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/Readme.md b/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/Readme.md new file mode 100644 index 000000000..63a124368 --- /dev/null +++ b/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/Readme.md @@ -0,0 +1,13 @@ +### 2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar + +很显然题目的意思是,nums经过一系列操作之后,需要变成targets。于是nums和targets的数组元素之和必然相等,否则无法实现+2/-2的守恒。 + +另外,我们发现,偶数无论如何也无法操作成奇数,反之亦然。所以知道,需要将奇数偶数分开处理,即nums里的奇数需要多少操作转化为targets里的奇数,同理nums里的偶数需要多少操作否转化为targets里的偶数。 + +接下来,我们考虑只含有奇数的nums数组和只含有奇数的targets数组。很明显,我们必然会把nums[0]转化为targets[0],将nums[1]转化为targets[1],依次类推。这样能使得每对元素差的绝对值之和最小。简单的证明可以从两对开始研究。假设有`nums[i] Date: Sun, 23 Oct 2022 12:07:26 -0700 Subject: [PATCH 1315/2729] Update 2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp --- ...r-of-Operations-to-Make-Arrays-Similar.cpp | 32 ++++--------------- 1 file changed, 7 insertions(+), 25 deletions(-) diff --git a/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp b/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp index 35ba72b92..a766e4111 100644 --- a/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp +++ b/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar.cpp @@ -18,39 +18,21 @@ class Solution { else odd2.push_back(x); } - auto [ret1, buff1] = helper(even1, even2); - auto [ret2, buff2] = helper(odd1, odd2); - return ret1 + ret2 - abs(buff1)/2; + + return helper(even1, even2) + helper(odd1, odd2); } - pair helper(vector&nums, vector&target) + LL helper(vector&nums, vector&target) { sort(target.begin(), target.end()); sort(nums.begin(), nums.end()); - LL buff = 0; - LL ret = 0; + LL count = 0; for (int i=0; i= 0) - { - if (buff < 0) - diff = max(0LL, diff + buff); - ret += diff / 2; - } - else - { - if (buff > 0) - diff = min(0LL, diff + buff); - ret += abs(diff) / 2; - } - buff += y-x; - } + if (nums[i] > target[i]) + count += (nums[i]-target[i])/2; - return {ret, buff}; + return count; } }; From 796aeced7f821a15a9ca0647ba7e042d673fa22a Mon Sep 17 00:00:00 2001 From: Xiao Sun Date: Sun, 23 Oct 2022 16:53:17 -0400 Subject: [PATCH 1316/2729] Update Readme.md --- .../1458.Max-Dot-Product-of-Two-Subsequences/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1458.Max-Dot-Product-of-Two-Subsequences/Readme.md b/Dynamic_Programming/1458.Max-Dot-Product-of-Two-Subsequences/Readme.md index a71581039..244e33823 100644 --- a/Dynamic_Programming/1458.Max-Dot-Product-of-Two-Subsequences/Readme.md +++ b/Dynamic_Programming/1458.Max-Dot-Product-of-Two-Subsequences/Readme.md @@ -3,6 +3,6 @@ 这是一道典型的双序列型的DP。令dp[i][j]表示A序列的前i个元素、B序列的前j个元素,可以得到的最大点乘结果。突破口就是看A[i]和B[j]。 1. A[i]和B[j]组成一对,那么dp[i][j] = dp[i-1][j-1]+A[i]*B[j]。注意,当dp[i-1][j-1]<0时,该项其实应该略去,即dp[i][j] = A[i]*B[j]. -2. A[i]和B[j]不组成一对,那么这两个元素必然至少有一个不会被用来参与点乘。所以dp[i][j] = min{dp[i-1][j], dp[i][j-1]}. +2. A[i]和B[j]不组成一对,那么这两个元素必然至少有一个不会被用来参与点乘。所以dp[i][j] = max{dp[i-1][j], dp[i][j-1]}. 最终的答案是dp[m][n]. From eb8ac9e4d1b5e0e6da77813f8f311e621e0e5c92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 16:16:46 -0700 Subject: [PATCH 1317/2729] Create 2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp --- ...48.Minimum-Cost-to-Make-Array-Equal_v1.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp diff --git a/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp b/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp new file mode 100644 index 000000000..aadce7aa0 --- /dev/null +++ b/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp @@ -0,0 +1,39 @@ +using LL = long long; +class Solution { +public: + long long minCost(vector& nums, vector& cost) + { + int n = nums.size(); + vector>arr; + for (int i=0; ileft(n, 0); + LL sum = arr[0].second; + for (int i=1; iright(n, 0); + sum = arr[n-1].second; + for (int i=n-2; i>=0; i--) + { + LL delta = arr[i+1].first - arr[i].first; + right[i] = right[i+1] + delta * sum; + sum += arr[i].second; + } + + vectorall(n,0); + for (int i=0; i Date: Sun, 23 Oct 2022 16:17:25 -0700 Subject: [PATCH 1318/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bad089cdf..e4bc2d992 100644 --- a/Readme.md +++ b/Readme.md @@ -1030,6 +1030,7 @@ * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) +[2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) From b574cd49b4b4f6835d19251db2ffdc8d9138fc28 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 16:18:15 -0700 Subject: [PATCH 1319/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index e4bc2d992..9d25fb272 100644 --- a/Readme.md +++ b/Readme.md @@ -1030,9 +1030,9 @@ * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) -[2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) +[2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) From 9d378fb7d21c7cfad7424ba513c74f7bcfe0db2c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 16:19:03 -0700 Subject: [PATCH 1320/2729] Rename 2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp to 2448.Minimum-Cost-to-Make-Array-Equal_v2.cpp --- ...-Equal_v1.cpp => 2448.Minimum-Cost-to-Make-Array-Equal_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2448.Minimum-Cost-to-Make-Array-Equal/{2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp => 2448.Minimum-Cost-to-Make-Array-Equal_v2.cpp} (100%) diff --git a/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp b/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v2.cpp similarity index 100% rename from Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp rename to Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v2.cpp From bb0b62504b43b99b257ea03306c4a76ef8627eee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 16:29:39 -0700 Subject: [PATCH 1321/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9d25fb272..3d5b8e347 100644 --- a/Readme.md +++ b/Readme.md @@ -1029,6 +1029,7 @@ [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) +462.Minimum-Moves-to-Equal-Array-Elements-II [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) From 17fd0996ed2e697d17728ecb343f5f4a0aa854f4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Oct 2022 16:44:43 -0700 Subject: [PATCH 1322/2729] Create 2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp --- ...48.Minimum-Cost-to-Make-Array-Equal_v1.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp diff --git a/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp b/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp new file mode 100644 index 000000000..7277528f9 --- /dev/null +++ b/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { +public: + long long minCost(vector& nums, vector& cost) + { + int n = nums.size(); + vector>arr; + for (int i=0; i= totalCost/2) + { + k = i; + break; + } + } + + LL ret = 0; + for (int i=0; i Date: Sun, 23 Oct 2022 23:14:40 -0700 Subject: [PATCH 1323/2729] Create Readme.md --- Math/2448.Minimum-Cost-to-Make-Array-Equal/Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Math/2448.Minimum-Cost-to-Make-Array-Equal/Readme.md diff --git a/Math/2448.Minimum-Cost-to-Make-Array-Equal/Readme.md b/Math/2448.Minimum-Cost-to-Make-Array-Equal/Readme.md new file mode 100644 index 000000000..47697f225 --- /dev/null +++ b/Math/2448.Minimum-Cost-to-Make-Array-Equal/Readme.md @@ -0,0 +1,12 @@ +### 2448.Minimum-Cost-to-Make-Array-Equal + +#### 解法1: +如果本题的所有cost[i]都是1的话,我们发现这其实就是`296.Best-Meeting-Point`。我们应该对这个结论很熟悉:对于一维序列{xi},我们想找一个位置p使得`sum{abs(xi-p)}`最小化,那么p的位置一定就是{xi}的中位数。 + +对于本题而言,我们想找一个位置p使得`sum{abs(xi-p)*cost[i]}`最小化。这其实可以卡成将每个xi复制cost[i]份,从而得到一个长度为totalCost的序列,然后回归到上述的问题。显然,我们想要找的位置就是新序列的中位数。我们只需要每查看一个xi,就增加`count+=cost[i]`,直至发现count恰好超过了totalCost的一半时候为止,这个xi就是best equal value. + + +#### 解法2: +对于这类题目,我们通常会有一个大胆的猜测,最优解所对应的“best equal value”一定是nums里的某一个元素。为什么呢?假设这个best equal value是x,位于排序后的某两个元素之间(记做nums[i]和nums[j]),那么我们可以论证还会有比x更优的解。假如我们将equal value设为x+1,那么对于右边的元素,总共会减少costSum[j:n-1],对于左边的元素,总共会增加costSum[0:i],即`delta1 = costSum[0:i]-costSum[j:n-1]`. 假如我们将equal value设为x-1,类似的会有`delta2 = -costSum[0:i]+costSum[j:n-1]`。通常情况下delta1和delta2必然是一正一负,这就意味着必然有一个方向能够得到更优的策略(即x+1或者x-1)。这个方向的移动可以持续,直至best equal value设置在了nums[i]或者nums[j]上。 + +有了这个想法,我们只需要遍历一遍每个nums[i],假想它是equal value的话,cost是多少。cost包括了左边元素的提升costLeft,以及右边元素的下降costRight。我们从左往右遍历的时候,costLeft都是可以一路累加的,即`costLeft[i] = costLeft[i-1]+costSum[i:i-1]*(nums[i]-nums[i-1])`. 同理我们从右往左走一遍,求得所有的costRight[i]。最终我们挑选最小的`costLeft[i]+costRight[i]`. From 5c8c3372fa2e99a96f9d6d3309b0fb6a14b1bf61 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Oct 2022 00:13:25 -0700 Subject: [PATCH 1324/2729] Update 204.Count Primes.cpp --- Math/204.Count-Primes/204.Count Primes.cpp | 24 ++++++++-------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/Math/204.Count-Primes/204.Count Primes.cpp b/Math/204.Count-Primes/204.Count Primes.cpp index 12e036640..45539ed0e 100644 --- a/Math/204.Count-Primes/204.Count Primes.cpp +++ b/Math/204.Count-Primes/204.Count Primes.cpp @@ -1,25 +1,17 @@ class Solution { public: int countPrimes(int n) - { - if (n<=2) return 0; + { + vector isPrime(n, 1); + int count = 0; - vector num(n - 1, true); - - for (int x = 2; x <= sqrt(n); x++) + for (int i = 2; i < n; i++) { - if (num[x]==false) continue; - - for (int j=2; x*j < n; j++) - num[x*j] = false; + if (isPrime[i]==false) continue; + count++; + for (int j=2*i; j < n; j+=i) + isPrime[j] = false; } - - int count=0; - for (int j = 2; j < n; ++j) - { - if (num[j]) count++; - } - return count; } }; From 1a669c500d79a66fa82bb62d99d5f48f5acf87a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Oct 2022 00:30:14 -0700 Subject: [PATCH 1325/2729] Update Readme.md --- Math/204.Count-Primes/Readme.md | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/Math/204.Count-Primes/Readme.md b/Math/204.Count-Primes/Readme.md index 0c048af5a..391011121 100644 --- a/Math/204.Count-Primes/Readme.md +++ b/Math/204.Count-Primes/Readme.md @@ -1,18 +1,6 @@ ### 204.Count-Primes -用倍数筛除法去除所有已知质数的倍数。 -```cpp -vectorq(n,true); -for (x=2; x<=sqrt(n); x++) -{ - if (q[x]==false) continue; - for (int i=2; x*i Date: Mon, 24 Oct 2022 00:31:59 -0700 Subject: [PATCH 1326/2729] Rename 204.Count Primes.cpp to 204.Count-Primes.cpp --- .../{204.Count Primes.cpp => 204.Count-Primes.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/204.Count-Primes/{204.Count Primes.cpp => 204.Count-Primes.cpp} (100%) diff --git a/Math/204.Count-Primes/204.Count Primes.cpp b/Math/204.Count-Primes/204.Count-Primes.cpp similarity index 100% rename from Math/204.Count-Primes/204.Count Primes.cpp rename to Math/204.Count-Primes/204.Count-Primes.cpp From 6789f2d1d9ff111c38061619437e08b1f4a9535b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Oct 2022 00:47:11 -0700 Subject: [PATCH 1327/2729] Update 204.Count-Primes.cpp --- Math/204.Count-Primes/204.Count-Primes.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Math/204.Count-Primes/204.Count-Primes.cpp b/Math/204.Count-Primes/204.Count-Primes.cpp index 45539ed0e..6c7f07dde 100644 --- a/Math/204.Count-Primes/204.Count-Primes.cpp +++ b/Math/204.Count-Primes/204.Count-Primes.cpp @@ -1,17 +1,19 @@ class Solution { public: int countPrimes(int n) - { - vector isPrime(n, 1); + { + vectorisPrime(n, true); int count = 0; - - for (int i = 2; i < n; i++) + for (int i=2; i Date: Wed, 26 Oct 2022 17:33:12 -0700 Subject: [PATCH 1328/2729] Update Readme.md --- Deque/1499.Max-Value-of-Equation/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Deque/1499.Max-Value-of-Equation/Readme.md b/Deque/1499.Max-Value-of-Equation/Readme.md index ebeb9fe22..37ab1180c 100644 --- a/Deque/1499.Max-Value-of-Equation/Readme.md +++ b/Deque/1499.Max-Value-of-Equation/Readme.md @@ -1,5 +1,5 @@ ### 1499.Max-Value-of-Equation -如果我们固定j点,那么原题就是求```max{yi+yj+xj-xi} = max{-xi+yi} + xj+yj ```.也就是要在|xi-xj| Date: Wed, 26 Oct 2022 17:38:52 -0700 Subject: [PATCH 1329/2729] Update 1499.Max-Value-of-Equation.cpp --- .../1499.Max-Value-of-Equation.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp b/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp index d18832742..1a4ba3b63 100644 --- a/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp +++ b/Deque/1499.Max-Value-of-Equation/1499.Max-Value-of-Equation.cpp @@ -10,15 +10,17 @@ class Solution { q.pop_front(); } + if (q.size() > 0) { + ret = max(ret, -points[q.front()][0]+points[q.front()][1] + points[i][0]+points[i][1]); + } + while (q.size()>0 && -points[q.back()][0]+points[q.back()][1] < -points[i][0]+points[i][1]) { q.pop_back(); } q.push_back(i); - if (q.size() > 0) { - ret = max(ret, -points[q.front()][0]+points[q.front()][1] + points[i][0]+points[i][1]); - } + } return ret; } From 2fd303f23d2f7c8994277b6fda3e9553aeae07a6 Mon Sep 17 00:00:00 2001 From: Ca Chen Date: Thu, 27 Oct 2022 12:21:09 +0800 Subject: [PATCH 1330/2729] missing code blocks closing tag --- Two_Pointers/015.3Sum/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Two_Pointers/015.3Sum/Readme.md b/Two_Pointers/015.3Sum/Readme.md index 39aa5b10f..ce9ffe746 100644 --- a/Two_Pointers/015.3Sum/Readme.md +++ b/Two_Pointers/015.3Sum/Readme.md @@ -13,7 +13,7 @@ while (left Date: Sun, 30 Oct 2022 18:23:12 -0700 Subject: [PATCH 1331/2729] Update 2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp --- .../2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp b/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp index 7277528f9..17616c4f0 100644 --- a/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp +++ b/Math/2448.Minimum-Cost-to-Make-Array-Equal/2448.Minimum-Cost-to-Make-Array-Equal_v1.cpp @@ -17,7 +17,7 @@ class Solution { for (int i=0; i= totalCost/2) + if (curCost >= totalCost*1.0/2) { k = i; break; From 389bf2028e84079c29ad8d283fb799c8694d57b0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 30 Oct 2022 19:40:18 -0700 Subject: [PATCH 1332/2729] Create 907.Sum-of-Subarray-Minimums_v2.cpp --- .../907.Sum-of-Subarray-Minimums_v2.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Stack/907.Sum-of-Subarray-Minimums/907.Sum-of-Subarray-Minimums_v2.cpp diff --git a/Stack/907.Sum-of-Subarray-Minimums/907.Sum-of-Subarray-Minimums_v2.cpp b/Stack/907.Sum-of-Subarray-Minimums/907.Sum-of-Subarray-Minimums_v2.cpp new file mode 100644 index 000000000..802ac8300 --- /dev/null +++ b/Stack/907.Sum-of-Subarray-Minimums/907.Sum-of-Subarray-Minimums_v2.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int sumSubarrayMins(vector& arr) + { + int n = arr.size(); + vectornextSmaller(n, n); + vectorprevSmaller(n, -1); + + stackStack; + for (int i=0; i arr[i]) + { + nextSmaller[Stack.top()] = i; + Stack.pop(); + } + + if (!Stack.empty()) + prevSmaller[i] = Stack.top(); + Stack.push(i); + } + + + long ret = 0; + long M = 1e9+7; + for (int i=0; i Date: Sun, 30 Oct 2022 19:41:41 -0700 Subject: [PATCH 1333/2729] Update Readme.md --- Stack/907.Sum-of-Subarray-Minimums/Readme.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Stack/907.Sum-of-Subarray-Minimums/Readme.md b/Stack/907.Sum-of-Subarray-Minimums/Readme.md index 500851280..6481a1ed5 100644 --- a/Stack/907.Sum-of-Subarray-Minimums/Readme.md +++ b/Stack/907.Sum-of-Subarray-Minimums/Readme.md @@ -8,5 +8,21 @@ 所以本题确切的说,是求每个元素的next smaller element,以及previous smaller or equal element. 另外,特别注意:如果一个数没有next smaller element,那么意味着它的左边界是可以到n;如果一个数没有prev smaller/equal element,那么意味着它的左边界是可以到-1. +Update: 事实上,`next smaller element`和`previous smaller or equal element`可以one-pass同时实现。 +```cpp + for (int i=0; i arr[i]) + { + nextSmaller[Stack.top()] = i; + Stack.pop(); + } -[Leetcode Link](https://leetcode.com/problems/sum-of-subarray-minimums) \ No newline at end of file + if (!Stack.empty()) + prevSmaller[i] = Stack.top(); + Stack.push(i); + } +``` + + +[Leetcode Link](https://leetcode.com/problems/sum-of-subarray-minimums) From d24a8b175230fba54bfbcae131f5f5f903df641c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 30 Oct 2022 20:00:53 -0700 Subject: [PATCH 1334/2729] Create 2453.Destroy-Sequential-Targets.cpp --- .../2453.Destroy-Sequential-Targets.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Others/2453.Destroy-Sequential-Targets/2453.Destroy-Sequential-Targets.cpp diff --git a/Others/2453.Destroy-Sequential-Targets/2453.Destroy-Sequential-Targets.cpp b/Others/2453.Destroy-Sequential-Targets/2453.Destroy-Sequential-Targets.cpp new file mode 100644 index 000000000..37384bb2f --- /dev/null +++ b/Others/2453.Destroy-Sequential-Targets/2453.Destroy-Sequential-Targets.cpp @@ -0,0 +1,32 @@ +using LL = long long; +class Solution { +public: + int destroyTargets(vector& nums, int space) + { + int len = 0; + int ret = 0; + + sort(nums.rbegin(), nums.rend()); + + unordered_mapdp; + + for (int i=0; i len) + { + ret = nums[i]; + len = dp[r]; + } + else if (dp[r] == len) + { + ret = nums[i]; + } + + } + + return ret; + } +}; From fd030478584f4afb25797f81cae05506780224d7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 30 Oct 2022 20:01:45 -0700 Subject: [PATCH 1335/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3d5b8e347..38c206e00 100644 --- a/Readme.md +++ b/Readme.md @@ -1287,6 +1287,7 @@ [2337.Move-Pieces-to-Obtain-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2337.Move-Pieces-to-Obtain-a-String) (aka. 777.Swap-Adjacent-in-LR-String) (M+) [2359.Find-Closest-Node-to-Given-Two-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2359.Find-Closest-Node-to-Given-Two-Nodes) (M) [2380.Time-Needed-to-Rearrange-a-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2380.Time-Needed-to-Rearrange-a-Binary-String) (H) +[2453.Destroy-Sequential-Targets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2453.Destroy-Sequential-Targets) (M) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 72e4e89298ab4f64cc43a8213068c4df2e899283 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 30 Oct 2022 20:17:57 -0700 Subject: [PATCH 1336/2729] Create Readme.md --- Others/2453.Destroy-Sequential-Targets/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2453.Destroy-Sequential-Targets/Readme.md diff --git a/Others/2453.Destroy-Sequential-Targets/Readme.md b/Others/2453.Destroy-Sequential-Targets/Readme.md new file mode 100644 index 000000000..19c7839e8 --- /dev/null +++ b/Others/2453.Destroy-Sequential-Targets/Readme.md @@ -0,0 +1,5 @@ +### 2453.Destroy-Sequential-Targets + +很明显,能够构成序列的位置必然是间隔为space的等差数列。不同的等差数列之间仅仅区别于offset,这个offset就是关于space的余数。例如,space如果是3,那么就有三种等差数列{0,3,6,9...},{1,4,7,10...},{2,5,8,11...}。 + +我们将所有的位置逆序排列,对于任意nums[i],令`r = nums[i] % space`,那么说明此位置属于offset为r的序列上,就有`dp[r] += 1`. 最终我们返回最长的dp[r]所对应的最后一个元素。 From 2c2ef32b56f83dd171c1ea2e3ebb5846824aff4c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 30 Oct 2022 20:20:14 -0700 Subject: [PATCH 1337/2729] Create 2454.Next-Greater-Element-IV.cpp --- .../2454.Next-Greater-Element-IV.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Stack/2454.Next-Greater-Element-IV/2454.Next-Greater-Element-IV.cpp diff --git a/Stack/2454.Next-Greater-Element-IV/2454.Next-Greater-Element-IV.cpp b/Stack/2454.Next-Greater-Element-IV/2454.Next-Greater-Element-IV.cpp new file mode 100644 index 000000000..c9bc1b724 --- /dev/null +++ b/Stack/2454.Next-Greater-Element-IV/2454.Next-Greater-Element-IV.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + vector secondGreaterElement(vector& nums) + { + stackst1; + stackst2; + + vectorrets(nums.size(), -1); + + for (int i=0; itemp; + while (!st1.empty() && nums[st1.top()] < nums[i]) + { + temp.push_back(st1.top()); + st1.pop(); + } + + reverse(temp.begin(), temp.end()); + for (auto x: temp) + st2.push(x); + + st1.push(i); + } + + return rets; + } +}; From 3115ac58397dca3a7e1fbb2232611a186ab0afb2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 30 Oct 2022 20:20:37 -0700 Subject: [PATCH 1338/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 38c206e00..64f2131de 100644 --- a/Readme.md +++ b/Readme.md @@ -359,6 +359,7 @@ [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) +[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) * ``monotonic stack: other usages`` [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) From 4286e56b23e610dd086328ed1b327a8c2021c74b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 30 Oct 2022 22:25:11 -0700 Subject: [PATCH 1339/2729] Create Readme.md --- Stack/2454.Next-Greater-Element-IV/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Stack/2454.Next-Greater-Element-IV/Readme.md diff --git a/Stack/2454.Next-Greater-Element-IV/Readme.md b/Stack/2454.Next-Greater-Element-IV/Readme.md new file mode 100644 index 000000000..4db7f0e98 --- /dev/null +++ b/Stack/2454.Next-Greater-Element-IV/Readme.md @@ -0,0 +1,9 @@ +### 2454.Next-Greater-Element-IV + +我们已经知道,常规的Next Greater Element可以用单调栈实现o(n)的解法。我们维护一个单调递减的栈,如果遇到新元素大于栈顶元素,就意味着栈顶元素遇到了next greater element,于是就可以退栈。 + +在此题里,栈顶元素遇到了next greater selement,并不意味着它就可以一劳永逸地舍弃。我们需要的是the second greater element,于是我们应该对这些元素进行标记,表示他们已经看到了一次next greater。当它们再次遇到greater element的时候,才能记录答案。 + +那么如何标记呢?如果把常规的单调栈记做stk1,那么我们可以把遇到过next greater的元素拿出来,放入另外一个单调栈里,记做stk2。每次新来一个元素nums[i],先看stk2的栈顶元素是否小于num[i],是的话就意味着这些栈顶元素遇到了the second greater element,就可以记录答案并退栈了。接下来看stk1的栈顶元素是否小于nums[i],同理,是的话就意味着这些栈顶元素遇到过了next greater element,并将其移至stk2中。 + +这里要注意一定,将stk1的元素移至stk2的过程中,是否会干扰stk2的单调顺序?是不会的。stk2经过退栈之后,栈顶元素一定是大于nums[i]的;而从stk1转移至stk2的这些元素都是小于nums[i]的,所以我们可以放心将转移的元素都堆在stk1的栈顶,依然能保持stk2的递减性质。 From 93ef9c0b63c0fd58b03ddc1207fe5d6795cefbae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 31 Oct 2022 00:32:38 -0700 Subject: [PATCH 1340/2729] Create 2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp --- ...mum-Addition-to-Make-Integer-Beautiful.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp diff --git a/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp b/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp new file mode 100644 index 000000000..aa4ed56b2 --- /dev/null +++ b/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int getSum(long long x) + { + int sum = 0; + while (x>0) + { + sum += x%10; + x/=10; + } + return sum; + } + + long long makeIntegerBeautiful(long long n, int target) + { + int len = to_string(n).size(); + string ret; + + int carry = 0; + for (int i=0; i Date: Mon, 31 Oct 2022 00:33:10 -0700 Subject: [PATCH 1341/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 64f2131de..b943280c6 100644 --- a/Readme.md +++ b/Readme.md @@ -1149,6 +1149,7 @@ [2366.Minimum-Replacements-to-Sort-the-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2366.Minimum-Replacements-to-Sort-the-Array) (H-) [2371.Minimize-Maximum-Value-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2371.Minimize-Maximum-Value-in-a-Grid) (M+) [2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar) (M+) +[2457.Minimum-Addition-to-Make-Integer-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful) (M) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From d2994af0cb88781bf3ed39628b3eb9d918b79129 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 31 Oct 2022 00:42:30 -0700 Subject: [PATCH 1342/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/Readme.md diff --git a/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/Readme.md b/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/Readme.md new file mode 100644 index 000000000..03ec1ea1a --- /dev/null +++ b/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/Readme.md @@ -0,0 +1,5 @@ +### 2457.Minimum-Addition-to-Make-Integer-Beautiful + +很明显,想要以最小的代价来降低digit sum,必然是从低位往高位,逐个加上一个“互补”的数字,使得将该位“清零”。即原数的某位上是2的话,你必然补上8,使得digit sum能够降低2. + +这里特别需要注意的是进位。例如原数是232,你补上一个8之后,你下一个考虑的十位数其实是4而不是3. From ad0e85c854cfbe3d161271059b0c1947c9517e48 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 31 Oct 2022 00:46:59 -0700 Subject: [PATCH 1343/2729] Update 2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp --- ...2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp b/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp index aa4ed56b2..9479e7ffb 100644 --- a/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp +++ b/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful/2457.Minimum-Addition-to-Make-Integer-Beautiful.cpp @@ -1,6 +1,6 @@ class Solution { public: - int getSum(long long x) + int DigitSum(long long x) { int sum = 0; while (x>0) @@ -13,13 +13,11 @@ class Solution { long long makeIntegerBeautiful(long long n, int target) { - int len = to_string(n).size(); - string ret; - + string ret; int carry = 0; - for (int i=0; i 0) { - if (getSum(n) <= target) break; + if (DigitSum(n) <= target) break; int cur = n%10; int d; From aeb821429b40295686ff0f1053f555cb36af15d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 31 Oct 2022 01:19:31 -0700 Subject: [PATCH 1344/2729] Create 462.Minimum-Moves-to-Equal-Array-Elements-II.cpp --- .../462.Minimum-Moves-to-Equal-Array-Elements-II.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Math/462.Minimum-Moves-to-Equal-Array-Elements-II/462.Minimum-Moves-to-Equal-Array-Elements-II.cpp diff --git a/Math/462.Minimum-Moves-to-Equal-Array-Elements-II/462.Minimum-Moves-to-Equal-Array-Elements-II.cpp b/Math/462.Minimum-Moves-to-Equal-Array-Elements-II/462.Minimum-Moves-to-Equal-Array-Elements-II.cpp new file mode 100644 index 000000000..9da968a42 --- /dev/null +++ b/Math/462.Minimum-Moves-to-Equal-Array-Elements-II/462.Minimum-Moves-to-Equal-Array-Elements-II.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minMoves2(vector& nums) + { + sort(nums.begin(),nums.end()); + int median=nums[nums.size()/2]; + int result=0; + for (int i=0; i Date: Mon, 31 Oct 2022 01:27:51 -0700 Subject: [PATCH 1345/2729] Create Readme.md --- Math/462.Minimum-Moves-to-Equal-Array-Elements-II/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Math/462.Minimum-Moves-to-Equal-Array-Elements-II/Readme.md diff --git a/Math/462.Minimum-Moves-to-Equal-Array-Elements-II/Readme.md b/Math/462.Minimum-Moves-to-Equal-Array-Elements-II/Readme.md new file mode 100644 index 000000000..cc61fedc5 --- /dev/null +++ b/Math/462.Minimum-Moves-to-Equal-Array-Elements-II/Readme.md @@ -0,0 +1,3 @@ +### 462.Minimum-Moves-to-Equal-Array-Elements-II + +本题的本质就是`296.Best-Meeting-Point`。满足`minimize Sum{|xi-p|}`的最优点p就是{xi}的中位数。 From 59ca21af0a7e07b58e138171ef764a10d451ab9f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 31 Oct 2022 01:29:15 -0700 Subject: [PATCH 1346/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b943280c6..6a97bae6c 100644 --- a/Readme.md +++ b/Readme.md @@ -1030,7 +1030,7 @@ [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` [296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) -462.Minimum-Moves-to-Equal-Array-Elements-II +[462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) From 9b18d12162c4fd1dad5c92bb7a91f677bbdcf28a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 2 Nov 2022 23:31:38 -0700 Subject: [PATCH 1347/2729] Create 2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries.cpp --- ...ary-Tree-After-Subtree-Removal-Queries.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries.cpp diff --git a/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries.cpp b/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries.cpp new file mode 100644 index 000000000..08ee36acc --- /dev/null +++ b/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries.cpp @@ -0,0 +1,48 @@ +/** + * 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 { + unordered_map>d2h; + int depth[100005]; + int height[100005]; +public: + vector treeQueries(TreeNode* root, vector& queries) + { + dfs_height(root, 0); + for (auto& [d, hs] : d2h) + sort(hs.rbegin(), hs.rend()); + + vectorrets; + for (int node: queries) + { + int d = depth[node]; + int h = height[node]; + if (d2h[d].size()==1) + rets.push_back(d - 1); + else if (d2h[d][0] == h) + rets.push_back(d2h[d][1] + d); + else + rets.push_back(d2h[d][0] + d); + } + return rets; + + } + + int dfs_height(TreeNode* node, int d) + { + if (node==NULL) return -1; + int h = max(dfs_height(node->left, d+1), dfs_height(node->right, d+1)) + 1; + d2h[d].push_back(h); + depth[node->val] = d; + height[node->val] = h; + return h; + } +}; From f537ec51fcd3575a3e434bd0d7a9aa46235f53e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 2 Nov 2022 23:32:25 -0700 Subject: [PATCH 1348/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6a97bae6c..712df090b 100644 --- a/Readme.md +++ b/Readme.md @@ -237,6 +237,7 @@ [2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H-) [2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) [2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) +[2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) From 044c016dfa5cfc4636caaf2f5c91cab3419fccc2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 2 Nov 2022 23:56:04 -0700 Subject: [PATCH 1349/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries/Readme.md diff --git a/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries/Readme.md b/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries/Readme.md new file mode 100644 index 000000000..b0c1525b2 --- /dev/null +++ b/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries/Readme.md @@ -0,0 +1,7 @@ +### 2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries + +我们定义一个节点的height表示从它到叶子节点的最大距离,depth表示从它到root的距离。 + +我们移除node节点对应的子树后,剩下的树的高度其实就取决于与它同depth的节点的height。所以我们将所有处在同depth的节点的height都提前收集好,那么就很容易找到其他子树的最大height。 + +特别注意,如果某个深度的节点只有一个,那么将其移除后,剩下树的最大高度就是该节点的depth-1. From bb8b9f827d1dc5328a7d1d00bd200dfa9674c906 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Nov 2022 23:09:54 -0700 Subject: [PATCH 1350/2729] Update 924.Minimize-Malware-Spread.cpp --- .../924.Minimize-Malware-Spread.cpp | 70 ++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/Union_Find/924.Minimize-Malware-Spread/924.Minimize-Malware-Spread.cpp b/Union_Find/924.Minimize-Malware-Spread/924.Minimize-Malware-Spread.cpp index 8b1378917..238725052 100644 --- a/Union_Find/924.Minimize-Malware-Spread/924.Minimize-Malware-Spread.cpp +++ b/Union_Find/924.Minimize-Malware-Spread/924.Minimize-Malware-Spread.cpp @@ -1 +1,69 @@ - +class Solution { + unordered_mapRoot; +public: + int minMalwareSpread(vector>& graph, vector& initial) + { + int N = graph.size(); + for (int i=0; i>Children; + for (int i=0; iSet(initial.begin(),initial.end()); + + int MaxGroup = 0; + int result; + for (auto a:Children) + { + int count = 0; + int candidate; + for (auto b:a.second) + { + if (Set.find(b)!=Set.end()) + { + count++; + candidate = b; + } + if (count>1) break; + } + if (count==1 && (a.second.size()>MaxGroup || a.second.size()==MaxGroup && candidate Date: Sun, 6 Nov 2022 00:20:34 -0700 Subject: [PATCH 1351/2729] Create 2463.Minimum-Total-Distance-Traveled.cpp --- .../2463.Minimum-Total-Distance-Traveled.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/2463.Minimum-Total-Distance-Traveled.cpp diff --git a/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/2463.Minimum-Total-Distance-Traveled.cpp b/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/2463.Minimum-Total-Distance-Traveled.cpp new file mode 100644 index 000000000..5670539fd --- /dev/null +++ b/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/2463.Minimum-Total-Distance-Traveled.cpp @@ -0,0 +1,44 @@ +using LL = long long; +class Solution { + LL dp[101][101]; + LL dist[101][101][101]; +public: + long long minimumTotalDistance(vector& robot, vector>& factory) + { + int m = robot.size(); + int n = factory.size(); + + sort(robot.begin(), robot.end()); + sort(factory.begin(), factory.end()); + + for (int i=0; i Date: Sun, 6 Nov 2022 00:21:22 -0700 Subject: [PATCH 1352/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 712df090b..00df457b6 100644 --- a/Readme.md +++ b/Readme.md @@ -738,6 +738,7 @@ [1335.Minimum-Difficulty-of-a-Job-Schedule](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1335.Minimum-Difficulty-of-a-Job-Schedule) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) [1977.Number-of-Ways-to-Separate-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1977.Number-of-Ways-to-Separate-Numbers) (H) +[2463.Minimum-Total-Distance-Traveled](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled) (M+) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From 522e772ff2f601fccb1b3c5b14dca08490f4b65d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 01:02:13 -0700 Subject: [PATCH 1353/2729] Create Readme.md --- .../2463.Minimum-Total-Distance-Traveled/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/Readme.md diff --git a/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/Readme.md b/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/Readme.md new file mode 100644 index 000000000..f93903844 --- /dev/null +++ b/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/Readme.md @@ -0,0 +1,13 @@ +### 2463.Minimum-Total-Distance-Traveled + +本题最重要的就是这个结论:所有的机器人排序后所对应的工厂顺序,一定就是工厂的位置顺序。也就是说,任意两个机器人i Date: Sun, 6 Nov 2022 10:23:33 -0800 Subject: [PATCH 1354/2729] Update 1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls.cpp --- ...ving-The-Same-Number-of-Distinct-Balls.cpp | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/Math/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls.cpp b/Math/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls.cpp index b177fd300..aed69116e 100644 --- a/Math/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls.cpp +++ b/Math/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls.cpp @@ -23,19 +23,16 @@ class Solution { return good*1.0/all; } - void dfs(int level, vector&set1, vector&set2) + void dfs(int k, vector&set1, vector&set2) { - if (level == balls.size()) - { - int tot1 = accumulate(set1.begin(), set1.end(), 0); - int tot2 = accumulate(set2.begin(), set2.end(), 0); - if (tot1!=tot2) return; + if (k == balls.size()) + { + if (accumulate(set1.begin(), set1.end(), 0) != accumulate(set2.begin(), set2.end(), 0)) + return; long long p = 1; for (int i=0; i Date: Sun, 6 Nov 2022 10:27:56 -0800 Subject: [PATCH 1355/2729] Update Readme.md --- .../Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Math/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/Readme.md b/Math/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/Readme.md index 7ffb6be2c..3e2df6af6 100644 --- a/Math/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/Readme.md +++ b/Math/1467.Probability-of-a-Two-Boxes-Having-The-Same-Number-of-Distinct-Balls/Readme.md @@ -20,3 +20,5 @@ C(i,j) = C(i-1, j-1) + C(i-1, j) } } ``` + +本题的时间DFS的复杂度是`6^8 = 1679616`,可以接受, From ab3d422cdb554b98206b665bc32c54fd8bee85e2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 16:39:03 -0800 Subject: [PATCH 1356/2729] Update and rename 527.Word Abbreviation.cpp to 527.Word-Abbreviation.cpp --- .../527.Word Abbreviation.cpp | 63 ------------------- .../527.Word-Abbreviation.cpp | 58 +++++++++++++++++ 2 files changed, 58 insertions(+), 63 deletions(-) delete mode 100644 String/527.Word-Abbreviation/527.Word Abbreviation.cpp create mode 100644 String/527.Word-Abbreviation/527.Word-Abbreviation.cpp diff --git a/String/527.Word-Abbreviation/527.Word Abbreviation.cpp b/String/527.Word-Abbreviation/527.Word Abbreviation.cpp deleted file mode 100644 index ec9d4bf25..000000000 --- a/String/527.Word-Abbreviation/527.Word Abbreviation.cpp +++ /dev/null @@ -1,63 +0,0 @@ -class Solution { -public: - vector wordsAbbreviation(vector& dict) - { - unordered_mapIndex; - for (int i=0; i>Map; - vectorresults(dict.size()); - int abbrNum=0; - - unordered_setSet; - for (int i=0; i1) - { - for (int i=0; i wordsAbbreviation(vector& dict) + { + int n = dict.size(); + vectorrets(n); + unordered_setSet; + for (int i=0; i>Map; + for (auto idx : Set) + { + string abbr=getAbbr(dict[idx], abbrNum); + Map[abbr].push_back(idx); + } + Set.clear(); + + for (auto& [str, indices]:Map) + { + if (indices.size()>1) + { + for (int idx: indices) + Set.insert(idx); + } + else + { + rets[indices[0]] = str; + } + } + + if (Set.size()==0) break; + abbrNum++; + } + + return rets; + + } + + string getAbbr(string s, int abbrNum) + { + string t; + if (s.size()<=2) + { + t=s; + return t; + } + + t=s.substr(0, abbrNum); + t+=to_string(s.size()-abbrNum-1); + t+=s.back(); + if (t.size()==s.size()) t=s; + return t; + } +}; From 94f9a00317f397c944bdcb39c68412ed7de4252e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 16:59:11 -0800 Subject: [PATCH 1357/2729] Update 527.Word-Abbreviation.cpp --- .../527.Word-Abbreviation.cpp | 56 +++++++++---------- 1 file changed, 27 insertions(+), 29 deletions(-) diff --git a/String/527.Word-Abbreviation/527.Word-Abbreviation.cpp b/String/527.Word-Abbreviation/527.Word-Abbreviation.cpp index 28ee88ff2..3e4922914 100644 --- a/String/527.Word-Abbreviation/527.Word-Abbreviation.cpp +++ b/String/527.Word-Abbreviation/527.Word-Abbreviation.cpp @@ -1,58 +1,56 @@ class Solution { public: - vector wordsAbbreviation(vector& dict) - { - int n = dict.size(); + vector wordsAbbreviation(vector& words) + { + int n = words.size(); vectorrets(n); - unordered_setSet; + + vectorSet; for (int i=0; i>Map; - for (auto idx : Set) + unordered_map> Map; + + for (int idx: Set) { - string abbr=getAbbr(dict[idx], abbrNum); + string abbr = getAbbr(words[idx], abbrNum); Map[abbr].push_back(idx); } Set.clear(); - for (auto& [str, indices]:Map) + for (auto& [abbr, indices]: Map) { - if (indices.size()>1) + if (indices.size() > 1) { for (int idx: indices) - Set.insert(idx); - } + Set.push_back(idx); + } else - { - rets[indices[0]] = str; - } + rets[indices[0]] = abbr; } - if (Set.size()==0) break; - abbrNum++; + abbrNum += 1; + if (Set.size() == 0) + break; } return rets; - } string getAbbr(string s, int abbrNum) - { + { + if (s.size() < 3) return s; + string t; - if (s.size()<=2) - { - t=s; - return t; - } + t = s.substr(0, abbrNum); + t += to_string(s.size() - abbrNum - 1); + t += s.back(); + + if (t.size() == s.size()) return s; - t=s.substr(0, abbrNum); - t+=to_string(s.size()-abbrNum-1); - t+=s.back(); - if (t.size()==s.size()) t=s; - return t; + return t; } }; From ad229fbcf8fe63d7eab7546c7d1e48e1a9e56601 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 17:02:49 -0800 Subject: [PATCH 1358/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 00df457b6..dfb0414aa 100644 --- a/Readme.md +++ b/Readme.md @@ -863,8 +863,7 @@ [388.Longest-Absolute-File-Path](https://github.com/wisdompeak/LeetCode/tree/master/String/388.Longest-Absolute-File-Path) (M+) [418.Sentence-Screen-Fitting](https://github.com/wisdompeak/LeetCode/tree/master/String/418.Sentence-Screen-Fitting) (M+) [423.Reconstruct-Original-Digits-from-English](https://github.com/wisdompeak/LeetCode/tree/master/Others/423.Reconstruct-Original-Digits-from-English) (H-) -[527.Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/527.Word-Abbreviation) (M+) -[556.Next Greater Element III](https://github.com/wisdompeak/LeetCode/tree/master/String/556.Next-Greater-Element-III) (H-) +[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/String/556.Next-Greater-Element-III) (H-) 616.Add-Bold-Tag-in-String (M) [467.Unique-Substrings-in-Wraparound-String](https://github.com/wisdompeak/LeetCode/tree/master/String/467.Unique-Substrings-in-Wraparound-String) (H-) [564.Find-the-Closest-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/String/564.Find-the-Closest-Palindrome) (H) @@ -878,6 +877,7 @@ * ``Abbreviation`` [408.Valid-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/408.Valid-Word-Abbreviation) (M) [411.Minimum-Unique-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/411.Minimum-Unique-Word-Abbreviation) (H) +[527.Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/527.Word-Abbreviation) (M+) [2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings) (H) * ``Rolling Hash`` [1044.Longest-Duplicate-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/1044.Longest-Duplicate-Substring) (H) From 7a658c053dd257d3257a080a6a98ed305057aa9f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 23:37:47 -0800 Subject: [PATCH 1359/2729] Create 2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K.cpp --- ...um-of-Distinct-Subarrays-With-Length-K.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K.cpp diff --git a/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K.cpp b/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K.cpp new file mode 100644 index 000000000..296089a64 --- /dev/null +++ b/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K.cpp @@ -0,0 +1,31 @@ +using LL = long long; +class Solution { +public: + long long maximumSubarraySum(vector& nums, int k) + { + LL ret = 0; + unordered_mapMap; + int count = 0; + LL sum = 0; + for (int i=0; i=k-1) + { + if (count == k) + ret = max(ret, sum); + + Map[nums[i-k+1]]--; + sum -= nums[i-k+1]; + if (Map[nums[i-k+1]]==0) + count--; + } + } + + return ret; + } +}; From 48c9b62c393a53ba27f63ef5512ddc27ed798443 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 23:38:09 -0800 Subject: [PATCH 1360/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index dfb0414aa..1f5a5b9d1 100644 --- a/Readme.md +++ b/Readme.md @@ -53,6 +53,7 @@ [159.Longest-Substring-with-At-Most-Two-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/159.Longest-Substring-with-At-Most-Two-Distinct-Characters)(H-) [340.Longest-Substring-with-At-Most-K-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/340.Longest-Substring-with-At-Most-K-Distinct-Characters) (H) [992.Subarrays-with-K-Different-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/992.Subarrays-with-K-Different-Integers) (H-) +[2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K) (M) * ``Two pointers for two seuqences`` [986.Interval-List-Intersections](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/986.Interval-List-Intersections) (M) [1229.Meeting-Scheduler](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1229.Meeting-Scheduler) (M+) From 800a37b8d8d0d44defb508cfb1205c17eadf8169 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 23:42:19 -0800 Subject: [PATCH 1361/2729] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K/Readme.md diff --git a/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K/Readme.md b/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K/Readme.md new file mode 100644 index 000000000..01afc5d50 --- /dev/null +++ b/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K/Readme.md @@ -0,0 +1,17 @@ +### 2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K + +非常普通的固定长度的滑窗。 + +用一个HashMap来记录每个number出现的次数。用count来表示滑窗内的distinct number的数量。count的变动依据如下: +1. 当新加入一个数字时 +```cpp +Map[num]++; +if (Map[num]==1) + count++; +``` +2. 当移出一个数字时 +```cpp +Map[num]--; +if (Map[num]==0) + count--; +``` From 3cf1ef819f241fb2dd7891f90d6fe3f8972759ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 23:53:42 -0800 Subject: [PATCH 1362/2729] Create 2361.Minimum-Costs-Using-the-Train-Line.cpp --- ...361.Minimum-Costs-Using-the-Train-Line.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line/2361.Minimum-Costs-Using-the-Train-Line.cpp diff --git a/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line/2361.Minimum-Costs-Using-the-Train-Line.cpp b/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line/2361.Minimum-Costs-Using-the-Train-Line.cpp new file mode 100644 index 000000000..e29f45d2d --- /dev/null +++ b/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line/2361.Minimum-Costs-Using-the-Train-Line.cpp @@ -0,0 +1,26 @@ +using LL = long long; +class Solution { + LL dp[100005][2]; +public: + vector minimumCosts(vector& regular, vector& express, int expressCost) + { + int n = regular.size(); + regular.insert(regular.begin(), 0); + express.insert(express.begin(), 0); + + dp[0][0] = 0; + dp[0][1] = expressCost; + + vectorrets; + + for (int i=1; i<=n; i++) + { + dp[i][0] = min(dp[i-1][0] + regular[i], dp[i-1][1] + regular[i]); + dp[i][1] = min(dp[i-1][1] + express[i], dp[i-1][0] + expressCost + express[i]); + + rets.push_back(min(dp[i][0], dp[i][1])); + } + + return rets; + } +}; From f17627cc150eef7bf9e41b3ff8568a8a86186481 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 23:54:05 -0800 Subject: [PATCH 1363/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1f5a5b9d1..60d79ab60 100644 --- a/Readme.md +++ b/Readme.md @@ -679,6 +679,7 @@ [2036.Maximum-Alternating-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum) (M+) [2143.Choose-Numbers-From-Two-Arrays-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range) (H) [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) +[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From d3bcbc90215edeed8efe5465069e2b2ccaa47f88 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Nov 2022 23:59:27 -0800 Subject: [PATCH 1364/2729] Create Readme.md --- .../2361.Minimum-Costs-Using-the-Train-Line/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line/Readme.md diff --git a/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line/Readme.md b/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line/Readme.md new file mode 100644 index 000000000..de0a1a977 --- /dev/null +++ b/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line/Readme.md @@ -0,0 +1,8 @@ +### 2361.Minimum-Costs-Using-the-Train-Line + +很明显,状态变量dp[i][0]表示到达第i个车站的regular所需要的最小代价,dp[i][1]表示到达第i个车站的express所需要的最小代价。于是有转移方程: +```cpp +dp[i][0] = min(dp[i-1][0] + regular[i], dp[i-1][1] + regular[i]); +dp[i][1] = min(dp[i-1][1] + express[i], dp[i-1][0] + expressCost + express[i]); +``` +注意我们不需要考虑dp[i][0]与dp[i][1]之间的转移。这是因为,我们如果想要从dp[i][0]转移到dp[i][1],其目的一定只是为了后续得到dp[i+1][1]。单独从第i站的角度来看,只要到了regular或express都算达成了任务,两者间的跳转对于第i站而言没有意义。 From a86f29f9d819feee953ac5e65a5391fdc87034e9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Nov 2022 00:16:07 -0800 Subject: [PATCH 1365/2729] Create 2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp --- ...oose-Edges-to-Maximize-Score-in-a-Tree.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Dynamic_Programming/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp diff --git a/Dynamic_Programming/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp b/Dynamic_Programming/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp new file mode 100644 index 000000000..447ca3eff --- /dev/null +++ b/Dynamic_Programming/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp @@ -0,0 +1,52 @@ +using LL = long long; +class Solution { + vector>children[100005]; + LL memo[100005][2]; +public: + long long maxScore(vector>& edges) + { + int n = edges.size(); + int root = -1; + for (int i=0; i Date: Mon, 7 Nov 2022 00:17:08 -0800 Subject: [PATCH 1366/2729] Rename Dynamic_Programming/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp to Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp --- .../2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Dynamic_Programming => Recursion}/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp (100%) diff --git a/Dynamic_Programming/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp b/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp similarity index 100% rename from Dynamic_Programming/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp rename to Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/2378.Choose-Edges-to-Maximize-Score-in-a-Tree.cpp From 9f79e25c98afd4a5fc7ff9ec4f770b69dfc232af Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Nov 2022 00:17:36 -0800 Subject: [PATCH 1367/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 60d79ab60..2e178da5e 100644 --- a/Readme.md +++ b/Readme.md @@ -954,6 +954,7 @@ [133.Clone-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/133.Clone-Graph) (M+) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (H-) [337.House-Robber-III](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/337.House-Robber-III) (M+) +[2378.Choose-Edges-to-Maximize-Score-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree) (H-) [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [397.Integer-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/397.Integer-Replacement) (M+) From b086302fee90371c094114101fc44bba96535dc5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Nov 2022 00:24:59 -0800 Subject: [PATCH 1368/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/Readme.md diff --git a/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/Readme.md b/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/Readme.md new file mode 100644 index 000000000..457b2c703 --- /dev/null +++ b/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree/Readme.md @@ -0,0 +1,11 @@ +### 2378.Choose-Edges-to-Maximize-Score-in-a-Tree + +我们不难发现,如果从parent到node的edge被选中的话,那么node到它所有children的edge都不能选中。如果从parent到node的edge不被选中的话,那么node到它所有children的edge里只能最多选一条。 + +所以我们定义`dfs(node, 1)`表示从parent到node的edge被选中,那么以node为根的子树的最大收益。于是有 +```cpp +dfs(node, 1) = sum{dfs(child, 0)}; +``` +同理,定义`dfs(node, 0)`表示从parent到node的edge不被选中,那么以node为根的子树的最大收益。因为我们允许有一条node的子边被选中,所以需要遍历这个选择。为了便于计算,我们先求出`Sum = sum{dfs(child, 0)}`,那么对于任何一个child,如果它的边被选中的话,则整棵树的最大收益就是`Sum - dfs(child, 0) + dfs(child, 1) + weight`. 我们遍历child,再返回最大的作为`dfs(node,1)`. + +显然,此题需要记忆化来避免重复计算。 From 89ba3efc69342be6053b18e1ec75ee64885a65ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Nov 2022 01:09:59 -0800 Subject: [PATCH 1369/2729] Create 2387.Median-of-a-Row-Wise-Sorted-Matrix.cpp --- ...387.Median-of-a-Row-Wise-Sorted-Matrix.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix/2387.Median-of-a-Row-Wise-Sorted-Matrix.cpp diff --git a/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix/2387.Median-of-a-Row-Wise-Sorted-Matrix.cpp b/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix/2387.Median-of-a-Row-Wise-Sorted-Matrix.cpp new file mode 100644 index 000000000..211ed8d22 --- /dev/null +++ b/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix/2387.Median-of-a-Row-Wise-Sorted-Matrix.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int matrixMedian(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + int k = (m*n+1)/2; + + int left = 0, right = INT_MAX; + while (left < right) + { + int mid = left+(right-left)/2; + int count = 0; + for (int i=0; i Date: Mon, 7 Nov 2022 01:10:41 -0800 Subject: [PATCH 1370/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 2e178da5e..21ae6ac95 100644 --- a/Readme.md +++ b/Readme.md @@ -129,6 +129,7 @@ [793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) [1201.Ugly-Number-III](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1201.Ugly-Number-III) (H-) [1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) +[2387.Median-of-a-Row-Wise-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix) (H-) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From ea974b6a1a59a3d163b8ad6d3c18a86cdfaae3e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Nov 2022 01:12:55 -0800 Subject: [PATCH 1371/2729] Create Readme.md --- .../2387.Median-of-a-Row-Wise-Sorted-Matrix/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix/Readme.md diff --git a/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix/Readme.md b/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix/Readme.md new file mode 100644 index 000000000..4c42ebded --- /dev/null +++ b/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix/Readme.md @@ -0,0 +1,9 @@ +### 2387.Median-of-a-Row-Wise-Sorted-Matrix + +令`k=(m*n+1)/2`,本题就是求矩阵里的从小到大的第k个元素。本质和`215.Kth-Largest-Element-in-an-Array`相同,只不过需要将各行`smallerOrEqual(mid)`的结果累加起来得到count。 +```cpp +if (count < k) + left = mid+1; +else + right = mid; +``` From 8b8a57dcb2c601749a45bd80bea7a70958657a8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 7 Nov 2022 23:45:05 -0800 Subject: [PATCH 1372/2729] Create 2403.Minimum-Time-to-Kill-All-Monsters.cpp --- ...2403.Minimum-Time-to-Kill-All-Monsters.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/2403.Minimum-Time-to-Kill-All-Monsters.cpp diff --git a/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/2403.Minimum-Time-to-Kill-All-Monsters.cpp b/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/2403.Minimum-Time-to-Kill-All-Monsters.cpp new file mode 100644 index 000000000..eb6a77b17 --- /dev/null +++ b/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/2403.Minimum-Time-to-Kill-All-Monsters.cpp @@ -0,0 +1,20 @@ +using LL = long long; +class Solution { +public: + long long minimumTime(vector& power) + { + int n = power.size(); + vectordp(1<>i)&1) + dp[state] = min(dp[state], dp[state- (1< Date: Mon, 7 Nov 2022 23:45:32 -0800 Subject: [PATCH 1373/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 21ae6ac95..740a76c7c 100644 --- a/Readme.md +++ b/Readme.md @@ -791,6 +791,7 @@ [1931.Painting-a-Grid-With-Three-Different-Colors](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1931.Painting-a-Grid-With-Three-Different-Colors) (M+) [1994.The-Number-of-Good-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1994.The-Number-of-Good-Subsets) (H) [2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall) (H-) +[2403.Minimum-Time-to-Kill-All-Monsters](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters) (M+) * ``枚举集合的子集`` [1494.Parallel-Courses-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1494.Parallel-Courses-II) (H) [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) From b0962c8909cee26679b333a969e87ee6cfff0392 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 8 Nov 2022 00:02:16 -0800 Subject: [PATCH 1374/2729] Create Readme.md --- .../Readme.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/Readme.md diff --git a/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/Readme.md b/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/Readme.md new file mode 100644 index 000000000..69a314e57 --- /dev/null +++ b/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/Readme.md @@ -0,0 +1,16 @@ +### 2403.Minimum-Time-to-Kill-All-Monsters + +本题首先需要知道,并不是将monster按照从小到大排序就是最优解。Example 1 就是一个反例。考虑到monster的个数只有17,说明所有的状态数是`2^17=131072`,使用状态压缩dp的复杂度是可以接受的。 + +我们令二进制数state表示哪些怪兽被消灭,dp[state]表示消灭这些怪兽所需要的最少天数,因此有状态转移方程 +```cpp +int k = __builtin_popcount(state); // state所对应的怪兽数目 +for (int i=0; i Date: Tue, 8 Nov 2022 00:03:43 -0800 Subject: [PATCH 1375/2729] Update Readme.md --- .../2403.Minimum-Time-to-Kill-All-Monsters/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/Readme.md b/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/Readme.md index 69a314e57..9f83e4c79 100644 --- a/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/Readme.md +++ b/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters/Readme.md @@ -2,7 +2,7 @@ 本题首先需要知道,并不是将monster按照从小到大排序就是最优解。Example 1 就是一个反例。考虑到monster的个数只有17,说明所有的状态数是`2^17=131072`,使用状态压缩dp的复杂度是可以接受的。 -我们令二进制数state表示哪些怪兽被消灭,dp[state]表示消灭这些怪兽所需要的最少天数,因此有状态转移方程 +我们令二进制数state表示哪些怪兽被消灭,dp[state]表示消灭这些怪兽所需要的最少天数,因此状态转移方程取决于state里面哪一个是最后一只被消灭的怪兽,穷举一下即可: ```cpp int k = __builtin_popcount(state); // state所对应的怪兽数目 for (int i=0; i Date: Fri, 11 Nov 2022 13:47:06 +0530 Subject: [PATCH 1376/2729] Update 1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted.cpp we don't need to check for min( ret, j ) as we have already assigned ret with n-1 . --- ...574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Two_Pointers/1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted.cpp b/Two_Pointers/1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted.cpp index da41641b1..2620b4ab4 100644 --- a/Two_Pointers/1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted.cpp +++ b/Two_Pointers/1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted/1574.Shortest-Subarray-to-be-Removed-to-Make-Array-Sorted.cpp @@ -8,7 +8,7 @@ class Solution { int j = n-1; while (j-1>=0 && arr[j-1]<=arr[j]) j--; - ret = min(ret, j); + ret = j; if (ret==0) return 0; for (int i=0; i Date: Sat, 12 Nov 2022 00:11:17 -0800 Subject: [PATCH 1377/2729] Create 2417.Closest-Fair-Integer.cpp --- .../2417.Closest-Fair-Integer.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Others/2417.Closest-Fair-Integer/2417.Closest-Fair-Integer.cpp diff --git a/Others/2417.Closest-Fair-Integer/2417.Closest-Fair-Integer.cpp b/Others/2417.Closest-Fair-Integer/2417.Closest-Fair-Integer.cpp new file mode 100644 index 000000000..b5732b550 --- /dev/null +++ b/Others/2417.Closest-Fair-Integer/2417.Closest-Fair-Integer.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + int closestFair(int n) + { + int count = 0; + int ret = helper(n, count); + if (ret!=-1) return ret; + + while (n>=0) + { + int ret = helper(n+1, count); + if (ret!=-1) return ret; + + ret = helper(n+2, count); + if (ret!=-1) return ret; + + n = n/10; + count++; + } + return -1; + } + + int helper(int n, int count) + { + int m = n; + int odd = 0, even = 0; + while (m>0) + { + if (m%2==0) + even++; + else + odd++; + m/=10; + } + + int sum = count, diff = odd-even; + if ((sum + diff) % 2 != 0) return -1; + int a = (sum + diff) / 2; // # of 0 + int b = (sum - diff) / 2; // # of 1 + if (a<0 || b<0) return -1; + + for (int i=0; i Date: Sat, 12 Nov 2022 00:11:41 -0800 Subject: [PATCH 1378/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 740a76c7c..dd6494bf0 100644 --- a/Readme.md +++ b/Readme.md @@ -1368,6 +1368,7 @@ [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) +[2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From bffa559e0dcbfe51a72d6b87fc33daf60a0321c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 12 Nov 2022 00:27:12 -0800 Subject: [PATCH 1379/2729] Create Readme.md --- Others/2417.Closest-Fair-Integer/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/2417.Closest-Fair-Integer/Readme.md diff --git a/Others/2417.Closest-Fair-Integer/Readme.md b/Others/2417.Closest-Fair-Integer/Readme.md new file mode 100644 index 000000000..a4322a885 --- /dev/null +++ b/Others/2417.Closest-Fair-Integer/Readme.md @@ -0,0 +1,13 @@ +### 2417.Closest-Fair-Integer + +为了寻找最小的答案,我们尽量保持高位不变。假设“仅”令前k-1位不变,如何构造一个比n稍微大一点的数呢? + +显然将第k位增加1,后面剩余的位数置零(假设有count个),这就是最小的方案了。此时我们基于这个新数num,用一个函数`helper(num,count)`来寻找最接近的答案:如果此时前k位的digit的奇偶个数之差是diff,那么这个diff可以由后面count位来抵消,怎么抵消呢,显然应该从count拿出一部分置为1,一部分置为0,其中将所有的1放在末尾即可。于是,简单的“和差问题”即可求出最后的count位里需要填充多少个0和多少1能够满足条件。注意,也有可能无解。 + +如果无解,我们需要尝试将第k位为增加2,继续调用之前的`helper(num,count)`。 + +如果依然无解,那么不需要再增加第k位的数字了,因为增加3对于前k位的奇偶数字数目不会带来变化,等同于第一种情况。于是我们应该减少k,即“仅”保持前k-2位不变,再重复之前的步骤。 + +最终本题一定有解。 + +注意,我们首先要检查原数n本身是否是符合条件的。 From 97425006270b387e0e750ef25cc27213c45e84e9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 12 Nov 2022 19:46:44 -0800 Subject: [PATCH 1380/2729] Update 084.Largest-Rectangle-in-Histogram_v1.cpp --- .../084.Largest-Rectangle-in-Histogram_v1.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v1.cpp b/Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v1.cpp index 631517722..88a0ba060 100644 --- a/Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v1.cpp +++ b/Stack/084.Largest-Rectangle-in-Histogram/084.Largest-Rectangle-in-Histogram_v1.cpp @@ -17,14 +17,13 @@ class Solution { while (!stk.empty()) stk.pop(); vectorprevSmaller(n, -1); - for (int i=0; i=0; i--) { while (!stk.empty() && heights[stk.top()] > heights[i]) - { + { + prevSmaller[stk.top()] = i; stk.pop(); } - if (!stk.empty()) - prevSmaller[i] = stk.top(); stk.push(i); } From 76802f35e72892e5ca610d3e5e7bbf911513c2e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 12 Nov 2022 22:22:19 -0800 Subject: [PATCH 1381/2729] Create 2468.Split-Message-Based-on-Limit.cpp --- .../2468.Split-Message-Based-on-Limit.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 String/2468.Split-Message-Based-on-Limit/2468.Split-Message-Based-on-Limit.cpp diff --git a/String/2468.Split-Message-Based-on-Limit/2468.Split-Message-Based-on-Limit.cpp b/String/2468.Split-Message-Based-on-Limit/2468.Split-Message-Based-on-Limit.cpp new file mode 100644 index 000000000..071db0910 --- /dev/null +++ b/String/2468.Split-Message-Based-on-Limit/2468.Split-Message-Based-on-Limit.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + vector splitMessage(string message, int limit) + { + for (int len=1; 3+2*len < limit; len++) + { + int num = pow(10,len)-1; + int cost = (3+len) * num; + for (int i=1; i<=len; i++) + cost += i * ((pow(10,i)-1) - (pow(10, i-1)-1)); + + if (limit*num - cost >= (int)message.size()) + return get(message, limit, len); + } + + return {}; + } + + vectorget(string message, int limit, int len) + { + vector rets; + int count = 0; + int part = 0; + while (count < message.size()) + { + part++; + int cost = 3+len+to_string(part).size(); + int k = min((int)message.size() - count, limit-cost); + rets.push_back(message.substr(count, k) + "<" + to_string(part) + "/"); + count += k; + } + + for (string& ret: rets) + ret += to_string(part) + ">"; + + return rets; + } + + +}; From 227e27aaad3762c9264e9c5c2b485234611fd0d0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 09:01:51 -0800 Subject: [PATCH 1382/2729] Create Readme.md --- String/2468.Split-Message-Based-on-Limit/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 String/2468.Split-Message-Based-on-Limit/Readme.md diff --git a/String/2468.Split-Message-Based-on-Limit/Readme.md b/String/2468.Split-Message-Based-on-Limit/Readme.md new file mode 100644 index 000000000..1200909ed --- /dev/null +++ b/String/2468.Split-Message-Based-on-Limit/Readme.md @@ -0,0 +1,7 @@ +### 2468.Split-Message-Based-on-Limit + +此题有很大的迷惑性,二分法试探切割的份数的做法是错误的。并不是份数越多,就越容易满足要求。比如说,分割成99份,一定比分割成98份可以装下更多的字符,因为多了一个字段。但是分割成100份,不见得能比分割成99份装下更多的字符。这是因为前者每个字段的overhead是``,而后者每个字段的overhead是``,前者每个字段反而要少装1个字符,即使多一个字段,也不见得能弥补得过来(特别是当limit比较小的话)。 + +由此可见,本题的关键其实在于确定“份数”里多有少个数字。如果份数是固定的k位数,那么自然是份数越多,就越容易满足要求。所以我们先估算需要多少位数的份数。如果是一位数,那么我们就查看分成9份最多能装多少字符;如果是两位数,那么我们就查看分成99份最多能装多少字符;如果是三位数,那么我们就查看分成999份最多能装多少字符... 当发现最多能装的字符数大于message的长度,那么我们就知道份数的digit number。 + +如果份数的digit number确定下来之后,比如说是三位数,我们就可以暴力构造答案了。虽然我们暂时不知道具体的份数,但可以用xxx代替。即`*****<1/xxx>`,`*****<2/xxx>`,其中`*****`表示可以填充的字符。不停地添加字段,直至恰好把message都填充完,此时我们就可以确定“份数”了。再将具体的“份数”替换原有的`xxx`就是答案。 From 5120440dbf75d9a480e1899f212a4a66cc48e466 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 09:04:06 -0800 Subject: [PATCH 1383/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index dd6494bf0..d0fba82b9 100644 --- a/Readme.md +++ b/Readme.md @@ -878,6 +878,7 @@ [1616.Split-Two-Strings-to-Make-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/String/1616.Split-Two-Strings-to-Make-Palindrome) (M+) [1754.Largest-Merge-Of-Two-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/1754.Largest-Merge-Of-Two-Strings) (M+) [1849.Splitting-a-String-Into-Descending-Consecutive-Values](https://github.com/wisdompeak/LeetCode/tree/master/String/1849.Splitting-a-String-Into-Descending-Consecutive-Values) (M+) +[2468.Split-Message-Based-on-Limit](https://github.com/wisdompeak/LeetCode/tree/master/String/2468.Split-Message-Based-on-Limit) (H-) * ``Abbreviation`` [408.Valid-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/408.Valid-Word-Abbreviation) (M) [411.Minimum-Unique-Word-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/411.Minimum-Unique-Word-Abbreviation) (H) From fc2d1a68644b057bcb3651719aa75f28f6e82609 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 15:38:09 -0800 Subject: [PATCH 1384/2729] Create 2467.Most-Profitable-Path-in-a-Tree.cpp --- .../2467.Most-Profitable-Path-in-a-Tree.cpp | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp diff --git a/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp b/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp new file mode 100644 index 000000000..8c8d0db73 --- /dev/null +++ b/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp @@ -0,0 +1,68 @@ +class Solution { + vector next[100005]; + int b[100005]; + int bob; + int n; + int ret = INT_MIN; + vectoramount; +public: + int mostProfitablePath(vector>& edges, int bob, vector& amount) + { + this->n = amount.size(); + this->bob = bob; + this->amount = amount; + + for (int i=0; i Date: Sun, 13 Nov 2022 15:43:28 -0800 Subject: [PATCH 1385/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d0fba82b9..95a524330 100644 --- a/Readme.md +++ b/Readme.md @@ -240,6 +240,7 @@ [2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) [2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) [2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) +[2467.Most-Profitable-Path-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2467.Most-Profitable-Path-in-a-Tree) (M+) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) From ab295231552fd43533c2408c08390cc56bd308ad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 15:48:54 -0800 Subject: [PATCH 1386/2729] Create Readme.md --- Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md diff --git a/Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md b/Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md new file mode 100644 index 000000000..0675fe188 --- /dev/null +++ b/Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md @@ -0,0 +1,5 @@ +### 2467.Most-Profitable-Path-in-a-Tree + +两次遍历全树。第一次遍历求得每个点到bob所在节点的距离(但只限bob节点往上的部分)。第二次遍历求每个点与root的距离。 + +对于每个节点而言,如果前者大于后者,则对于Alice而言没有收益。如果前者小于后者,则Alice可以拿取该节点的价值。基于这个原则,第二次dfs的时候可以求得收益最大的一条从root到leaf的路径。 From d827130a986d345629c43d335ae899c4e7a016d2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 15:50:17 -0800 Subject: [PATCH 1387/2729] Update Readme.md --- Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md b/Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md index 0675fe188..aef344e50 100644 --- a/Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md +++ b/Tree/2467.Most-Profitable-Path-in-a-Tree/Readme.md @@ -3,3 +3,5 @@ 两次遍历全树。第一次遍历求得每个点到bob所在节点的距离(但只限bob节点往上的部分)。第二次遍历求每个点与root的距离。 对于每个节点而言,如果前者大于后者,则对于Alice而言没有收益。如果前者小于后者,则Alice可以拿取该节点的价值。基于这个原则,第二次dfs的时候可以求得收益最大的一条从root到leaf的路径。 + +通过本题,需要掌握不需要建rooted tree的dfs方法,即`dfs(cur, parent)`。当`next[cur]!=parent`时,可以继续递归`dfs(next[cur], cur)`。 From 950bc19c9e2a050f33d144a3af5029dec36c3c4c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 15:53:33 -0800 Subject: [PATCH 1388/2729] Update 2467.Most-Profitable-Path-in-a-Tree.cpp --- .../2467.Most-Profitable-Path-in-a-Tree.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp b/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp index 8c8d0db73..c77891b83 100644 --- a/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp +++ b/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp @@ -36,15 +36,15 @@ class Solution { return; } - int near = INT_MAX/2; + int toBob = INT_MAX/2; for (int nxt: next[cur]) { if (nxt==parent) continue; dfs(nxt, cur, step+1); - near = min(near, b[nxt]); + toBob = min(toBob, b[nxt]+1); } - b[cur] = min(near+1, INT_MAX/2); + b[cur] = toBob; return; } From 22164d95c6a82921c8b307ba4db0aa1852874245 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 16:36:25 -0800 Subject: [PATCH 1389/2729] Update 2467.Most-Profitable-Path-in-a-Tree.cpp --- .../2467.Most-Profitable-Path-in-a-Tree.cpp | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp b/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp index c77891b83..25e5f7de9 100644 --- a/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp +++ b/Tree/2467.Most-Profitable-Path-in-a-Tree/2467.Most-Profitable-Path-in-a-Tree.cpp @@ -1,18 +1,18 @@ class Solution { - vector next[100005]; int b[100005]; + vectornext[100005]; + int ret = INT_MIN/2; int bob; - int n; - int ret = INT_MIN; vectoramount; public: int mostProfitablePath(vector>& edges, int bob, vector& amount) { - this->n = amount.size(); this->bob = bob; this->amount = amount; - for (int i=0; i Date: Sun, 13 Nov 2022 16:38:58 -0800 Subject: [PATCH 1390/2729] Create 2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp --- ...rations-to-Sort-a-Binary-Tree-by-Level.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp diff --git a/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp b/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp new file mode 100644 index 000000000..3a8b8ca38 --- /dev/null +++ b/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp @@ -0,0 +1,49 @@ +/** + * 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 { + vectorlevel[100005]; + int maxDepth = 0; +public: + int minimumOperations(TreeNode* root) + { + dfs(root, 0); + int count = 0; + for (int t=0; t<=maxDepth; t++) + { + auto sorted = level[t]; + sort(sorted.begin(), sorted.end()); + unordered_maprank; + for (int i=0; ival); + dfs(node->left, depth+1); + dfs(node->right, depth+1); + } +}; From 380b4f0ee3b0b05e5da885df33fafb22daaf6fd9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 16:39:23 -0800 Subject: [PATCH 1391/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 95a524330..509d25d92 100644 --- a/Readme.md +++ b/Readme.md @@ -1223,6 +1223,7 @@ [442.Find-All-Duplicates-in-an-Array](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/442.Find-All-Duplicates-in-an-Array) (M) [448.Find-All-Numbers-Disappeared-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/448.Find-All-Numbers-Disappeared-in-an-Array) (M) [645.Set-Mismatch](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/645.Set-Mismatch) (M) +[2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level) (M+) * ``Parenthesis`` [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) [921.Minimum-Add-to-Make-Parentheses-Valid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/921.Minimum-Add-to-Make-Parentheses-Valid) (M+) From 6deccd4caea74999b1514e9fac1a302c402b6a43 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 16:41:26 -0800 Subject: [PATCH 1392/2729] Update 2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp --- ...mber-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp b/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp index 3a8b8ca38..1708f0a3f 100644 --- a/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp +++ b/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level.cpp @@ -19,18 +19,19 @@ class Solution { int count = 0; for (int t=0; t<=maxDepth; t++) { - auto sorted = level[t]; + auto& nums = level[t]; + auto sorted = nums; sort(sorted.begin(), sorted.end()); unordered_maprank; for (int i=0; i Date: Sun, 13 Nov 2022 16:46:36 -0800 Subject: [PATCH 1393/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/Readme.md diff --git a/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/Readme.md b/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/Readme.md new file mode 100644 index 000000000..62d16b8f3 --- /dev/null +++ b/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level/Readme.md @@ -0,0 +1,7 @@ +### 2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level + +将属于同一个level的数字都收集起来。然后用Indexing sort的方法去贪心地交换。 + +比如说,对于一个乱序的nums数组,我们可以提前知道每个数字的期望位置rank[nums[i]]。我们就从前往后查看每一个位置,如果当前的`rank[nums[i]]!=i`,那么就把nums[i]与位于rank[nums[i]]的数字交换。这样的交换可以持续多次,直至我们在i这个位置上迎来期望的数字。 + +为什么一定能够迎来期望的数字呢?因为每一次交换,我们都把一个数字送到了它应该在的位置。一旦把n-1个数字都放到了它们对应期望的位置,那么i这个位置的数字一定也已经安排到了期望的数字。 From f527c8a57c293758e902043a4894c2320bb5f0f6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 21:33:22 -0800 Subject: [PATCH 1394/2729] Create 2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings.cpp --- ...-Non-overlapping-Palindrome-Substrings.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings.cpp diff --git a/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings.cpp b/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings.cpp new file mode 100644 index 000000000..e35670f24 --- /dev/null +++ b/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings.cpp @@ -0,0 +1,32 @@ +class Solution { + int isPalin[2001][2001]; +public: + int maxPalindromes(string s, int k) + { + int n = s.size(); + for (int i=0; idp(n); + for (int i=k-1; i Date: Sun, 13 Nov 2022 21:33:46 -0800 Subject: [PATCH 1395/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 509d25d92..52e301a2b 100644 --- a/Readme.md +++ b/Readme.md @@ -743,6 +743,7 @@ [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) [1977.Number-of-Ways-to-Separate-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1977.Number-of-Ways-to-Separate-Numbers) (H) [2463.Minimum-Total-Distance-Traveled](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled) (M+) +[2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings) (M+) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From 0d397d4231933d1488f36a02779cb8b3a6fbe4fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Nov 2022 21:46:29 -0800 Subject: [PATCH 1396/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings/Readme.md diff --git a/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings/Readme.md b/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings/Readme.md new file mode 100644 index 000000000..dfb750a22 --- /dev/null +++ b/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings/Readme.md @@ -0,0 +1,5 @@ +### 2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings + +令dp[i]表示s[0:i]里面的the maximum number of palindrome substrings. 显然,转移方程的突破口在于最后一个回文子串。如果最后一个回文子串不包括s[i],那么有`dp[i] = dp[i-1]`,如果最后一个回文子串包括s[i],那么我们就需要找这个回文子串的起始位置j,然后`dp[i] = dp[j-1] + 1`. 这样的j可能有多个,根据数据量,从[0:i]遍历一遍都是可行的。 + +另外,我们需要用o(N^2)的时间提前处理得到一个数组isPalin[i][j],来记录s[i:j]是否是一个回文串。这个技巧已经出现过很多次了。 From 9cc1f8c1e42f4b38e698b4734d2e4990f5042291 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Nov 2022 00:50:04 -0800 Subject: [PATCH 1397/2729] Create 2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome.cpp --- ...ations-to-Turn-Array-Into-a-Palindrome.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome.cpp diff --git a/Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome.cpp b/Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome.cpp new file mode 100644 index 000000000..a2b94b71a --- /dev/null +++ b/Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { +public: + int minimumOperations(vector& nums) + { + int i = 0, j = nums.size()-1; + LL left = nums[i], right = nums[j]; + int count = 0; + + while (i right) + { + j--; + right += nums[j]; + count++; + } + } + return count; + + } +}; From 15cfb93dfc821456bb2602a5a7073647b90287de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Nov 2022 00:50:33 -0800 Subject: [PATCH 1398/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 52e301a2b..81de381d6 100644 --- a/Readme.md +++ b/Readme.md @@ -32,6 +32,7 @@ [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag) (M+) [2354.Number-of-Excellent-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2354.Number-of-Excellent-Pairs) (H-) +[2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome) (H-) * ``Sliding window`` [532.K-diff-Pairs-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/532.K-diff-Pairs-in-an-Array) (H-) [611.Valid-Triangle-Number](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/611.Valid-Triangle-Number) (M+) From 39f226ef399d623cb575d1197cd849d4f422d16d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Nov 2022 01:01:08 -0800 Subject: [PATCH 1399/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome/Readme.md diff --git a/Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome/Readme.md b/Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome/Readme.md new file mode 100644 index 000000000..7ff199e20 --- /dev/null +++ b/Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome/Readme.md @@ -0,0 +1,7 @@ +### 2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome + +我们可以设想,最终得到的回文串的最左边和最右边的元素是怎么得到的?一定是来自nums最左侧的若干个元素之和,与nums最右侧的若干个元素之和。考虑到所有的元素都是正数,我们可以用双指针的方法来得到two equal sum。也就是说,初始令`left=nums[0]`和`right=nums[n-1]`,如果发现`leftright`,必然只能将右指针左移才能试图让left与right相等。于是在得到`left==right`之前,两侧指针移动的总次数就是merge的次数。此时,说明我们找到了最终回文串的最外层的一对。剥离掉这最外层后,我们可以重复上述的过程。 + +此外,我们必须考虑到,有可能在左右指针相遇之前,都无法满足`left==right`。这意味着什么呢?说明只有一个方案,即将整个数组都归并在一起,成为回文串的中心。 + +总结:所以本题就是一个双指针,不停地调整左右指针,试图使得前缀和等于后缀和。如此一轮一轮地确定外层的每一对。如果最终指针相遇,意味着该轮的所有元素必须都归并在一起。 From 73736a1da1c10b2a7875022a4701e2fc14864465 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Nov 2022 22:39:47 -0800 Subject: [PATCH 1400/2729] Create 2431.Maximize-Total-Tastiness-of-Purchased-Fruits.cpp --- ...ze-Total-Tastiness-of-Purchased-Fruits.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits/2431.Maximize-Total-Tastiness-of-Purchased-Fruits.cpp diff --git a/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits/2431.Maximize-Total-Tastiness-of-Purchased-Fruits.cpp b/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits/2431.Maximize-Total-Tastiness-of-Purchased-Fruits.cpp new file mode 100644 index 000000000..89ea96c2f --- /dev/null +++ b/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits/2431.Maximize-Total-Tastiness-of-Purchased-Fruits.cpp @@ -0,0 +1,36 @@ +class Solution { + int dp[1005][1005][6]; +public: + int maxTastiness(vector& price, vector& tastiness, int maxAmount, int maxCoupons) + { + int ret = 0; + dp[0][0][0] = 0; + if (price[0]<=maxAmount) + { + dp[0][price[0]][0] = tastiness[0]; + ret = tastiness[0]; + } + if (price[0]/2<=maxAmount && 1<=maxCoupons) + { + dp[0][price[0]/2][1] = tastiness[0]; + ret = tastiness[0]; + } + + for (int i=1; i=price[i]) + dp[i][j][k] = max(dp[i][j][k], dp[i-1][j-price[i]][k] + tastiness[i]); + if (j>=price[i]/2 && k>=1) + dp[i][j][k] = max(dp[i][j][k], dp[i-1][j-price[i]/2][k-1] + tastiness[i]); + + ret = max(ret, dp[i][j][k]); + } + + return ret; + + + } +}; From f47ea75aa8efe5e3c6b65c9be5c1d76897aca837 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Nov 2022 22:40:31 -0800 Subject: [PATCH 1401/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 81de381d6..94f7c746d 100644 --- a/Readme.md +++ b/Readme.md @@ -653,6 +653,7 @@ [2222.Number-of-Ways-to-Select-Buildings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2222.Number-of-Ways-to-Select-Buildings) (M+) [2312.Selling-Pieces-of-Wood](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2312.Selling-Pieces-of-Wood) (M+) [2338.Count-the-Number-of-Ideal-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays) (H) +[2431.Maximize-Total-Tastiness-of-Purchased-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits) (M+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 7dd85d0b32b92a3327f615135f7f0eb876f787ae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Nov 2022 22:43:35 -0800 Subject: [PATCH 1402/2729] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits/Readme.md diff --git a/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits/Readme.md b/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits/Readme.md new file mode 100644 index 000000000..a84b44348 --- /dev/null +++ b/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits/Readme.md @@ -0,0 +1,10 @@ +### 2431.Maximize-Total-Tastiness-of-Purchased-Fruits + +很常规的DP模式。令dp[i][j][k]表示前i个水果、花费j的钱、使用k张半价券,所能得到的最大tastiness。 + +显然,我们会考虑对第i个水果的决策: +1. 我们不买第i个水果,`dp[i][j][k] = dp[i-1][j][k]`; +2. 我们原价买第i个水果,`dp[i][j][k] = dp[i-1][j-price[i]][k] + tastiness[i]`; +3. 我们半价买第i个水果,`dp[i][j][k] = dp[i-1][j-price[i]/2][k-1] + tastiness[i]`; + +注意为了不出现越界,我们使用上述的转移方程时,需要对j和k加上约束。此外`i=0`时单独处理dp最为方便。 From b0d7d62e238fe26e2ce5e43a84d1ac69189c4467 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Nov 2022 22:56:46 -0800 Subject: [PATCH 1403/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 94f7c746d..81d7523be 100644 --- a/Readme.md +++ b/Readme.md @@ -29,7 +29,6 @@ [1580.Put-Boxes-Into-the-Warehouse-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1580.Put-Boxes-Into-the-Warehouse-II) (H-) [1687.Delivering-Boxes-from-Storage-to-Ports](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1687.Delivering-Boxes-from-Storage-to-Ports) (H) [1793.Maximum-Score-of-a-Good-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1793.Maximum-Score-of-a-Good-Subarray) (M+) -[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1989.Maximum-Number-of-People-That-Can-Be-Caught-in-Tag) (M+) [2354.Number-of-Excellent-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2354.Number-of-Excellent-Pairs) (H-) [2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2422.Merge-Operations-to-Turn-Array-Into-a-Palindrome) (H-) @@ -1139,6 +1138,7 @@ [1727.Largest-Submatrix-With-Rearrangements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1727.Largest-Submatrix-With-Rearrangements) (M) [1744.Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1744.Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day) (M) [1788.Maximize-the-Beauty-of-the-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1788.Maximize-the-Beauty-of-the-Garden) (M+) +[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [1818.Minimum-Absolute-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1818.Minimum-Absolute-Sum-Difference) (M+) [1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number) (M+) [1911.Maximum-Alternating-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1911.Maximum-Alternating-Subsequence-Sum) (M+) From 94ab4692e5ac5a0d2252c0ec4e09405c35574a8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Nov 2022 19:46:43 -0800 Subject: [PATCH 1404/2729] Update 467.Unique-Substrings-in-Wraparound-String.cpp --- ....Unique-Substrings-in-Wraparound-String.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/String/467.Unique-Substrings-in-Wraparound-String/467.Unique-Substrings-in-Wraparound-String.cpp b/String/467.Unique-Substrings-in-Wraparound-String/467.Unique-Substrings-in-Wraparound-String.cpp index 39442862e..301212539 100644 --- a/String/467.Unique-Substrings-in-Wraparound-String/467.Unique-Substrings-in-Wraparound-String.cpp +++ b/String/467.Unique-Substrings-in-Wraparound-String/467.Unique-Substrings-in-Wraparound-String.cpp @@ -3,18 +3,20 @@ class Solution { int findSubstringInWraproundString(string p) { unordered_mapMap; + for (int i=0; iMap[p[i]]) - Map[p[i]]=j-i+1; + int i0=i; + while (i+1 Date: Thu, 24 Nov 2022 10:45:44 -0800 Subject: [PATCH 1405/2729] Update 940.Distinct-Subsequences-II.cpp --- .../940.Distinct-Subsequences-II.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp index 4fb44ec31..3d84a16a2 100644 --- a/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp +++ b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp @@ -17,6 +17,6 @@ class Solution { last[s[i]-'a'] = i; } - return dp[n] - 1; + return ((dp[n] + M )- 1) % M; } }; From e1a4fc23d504c61d0b621e4b8ae00ab3e8fb786b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 11:01:29 -0800 Subject: [PATCH 1406/2729] Create 2478.Number-of-Beautiful-Partitions_v1.cpp --- ...2478.Number-of-Beautiful-Partitions_v1.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Dynamic_Programming/2478.Number-of-Beautiful-Partitions/2478.Number-of-Beautiful-Partitions_v1.cpp diff --git a/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/2478.Number-of-Beautiful-Partitions_v1.cpp b/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/2478.Number-of-Beautiful-Partitions_v1.cpp new file mode 100644 index 000000000..ce8500f5f --- /dev/null +++ b/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/2478.Number-of-Beautiful-Partitions_v1.cpp @@ -0,0 +1,33 @@ +using LL = long long; +class Solution { + LL dp[1005][1005]; + LL M = 1e9+7; +public: + int beautifulPartitions(string s, int K, int minLength) + { + int n = s.size(); + s = "#"+s; + + dp[0][0] = 1; + for (int i=1; i<=n; i++) + for (int j=1; j<=K; j++) + { + if (isprime(s[i])) { + continue; + } + for (int k=j; (k+minLength-1)<=i; k++) + { + if (isprime(s[k])) + dp[i][j] = (dp[i][j] + dp[k-1][j-1]) % M; + } + } + return dp[n][K]; + } + + bool isprime(char ch) + { + return ch == '2' || ch == '3' || ch == '5' || ch == '7'; + } + + +}; From 14418f226305e2479dc4882fb9bec882bc2e4a43 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 11:10:11 -0800 Subject: [PATCH 1407/2729] Create 2478.Number-of-Beautiful-Partitions_v2.cpp --- ...2478.Number-of-Beautiful-Partitions_v2.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Dynamic_Programming/2478.Number-of-Beautiful-Partitions/2478.Number-of-Beautiful-Partitions_v2.cpp diff --git a/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/2478.Number-of-Beautiful-Partitions_v2.cpp b/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/2478.Number-of-Beautiful-Partitions_v2.cpp new file mode 100644 index 000000000..a79fc29ae --- /dev/null +++ b/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/2478.Number-of-Beautiful-Partitions_v2.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { + LL dp[1005][1005]; + LL M = 1e9+7; +public: + int beautifulPartitions(string s, int K, int minLength) + { + int n = s.size(); + s = "#"+s; + + dp[0][0] = 1; + for (int j=1; j<=K; j++) + { + LL sum = 0; + for (int i=1; i<=n; i++) + { + if (i-minLength>=0 && !isprime(s[i-minLength]) && isprime(s[i-minLength+1])) + { + sum += dp[i-minLength][j-1]; + sum %= M; + } + if (!isprime(s[i])) { + dp[i][j] = sum; + } + } + } + return dp[n][K]; + } + + bool isprime(char ch) + { + return ch == '2' || ch == '3' || ch == '5' || ch == '7'; + } +}; From dfb7f68a492c00d3b30bedbb60f9f011f58995b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 11:10:44 -0800 Subject: [PATCH 1408/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 81d7523be..62e8d531d 100644 --- a/Readme.md +++ b/Readme.md @@ -700,6 +700,7 @@ [2188.Minimum-Time-to-Finish-the-Race](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race) (H-) [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) [2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) +[2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) From 1aa8bf9661ec4b3ce7fc5cea7c8324ef9c631106 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 11:24:23 -0800 Subject: [PATCH 1409/2729] Create Readme.md --- .../Readme.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Dynamic_Programming/2478.Number-of-Beautiful-Partitions/Readme.md diff --git a/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/Readme.md b/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/Readme.md new file mode 100644 index 000000000..5a3ff75cb --- /dev/null +++ b/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/Readme.md @@ -0,0 +1,41 @@ +### 2478.Number-of-Beautiful-Partitions + +本题很容易想到常规的N^3的动态规划。令dp[i][j]表示前i个元素(1-index)分成j份的最优方案(即最多的切分数)。显然,我们关注的就是最后一个subarray的位置。如果i是合数,那么我们可以遍历所有i之前的位置k,如果满足`isprime(k)`, `!isprime(k+1)`,`i-k>=minLength`,那么就意味着我们可以在k后面切一刀,[k+1,i]作为最后一段。于是就有`dp[i][j] += dp[k][j-1]`。 + +代码如下: +```cpp +for (int i=1; i<=n; i++) + for (int j=1; j<=K; j++) + { + if (isprime(s[i])) { + continue; + } + for (int k=j; (k+minLength-1)<=i; k++) + { + if (isprime(s[k])) + dp[i][j] += dp[k-1][j-1]; + } + } +``` + +那么如何改进时间复杂度呢?我们观察这个状态转移方程,发现无论i是多少,dp[i][j]只与`sum{dp[k][j-1]}`有关,其中k是比i小的数。所以我们可以把j放在第一个循环(前两个循环互换没有任何影响),然后随着i的遍历,我们可同时累加与更新`sum{dp[k][j-1]}`得到一段适当的前缀和,这样直接就有`dp[i][j] = presum`即可。 + +于是改动后的代码 +``` +for (int j=1; j<=K; j++) +{ + LL sum = 0; + for (int i=1; i<=n; i++) + { + if (i-minLength>=0 && !isprime(s[i-minLength]) && isprime(s[i-minLength+1])) + { + sum += dp[i-minLength][j-1]; + sum %= M; + } + if (!isprime(s[i])) { + dp[i][j] = sum; + } + } +} +``` +最后答案是dp[n][K]。 From c78ba270d15cbb82405f216ac79f002ba595b6b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 11:24:37 -0800 Subject: [PATCH 1410/2729] Update Readme.md --- .../2478.Number-of-Beautiful-Partitions/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/Readme.md b/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/Readme.md index 5a3ff75cb..8aff030ae 100644 --- a/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/Readme.md +++ b/Dynamic_Programming/2478.Number-of-Beautiful-Partitions/Readme.md @@ -21,7 +21,7 @@ for (int i=1; i<=n; i++) 那么如何改进时间复杂度呢?我们观察这个状态转移方程,发现无论i是多少,dp[i][j]只与`sum{dp[k][j-1]}`有关,其中k是比i小的数。所以我们可以把j放在第一个循环(前两个循环互换没有任何影响),然后随着i的遍历,我们可同时累加与更新`sum{dp[k][j-1]}`得到一段适当的前缀和,这样直接就有`dp[i][j] = presum`即可。 于是改动后的代码 -``` +```cpp for (int j=1; j<=K; j++) { LL sum = 0; From 2a6e8a2f89ac55b59a84d91bccaefbc50d180e7b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 12:04:11 -0800 Subject: [PATCH 1411/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 62e8d531d..5bd1795e9 100644 --- a/Readme.md +++ b/Readme.md @@ -700,7 +700,6 @@ [2188.Minimum-Time-to-Finish-the-Race](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race) (H-) [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) [2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) -[2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) @@ -746,6 +745,7 @@ [1977.Number-of-Ways-to-Separate-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1977.Number-of-Ways-to-Separate-Numbers) (H) [2463.Minimum-Total-Distance-Traveled](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled) (M+) [2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings) (M+) +[2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From 140de22e6edbab41d1ffe4c9bfa53880f9654f3d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 17:31:04 -0800 Subject: [PATCH 1412/2729] Update range_sum.cpp --- Template/SegmentTree/range_sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_sum.cpp b/Template/SegmentTree/range_sum.cpp index 468288302..9305a1af1 100644 --- a/Template/SegmentTree/range_sum.cpp +++ b/Template/SegmentTree/range_sum.cpp @@ -97,6 +97,6 @@ int main() for (auto& query: queries) { int start = query[0], end = query[1]; - ret[i] = root->updateRange(start, end); // get the range sum over [start, end] + ret[i] = root->queryRange(start, end); // get the range sum over [start, end] } } From 22ece0ca261a6f033ab8dec685497816aea6556d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 17:35:55 -0800 Subject: [PATCH 1413/2729] Update range_sum.cpp --- Template/SegmentTree/range_sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_sum.cpp b/Template/SegmentTree/range_sum.cpp index 9305a1af1..c52051e69 100644 --- a/Template/SegmentTree/range_sum.cpp +++ b/Template/SegmentTree/range_sum.cpp @@ -86,7 +86,7 @@ class SegTreeNode int main() { - SegTreeNode* root = new SegTreeNode(0, length-1); + SegTreeNode* root = new SegTreeNode(0, length-1, 0); for (auto& update: updates) { From 85eacaa7224ab523f04d791b75e49ba19aa1b6e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 24 Nov 2022 21:13:29 -0800 Subject: [PATCH 1414/2729] Update 940.Distinct-Subsequences-II.cpp --- .../940.Distinct-Subsequences-II.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp index 3d84a16a2..61f80bdd4 100644 --- a/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp +++ b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp @@ -17,6 +17,6 @@ class Solution { last[s[i]-'a'] = i; } - return ((dp[n] + M )- 1) % M; + return (dp[n] -1 +M) % M; } }; From 4f98ff86ad25bf7366c9d68a2746d6ea34103e84 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 26 Nov 2022 12:22:50 -0800 Subject: [PATCH 1415/2729] Create 2484.Count-Palindromic-Subsequences.cpp --- .../2484.Count-Palindromic-Subsequences.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Dynamic_Programming/2484.Count-Palindromic-Subsequences/2484.Count-Palindromic-Subsequences.cpp diff --git a/Dynamic_Programming/2484.Count-Palindromic-Subsequences/2484.Count-Palindromic-Subsequences.cpp b/Dynamic_Programming/2484.Count-Palindromic-Subsequences/2484.Count-Palindromic-Subsequences.cpp new file mode 100644 index 000000000..0ed7d6b39 --- /dev/null +++ b/Dynamic_Programming/2484.Count-Palindromic-Subsequences/2484.Count-Palindromic-Subsequences.cpp @@ -0,0 +1,62 @@ +using LL = long long; +class Solution { + LL dp1[10005][10][10]; + LL dp2[10005][10][10]; + LL count1[10005][10]; + LL count2[10005][10]; + LL M = 1e9+7; +public: + int countPalindromes(string s) + { + int n = s.size(); + s = "#"+s; + + for (int j=0; j<=9; j++) + { + int sum = 0; + for (int i=1; i<=n; i++) + { + sum += (s[i]-'0'==j); + count1[i][j] = sum; + } + } + + for (int j=0; j<=9; j++) + { + int sum = 0; + for (int i=n; i>=1; i--) + { + sum += (s[i]-'0'==j); + count2[i][j] = sum; + } + } + + for (int i=2; i<=n; i++) + for (int j=0; j<=9; j++) + for (int k=0; k<=9; k++) + { + dp1[i][j][k] = dp1[i-1][j][k]; + if (s[i]=='0'+k) + dp1[i][j][k] = (dp1[i][j][k] + count1[i-1][j]) % M; + } + + for (int i=n-1; i>=1; i--) + for (int j=0; j<=9; j++) + for (int k=0; k<=9; k++) + { + dp2[i][j][k] = dp2[i+1][j][k]; + if (s[i]=='0'+k) + dp2[i][j][k] = (dp2[i][j][k] + count2[i+1][j]) % M; + } + + LL ret = 0; + for (int i=3; i<=n-2; i++) + for (int j=0; j<=9; j++) + for (int k=0; k<=9; k++) + { + ret += dp1[i-1][j][k] * dp2[i+1][j][k] % M; + ret %= M; + } + return ret; + } +}; From 2adc05b6bc421b085b1f02a382c63f0430e11f83 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 26 Nov 2022 12:23:47 -0800 Subject: [PATCH 1416/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5bd1795e9..b6cae87fe 100644 --- a/Readme.md +++ b/Readme.md @@ -3,7 +3,7 @@ #### My LeetCode Daily Problem & Contest Group: [See rules and score board here](https://wisdompeak.github.io/lc-score-board/) (If you are interested in joining this group, ping me guan.huifeng@gmail.com) -### LeetCode难题代码和算法要点分析 +### LeetCode难题代码和算法要点分析https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences #### 目前分类目录 #### [Two Pointers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers) [011.Container-With-Most-Water](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/011.Container-With-Most-Water) (M+) @@ -653,6 +653,7 @@ [2312.Selling-Pieces-of-Wood](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2312.Selling-Pieces-of-Wood) (M+) [2338.Count-the-Number-of-Ideal-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays) (H) [2431.Maximize-Total-Tastiness-of-Purchased-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits) (M+) +[2484.Count-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From f538906acb1aeb7b2a842f003912eb7b2094e22e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 26 Nov 2022 12:31:42 -0800 Subject: [PATCH 1417/2729] Create Readme.md --- .../2484.Count-Palindromic-Subsequences/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2484.Count-Palindromic-Subsequences/Readme.md diff --git a/Dynamic_Programming/2484.Count-Palindromic-Subsequences/Readme.md b/Dynamic_Programming/2484.Count-Palindromic-Subsequences/Readme.md new file mode 100644 index 000000000..11d483d9b --- /dev/null +++ b/Dynamic_Programming/2484.Count-Palindromic-Subsequences/Readme.md @@ -0,0 +1,7 @@ +### 2484.Count-Palindromic-Subsequences + +长度为5的回文串,意味着我们对中间的字符没有任何要求。剩下的镜像部分,本质只是两个字符的组合。考虑到本题的元素只是数字,只有0-9共10种可能,所以组合的方式只有100种。结合字符串的长度是1e4,基本可以判定时间复杂度就是10^6,状态变量定义为`dp1[i][j][k]`表示前i个元素的子串里,以j和k结尾的subsequence有多少。同理定义为`dp2[i][j][k]`表示后i个元素逆序来看的子串里,以j和k结尾的subsequence有多少。这样我们枚举长度为5的回文串的中间字符位置i,则有`ret+=dp[i-1][j][k]*dp[i+1][j][k]`. + +接下来考虑`dp1[i][j][k]`如何求解。依然从第i个元素下手。如果第i个元素没有贡献任何“以j,k结尾的新子串”,则有`dp1[i][j][k] += dp[i-1][j][k]`。如果第i个元素恰好是k,那么s[i]本身就可能贡献一个“以j,k结尾的新子串”,这个子串的数目取决于i之前出现了多少个j。所以我们还需要预处理得到一个`count1[i-1][j]`表示前i-1个元素里面有多少个j。因此就有`dp1[i][j][k] += count1[i-1][j]`. + +同理我们可以逆序处理得到count2和dp2. From 63e8c9df96d4bc1ea0385dd3acd61faefcc9ab71 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 26 Nov 2022 13:12:24 -0800 Subject: [PATCH 1418/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b6cae87fe..caf14348b 100644 --- a/Readme.md +++ b/Readme.md @@ -3,7 +3,7 @@ #### My LeetCode Daily Problem & Contest Group: [See rules and score board here](https://wisdompeak.github.io/lc-score-board/) (If you are interested in joining this group, ping me guan.huifeng@gmail.com) -### LeetCode难题代码和算法要点分析https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences +### LeetCode难题代码和算法要点分析 #### 目前分类目录 #### [Two Pointers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers) [011.Container-With-Most-Water](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/011.Container-With-Most-Water) (M+) From 6ca71f1c58cb2f694ec19451624a8c5057584398 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Nov 2022 00:55:33 -0800 Subject: [PATCH 1419/2729] Create 2488.Count-Subarrays-With-Median-K.cpp --- .../2488.Count-Subarrays-With-Median-K.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Hash/2488.Count-Subarrays-With-Median-K/2488.Count-Subarrays-With-Median-K.cpp diff --git a/Hash/2488.Count-Subarrays-With-Median-K/2488.Count-Subarrays-With-Median-K.cpp b/Hash/2488.Count-Subarrays-With-Median-K/2488.Count-Subarrays-With-Median-K.cpp new file mode 100644 index 000000000..6526b4f87 --- /dev/null +++ b/Hash/2488.Count-Subarrays-With-Median-K/2488.Count-Subarrays-With-Median-K.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int countSubarrays(vector& nums, int k) + { + for (auto& x: nums) + { + if (x>k) x=1; + else if (x==k) x=0; + else x=-1; + } + + unordered_mapoddSum; + unordered_mapevenSum; + + evenSum[0] = 1; + + int sum = 0; + int ret = 0; + for (int i=0; i Date: Sun, 27 Nov 2022 00:56:16 -0800 Subject: [PATCH 1420/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index caf14348b..d8889ef62 100644 --- a/Readme.md +++ b/Readme.md @@ -169,6 +169,7 @@ [1915.Number-of-Wonderful-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1915.Number-of-Wonderful-Substrings) (M+) [1983.Widest-Pair-of-Indices-With-Equal-Range-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum) (M+) [2025.Maximum-Number-of-Ways-to-Partition-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array) (H) +[2488.Count-Subarrays-With-Median-K](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2488.Count-Subarrays-With-Median-K) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From ebe6968fee2e6f938715c8204cb8c37f7eac42c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Nov 2022 01:47:00 -0800 Subject: [PATCH 1421/2729] Create Readme.md --- Hash/2488.Count-Subarrays-With-Median-K/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Hash/2488.Count-Subarrays-With-Median-K/Readme.md diff --git a/Hash/2488.Count-Subarrays-With-Median-K/Readme.md b/Hash/2488.Count-Subarrays-With-Median-K/Readme.md new file mode 100644 index 000000000..bd930dacf --- /dev/null +++ b/Hash/2488.Count-Subarrays-With-Median-K/Readme.md @@ -0,0 +1,11 @@ +### 2488.Count-Subarrays-With-Median-K + +考虑以k为median的subarray定义,就是在比k大的元素和比k小的元素一样多。这就说明我们其实并不关心nums的具体数值,所以一个常见的技巧是将原数组转化为-1,0,1三种元素,分别代表小于、等于和大于k的分布。 + +对于以k为median的subarray,我们容易发现,如果该subarray长度是奇数,那么其中的元素之和必然是0. 如果该subarray长度是偶数,那么其中的元素之和必然是1. 所以我们其实就是寻找有多少个元素和是0、长度为奇数的subarray(记做A),以及多少个元素和是1、长度为偶数的subarray(记做B)。 + +对于这类subarray sum的题目,使用前缀和是必然的套路。假设截止到i的前缀和是sum,且该前缀的长度是偶数,那么我们只需要找出:有多少前缀和是sum、长度为奇数的前缀,两个前缀之差就代表了A;有多少前缀和是sum-1、长度为偶数的前缀,两个前缀之差就代表了B。 + +同理,假设截止到i的前缀和是sum,且该前缀的长度是奇数,那么我们只需要找出:有多少前缀和是sum-1、长度为奇数的前缀,两个前缀之差就代表了B;有多少前缀和是sum、长度为偶数的前缀,两个前缀之差就代表了A。 + +所以我们需要维护两个Hash表。evenSum[s]表示前缀和是s、且长度是偶数的前缀有多少个;oddSum[s]表示前缀和是s、且长度是奇数的前缀有多少个。我们遍历每个元素i,根据上面的方法计算有多少个以i为结尾的、符合条件的subarray(A类型或B类型),然后再更新oddSum或者evenSum,一路走下去。 From 1ba7cb746ece59701469de961c8b40aaf2472517 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Dec 2022 13:35:16 -0800 Subject: [PATCH 1422/2729] Update Readme.md --- Hash/2488.Count-Subarrays-With-Median-K/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Hash/2488.Count-Subarrays-With-Median-K/Readme.md b/Hash/2488.Count-Subarrays-With-Median-K/Readme.md index bd930dacf..32931faa2 100644 --- a/Hash/2488.Count-Subarrays-With-Median-K/Readme.md +++ b/Hash/2488.Count-Subarrays-With-Median-K/Readme.md @@ -9,3 +9,5 @@ 同理,假设截止到i的前缀和是sum,且该前缀的长度是奇数,那么我们只需要找出:有多少前缀和是sum-1、长度为奇数的前缀,两个前缀之差就代表了B;有多少前缀和是sum、长度为偶数的前缀,两个前缀之差就代表了A。 所以我们需要维护两个Hash表。evenSum[s]表示前缀和是s、且长度是偶数的前缀有多少个;oddSum[s]表示前缀和是s、且长度是奇数的前缀有多少个。我们遍历每个元素i,根据上面的方法计算有多少个以i为结尾的、符合条件的subarray(A类型或B类型),然后再更新oddSum或者evenSum,一路走下去。 + +PS:这个思路类似于LC 525. From 3aaf9ddae093e726851c63628a469fecb76188c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Dec 2022 13:57:28 -0800 Subject: [PATCH 1423/2729] Update Readme.md --- Two_Pointers/076.Minimum-Window-Substring/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/076.Minimum-Window-Substring/Readme.md b/Two_Pointers/076.Minimum-Window-Substring/Readme.md index 9b9ae4856..d275b2a41 100644 --- a/Two_Pointers/076.Minimum-Window-Substring/Readme.md +++ b/Two_Pointers/076.Minimum-Window-Substring/Readme.md @@ -4,9 +4,9 @@ 对于每个新加入的元素s[j],首先更新该字符出现次数的Map[s[i]]++。如果更新后,Map[s[i]]等于需要出现的次数Table[s[i]],则计数器count++,说明有一个字符满足了出现次数的要求. -当count等于t中的字符类型数COUNT时,说明任务已经实现。此时,让左指针不断右移,相应的Map[s[i]]就要自减,一旦Map[s[i] < Table[s[i]],则count需要自减1从而不再满足COUNT,说明需要继续加入新元素才能满足任务. 从而j才可以右移继续遍历。 +当count等于t中的字符类型数COUNT时,说明任务已经实现。此时,让左指针不断右移,相应的Map[s[i]]就要自减,一旦Map[s[i]] < Table[s[i]],则count需要自减1从而不再满足COUNT,说明需要继续加入新元素才能满足任务. 从而j才可以右移继续遍历。 在这个过程中如果满足条件count==COUNT,都需要不断更新和记录结果。 -[Leetcode Link](https://leetcode.com/problems/minimum-window-substring) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/minimum-window-substring) From 4bf4b4737aa755b3d020a0a35187b6f3fe49ea89 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Dec 2022 13:57:41 -0800 Subject: [PATCH 1424/2729] Update Readme.md --- Two_Pointers/076.Minimum-Window-Substring/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Two_Pointers/076.Minimum-Window-Substring/Readme.md b/Two_Pointers/076.Minimum-Window-Substring/Readme.md index d275b2a41..f358ed641 100644 --- a/Two_Pointers/076.Minimum-Window-Substring/Readme.md +++ b/Two_Pointers/076.Minimum-Window-Substring/Readme.md @@ -4,7 +4,7 @@ 对于每个新加入的元素s[j],首先更新该字符出现次数的Map[s[i]]++。如果更新后,Map[s[i]]等于需要出现的次数Table[s[i]],则计数器count++,说明有一个字符满足了出现次数的要求. -当count等于t中的字符类型数COUNT时,说明任务已经实现。此时,让左指针不断右移,相应的Map[s[i]]就要自减,一旦Map[s[i]] < Table[s[i]],则count需要自减1从而不再满足COUNT,说明需要继续加入新元素才能满足任务. 从而j才可以右移继续遍历。 +当count等于t中的字符类型数COUNT时,说明任务已经实现。此时,让左指针不断右移,相应的Map[s[i]]就要自减,一旦`Map[s[i]] < Table[s[i]]`,则count需要自减1从而不再满足COUNT,说明需要继续加入新元素才能满足任务. 从而j才可以右移继续遍历。 在这个过程中如果满足条件count==COUNT,都需要不断更新和记录结果。 From d106ab60dfdbd1b656daf0152bfe0e6b73c09401 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Dec 2022 14:20:20 -0800 Subject: [PATCH 1425/2729] Update and rename 525.Contiguous Array.cpp to 525.Contiguous-Array.cpp --- .../525.Contiguous Array.cpp | 23 ----------------- .../525.Contiguous-Array.cpp | 25 +++++++++++++++++++ 2 files changed, 25 insertions(+), 23 deletions(-) delete mode 100644 Hash/525.Contiguous-Array/525.Contiguous Array.cpp create mode 100644 Hash/525.Contiguous-Array/525.Contiguous-Array.cpp diff --git a/Hash/525.Contiguous-Array/525.Contiguous Array.cpp b/Hash/525.Contiguous-Array/525.Contiguous Array.cpp deleted file mode 100644 index 153dc627a..000000000 --- a/Hash/525.Contiguous-Array/525.Contiguous Array.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - int findMaxLength(vector& nums) - { - int sum=0; - unordered_mapMap; - Map[0]=-1; - - int result=0; - for (int i=0; i& nums) + { + unordered_mapMap; // presum -> j + Map[0] = -1; + + int ret = 0; + int presum = 0; + for (int i=0; i Date: Sat, 3 Dec 2022 14:25:12 -0800 Subject: [PATCH 1426/2729] Update 974.Subarray-Sums-Divisible-by-K.cpp --- .../974.Subarray-Sums-Divisible-by-K.cpp | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/Hash/974.Subarray-Sums-Divisible-by-K/974.Subarray-Sums-Divisible-by-K.cpp b/Hash/974.Subarray-Sums-Divisible-by-K/974.Subarray-Sums-Divisible-by-K.cpp index 28764639e..3a0acfa01 100644 --- a/Hash/974.Subarray-Sums-Divisible-by-K/974.Subarray-Sums-Divisible-by-K.cpp +++ b/Hash/974.Subarray-Sums-Divisible-by-K/974.Subarray-Sums-Divisible-by-K.cpp @@ -1,19 +1,17 @@ class Solution { public: - int subarraysDivByK(vector& A, int K) - { + int subarraysDivByK(vector& nums, int k) { unordered_mapMap; - Map[0] = 1; - int presum = 0; - int ret = 0; - for (int i=0; i 0 ? presum%K : (presum%K+K)%K; - ret += Map[r]; + + int r = 0; + int count = 0; + for (int i=0; i Date: Sat, 3 Dec 2022 15:12:46 -0800 Subject: [PATCH 1427/2729] Update 1983.Widest-Pair-of-Indices-With-Equal-Range-Sum.cpp --- ...t-Pair-of-Indices-With-Equal-Range-Sum.cpp | 33 ++++++++----------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum.cpp b/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum.cpp index 192803a27..0c92d80cb 100644 --- a/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum.cpp +++ b/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum.cpp @@ -1,30 +1,23 @@ class Solution { public: int widestPairOfIndices(vector& nums1, vector& nums2) - { - int sum = 0; - int n = nums1.size(); - vectorpre1(n+1); - vectorpre2(n+1); - - for (int i=1; i<=n; i++) - pre1[i] = pre1[i-1]+nums1[i-1]; - for (int i=1; i<=n; i++) - pre2[i] = pre2[i-1]+nums2[i-1]; - - vectordiff(n+1); - for (int i=0; i<=n; i++) - diff[i] = pre1[i]-pre2[i]; - + { + vectorarr; + for (int i=0; iMap; - Map[0]=0; + Map[0] = -1; + + int presum = 0; int ret = 0; - for (int i=1; i<=n; i++) + for (int i=0; i Date: Sat, 3 Dec 2022 15:13:47 -0800 Subject: [PATCH 1428/2729] Update Readme.md --- .../Readme.md | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum/Readme.md b/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum/Readme.md index d44be1326..6e4d4d1a6 100644 --- a/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum/Readme.md +++ b/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum/Readme.md @@ -1,14 +1,3 @@ ### 1983.Widest-Pair-of-Indices-With-Equal-Range-Sum -令pre1表示nums1的前缀和数组,pre2表示nums2的前缀和数组。本题即求跨度最大的{i,j}使得 -``` -pre1[j]-pre1[i] = pre2[j]-pre2[i] -``` -稍微移项变换 -``` -pre1[j]-pre2[j] = pre1[i]-pre2[i] -``` -令diff数组表示pre1-pre2之差,那么本题的本质就是在diff数组里找跨度最大的{i,j}使得 -``` -dfff[i] = diff[j] -``` +令arr数组表示`arr[i]=nums1[i]-nums2[i]`,那么本题的本质就是在arr数组里找最大的subarray,使得其区间和是0. From d1aeb794fad39830fe494e366ae23ff8c2e2c73e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Dec 2022 15:14:19 -0800 Subject: [PATCH 1429/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d8889ef62..6dd2b3a87 100644 --- a/Readme.md +++ b/Readme.md @@ -159,6 +159,7 @@ * ``Hash+Prefix`` [525.Contiguous-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/525.Contiguous-Array) (M) [930.Binary-Subarrays-With-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/930.Binary-Subarrays-With-Sum) (M) +[1983.Widest-Pair-of-Indices-With-Equal-Range-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum) (M) [1442.Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1442.Count-Triplets-That-Can-Form-Two-Arrays-of-Equal-XOR) (H-) [1524.Number-of-Sub-arrays-With-Odd-Sum ](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1524.Number-of-Sub-arrays-With-Odd-Sum) (M) [974.Subarray-Sums-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Hash/974.Subarray-Sums-Divisible-by-K) (M) @@ -167,7 +168,6 @@ [1371.Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1371.Find-the-Longest-Substring-Containing-Vowels-in-Even-Counts) (H-) [1542.Find-Longest-Awesome-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1542.Find-Longest-Awesome-Substring) (H-) [1915.Number-of-Wonderful-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1915.Number-of-Wonderful-Substrings) (M+) -[1983.Widest-Pair-of-Indices-With-Equal-Range-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1983.Widest-Pair-of-Indices-With-Equal-Range-Sum) (M+) [2025.Maximum-Number-of-Ways-to-Partition-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array) (H) [2488.Count-Subarrays-With-Median-K](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2488.Count-Subarrays-With-Median-K) (H-) From 4abd043dcc82beaa5787887b592519a589d79eb8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 17:52:23 -0800 Subject: [PATCH 1430/2729] Create 2492.Minimum-Score-of-a-Path-Between-Two-Cities.cpp --- ...mum-Score-of-a-Path-Between-Two-Cities.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities/2492.Minimum-Score-of-a-Path-Between-Two-Cities.cpp diff --git a/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities/2492.Minimum-Score-of-a-Path-Between-Two-Cities.cpp b/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities/2492.Minimum-Score-of-a-Path-Between-Two-Cities.cpp new file mode 100644 index 000000000..0b325afa4 --- /dev/null +++ b/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities/2492.Minimum-Score-of-a-Path-Between-Two-Cities.cpp @@ -0,0 +1,41 @@ +class Solution { + int Father[100005]; + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (x>& roads) + { + for (int i=1; i<=n; i++) + Father[i] = i; + + for (auto road: roads) + { + int a = road[0], b = road[1], d = road[2]; + if (FindFather(a)!=FindFather(b)) + Union(a,b); + } + + int ret = INT_MAX; + for (auto road: roads) + { + int a = road[0], b = road[1], d = road[2]; + if (FindFather(a)==FindFather(1)) + ret = min(ret, d); + } + + return ret; + } +}; From c3c09073cfbc09ab3046e86d8d7c6460dccf986e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 17:52:52 -0800 Subject: [PATCH 1431/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6dd2b3a87..5cffd195a 100644 --- a/Readme.md +++ b/Readme.md @@ -941,6 +941,7 @@ [2076.Process-Restricted-Friend-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2076.Process-Restricted-Friend-Requests) (H-) [2092.Find-All-People-With-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2092.Find-All-People-With-Secret) (H-) [2157.Groups-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2157.Groups-of-Strings) (H) +[2492.Minimum-Score-of-a-Path-Between-Two-Cities](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities) (M) * ``Union in an order`` [803.Bricks-Falling-When-Hit](https://github.com/wisdompeak/LeetCode/tree/master/DFS/803.Bricks-Falling-When-Hit) (H) [1970.Last-Day-Where-You-Can-Still-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1970.Last-Day-Where-You-Can-Still-Cross) (H-) From 9524c5139dabe37f20805ac0f48dcedfc90edd76 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 17:55:16 -0800 Subject: [PATCH 1432/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities/Readme.md diff --git a/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities/Readme.md b/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities/Readme.md new file mode 100644 index 000000000..4ba9c11ce --- /dev/null +++ b/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities/Readme.md @@ -0,0 +1,5 @@ +### 2492.Minimum-Score-of-a-Path-Between-Two-Cities + +注意题意,一条路径允许重复访问边和节点。因此城市1与N之间的score本质,就是这两个节点所在连通图里最短的边。 + +所以我们用Union Find将所有的节点标记联通之后,只要再遍历一遍所有的边,找到最短的边、同时两个端点都是与1(或者N)联通的。 From ff7389dba9c36757a55ae11946615538bcbbe16c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 18:13:27 -0800 Subject: [PATCH 1433/2729] Create 2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp --- ...odes-Into-the-Maximum-Number-of-Groups.cpp | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp diff --git a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp new file mode 100644 index 000000000..8397c7007 --- /dev/null +++ b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp @@ -0,0 +1,73 @@ +class Solution { + int Father[505]; + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (xnext[505]; + +public: + int magnificentSets(int n, vector>& edges) + { + for (int i=1; i<=n; i++) + Father[i] = i; + for (auto edge: edges) + { + int a = edge[0], b = edge[1]; + if (FindFather(a)!=FindFather(b)) + Union(a,b); + next[a].push_back(b); + next[b].push_back(a); + } + + unordered_map>groups; + for (int i=1; i<=n; i++) + groups[FindFather(i)].push_back(i); + + int ret = 0; + + for (auto& [_, nodes]: groups) + { + int ans = 0; + for (int start: nodes) + { + unordered_maplevel; + level[start] = 1; + queue>q; + q.push({start, 1}); + + while (!q.empty()) + { + auto [cur, d] = q.front(); + q.pop(); + ans = max(ans, d); + + for (int nxt: next[cur]) + { + if (level.find(nxt)==level.end()) + { + level[nxt] = d+1; + q.push({nxt, d+1}); + } + else if (level[nxt] == d) + return -1; + } + } + } + ret += ans; + } + + return ret; + } +}; From 6aa47a9f7c63d196865f323250d5216e1b89cbe5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 18:14:00 -0800 Subject: [PATCH 1434/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5cffd195a..04d5b367e 100644 --- a/Readme.md +++ b/Readme.md @@ -518,6 +518,7 @@ [2101.Detonate-the-Maximum-Bombs](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2101.Detonate-the-Maximum-Bombs) (M+) [2258.Escape-the-Spreading-Fire](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2258.Escape-the-Spreading-Fire) (H+) [2290.Minimum-Obstacle-Removal-to-Reach-Corner](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner) (M+) +[2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups) (H-) * ``Multi State`` [847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) [864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) From e49e2a8b3eddab3ab616083758050abf54da38d5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 18:37:34 -0800 Subject: [PATCH 1435/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/Readme.md diff --git a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/Readme.md b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/Readme.md new file mode 100644 index 000000000..f19038d1f --- /dev/null +++ b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/Readme.md @@ -0,0 +1,9 @@ +### 2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups + +本题的突破点是,只要我们能确定一个节点作为第一个group,那么剩下的节点该如何安排其实是可以贪心地确定的:很显然只要用BFS进行层级遍历即可,就像生成一棵树一样,把同属于一个层级的放入一个group,不停往下扩展,这样就可以得到最多的层级(也就是group)。但是,本题要求同一个group不能有边,所以我们需要额外检查一下这种方法得到的拓扑结构,是否存在同一个层级的点有边相连的情况。有的话就标记终止。 + +因此,遍历起点的循环是V次,每次BFS需要至多访问E条边。总的时间复杂度是o(VE)恰好符合要求。 + +有人会问,以上的方法约定了第一个group只能有一个节点(看做是根)。可不可能有两个节点A与B都是处于第一个group的最优解呢?答案是不会更优。当A与B(第一层级)都和C(第二层级)联通时,我们其实按照之前的方法,会把B看做是第三个层级,显然这个方案能够得到更多的group。 + +此外,本题可能会有多个不同的联通区域。最终答案是每个联通区域所能构造出的最大group数量之和。一种处理方法是先用Union Find把不同联通区域的节点都标记出来,接着再遍历每个联通区域,变换根的位置去做BFS的尝试。另一种处理方法可以直接遍历每个节点作为根,BFS完之后记得将遇到的最小编号的节点作为联通区域的代号,最后我们将不同联通区域的答案再相加。 From 101c96efe2ac26d5d7b72a35935d16b7519f733f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 20:13:54 -0800 Subject: [PATCH 1436/2729] Update 2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp --- ...493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp index 8397c7007..d48a0b54b 100644 --- a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp +++ b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp @@ -42,7 +42,7 @@ class Solution { int ans = 0; for (int start: nodes) { - unordered_maplevel; + vectorlevel(505); level[start] = 1; queue>q; q.push({start, 1}); @@ -55,7 +55,7 @@ class Solution { for (int nxt: next[cur]) { - if (level.find(nxt)==level.end()) + if (level[nxt]==0) { level[nxt] = d+1; q.push({nxt, d+1}); @@ -65,9 +65,11 @@ class Solution { } } } + ret += ans; } - return ret; + return ret; + } }; From bee23d397cce6ab1c7d12611e52ef6be357705ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 20:21:20 -0800 Subject: [PATCH 1437/2729] Update Readme.md --- .../Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/Readme.md b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/Readme.md index f19038d1f..8fe7b181d 100644 --- a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/Readme.md +++ b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/Readme.md @@ -1,6 +1,8 @@ ### 2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups -本题的突破点是,只要我们能确定一个节点作为第一个group,那么剩下的节点该如何安排其实是可以贪心地确定的:很显然只要用BFS进行层级遍历即可,就像生成一棵树一样,把同属于一个层级的放入一个group,不停往下扩展,这样就可以得到最多的层级(也就是group)。但是,本题要求同一个group不能有边,所以我们需要额外检查一下这种方法得到的拓扑结构,是否存在同一个层级的点有边相连的情况。有的话就标记终止。 +本题的突破点是,只要我们能确定一个节点作为第一个group,那么剩下的节点该如何安排其实是可以贪心地确定的:很显然只要用BFS进行层级遍历即可,就像生成一棵树一样,把同属于一个层级的放入一个group,不停往下扩展,这样就可以得到最多的层级(也就是group)。 + +因为本题要求同一个group不能有边,所以我们需要检查一下这种方法得到的拓扑结构:是否有任何点指向了同一层级的其他点。有的话就标记BFS。特别注意的是,如果发现了这种情况,不仅意味着从当前根节点出发的BFS无解,也意味着整个连通图无解,即你从此连通图的任何一个位置作为根,都无法得到合法的层级结构。 因此,遍历起点的循环是V次,每次BFS需要至多访问E条边。总的时间复杂度是o(VE)恰好符合要求。 From 4527803406674f38a77e60cf5fea49458fc1d616 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 20:21:44 -0800 Subject: [PATCH 1438/2729] Update 2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp --- ...odes-Into-the-Maximum-Number-of-Groups.cpp | 86 +++++++------------ 1 file changed, 33 insertions(+), 53 deletions(-) diff --git a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp index d48a0b54b..97bddfc50 100644 --- a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp +++ b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp @@ -1,73 +1,53 @@ class Solution { - int Father[505]; - int FindFather(int x) - { - if (Father[x]!=x) - Father[x] = FindFather(Father[x]); - return Father[x]; - } - - void Union(int x, int y) - { - x = Father[x]; - y = Father[y]; - if (xnext[505]; - + vectornext [505]; public: int magnificentSets(int n, vector>& edges) { - for (int i=1; i<=n; i++) - Father[i] = i; for (auto edge: edges) { int a = edge[0], b = edge[1]; - if (FindFather(a)!=FindFather(b)) - Union(a,b); next[a].push_back(b); next[b].push_back(a); } - - unordered_map>groups; - for (int i=1; i<=n; i++) - groups[FindFather(i)].push_back(i); - - int ret = 0; - - for (auto& [_, nodes]: groups) - { - int ans = 0; - for (int start: nodes) - { - vectorlevel(505); - level[start] = 1; - queue>q; - q.push({start, 1}); - while (!q.empty()) + unordered_mapMap; + for (int start=1; start<=n; start++) + { + int maxDepth = 0; + int smallestId = INT_MAX; + vectorlevel(505); + + queue>q; + q.push({start,1}); + level[start] = 1; + + while (!q.empty()) + { + auto [cur, d] = q.front(); + q.pop(); + maxDepth = max(maxDepth, d); + smallestId = min(smallestId, cur); + + for (int nxt: next[cur]) { - auto [cur, d] = q.front(); - q.pop(); - ans = max(ans, d); - - for (int nxt: next[cur]) + if (level[nxt] == 0) + { + level[nxt] = d+1; + q.push({nxt, d+1}); + } + else if (level[nxt] == d) { - if (level[nxt]==0) - { - level[nxt] = d+1; - q.push({nxt, d+1}); - } - else if (level[nxt] == d) - return -1; + return -1; } } } - ret += ans; - } + Map[smallestId] = max(Map[smallestId], maxDepth); + } + + int ret = 0; + for (auto [k,v]: Map) + ret += v; return ret; From 72e6dc7b6c11cb73717d44289cd696d4435c5849 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Dec 2022 22:35:35 -0800 Subject: [PATCH 1439/2729] Update 2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp --- ...odes-Into-the-Maximum-Number-of-Groups.cpp | 66 +++++++++++-------- 1 file changed, 37 insertions(+), 29 deletions(-) diff --git a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp index 97bddfc50..f7e5b0c5d 100644 --- a/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp +++ b/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp @@ -1,5 +1,5 @@ class Solution { - vectornext [505]; + vectornext[505]; public: int magnificentSets(int n, vector>& edges) { @@ -9,47 +9,55 @@ class Solution { next[a].push_back(b); next[b].push_back(a); } - + unordered_mapMap; + for (int start=1; start<=n; start++) - { - int maxDepth = 0; + { + int d = 0; int smallestId = INT_MAX; vectorlevel(505); - - queue>q; - q.push({start,1}); - level[start] = 1; - + + queueq; + q.push(start); + level[start] = 1; + while (!q.empty()) { - auto [cur, d] = q.front(); - q.pop(); - maxDepth = max(maxDepth, d); - smallestId = min(smallestId, cur); - - for (int nxt: next[cur]) + d++; + int len = q.size(); + while (len--) { - if (level[nxt] == 0) - { - level[nxt] = d+1; - q.push({nxt, d+1}); - } - else if (level[nxt] == d) + int cur = q.front(); + q.pop(); + smallestId = min(smallestId, cur); + + for (int nxt: next[cur]) { - return -1; - } - } + if (level[nxt] == 0) + { + level[nxt] = d+1; + q.push(nxt); + } + else if (level[nxt] == d) + { + return -1; + } + } + } } - Map[smallestId] = max(Map[smallestId], maxDepth); - } + Map[smallestId] = max(Map[smallestId], d); + } int ret = 0; - for (auto [k,v]: Map) + for (auto [k, v]: Map) ret += v; - return ret; - + return ret; } }; + + + + From e7092e4161a4e3815dca142cae93fcda2fbf6984 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 11:14:12 -0800 Subject: [PATCH 1440/2729] Create 2503.Maximum-Number-of-Points-From-Grid-Queries.cpp --- ...mum-Number-of-Points-From-Grid-Queries.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 BFS/2503.Maximum-Number-of-Points-From-Grid-Queries/2503.Maximum-Number-of-Points-From-Grid-Queries.cpp diff --git a/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries/2503.Maximum-Number-of-Points-From-Grid-Queries.cpp b/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries/2503.Maximum-Number-of-Points-From-Grid-Queries.cpp new file mode 100644 index 000000000..34b8511bc --- /dev/null +++ b/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries/2503.Maximum-Number-of-Points-From-Grid-Queries.cpp @@ -0,0 +1,47 @@ +using AI3 = array; +class Solution { +public: + vector maxPoints(vector>& grid, vector& queries) + { + vector>dir({{0,1},{0,-1},{1,0},{-1,0}}); + vector>qs; + for (int i=0; irets(queries.size()); + + priority_queue, greater<>>pq; + pq.push({grid[0][0], 0, 0}); + + int count = 0; + int m = grid.size(), n = grid[0].size(); + vector>visited(m, vector(n)); + visited[0][0] = 1; + + for (auto [q, idx]: qs) + { + while (!pq.empty() && pq.top()[0] < q) + { + int i = pq.top()[1], j = pq.top()[2]; + pq.pop(); + count++; + + for (int k=0; k<4; k++) + { + int x = i+dir[k].first; + int y = j+dir[k].second; + if (x<0||x>=m||y<0||y>=n) continue; + if (visited[x][y]) + continue; + + pq.push({grid[x][y],x,y}); + visited[x][y] = 1; + } + } + rets[idx] = count; + } + return rets; + } +}; From 5267f26dcf825d57eb0435487ee85fc570286851 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 11:15:02 -0800 Subject: [PATCH 1441/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 04d5b367e..b0b44c6ec 100644 --- a/Readme.md +++ b/Readme.md @@ -547,9 +547,10 @@ [2392.Build-a-Matrix-With-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2392.Build-a-Matrix-With-Conditions) (M+) [2440.Create-Components-With-Same-Value](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2440.Create-Components-With-Same-Value) (H-) * ``Dijkstra (BFS+PQ)`` -[743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H) +[743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H-) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) [778.Swim-in-Rising-Water](https://github.com/wisdompeak/LeetCode/tree/master/BFS/778.Swim-in-Rising-Water) (H) +[2503.Maximum-Number-of-Points-From-Grid-Queries](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries) (H-) [505.The-Maze-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/505.The-Maze-II) (H-) [499.The-Maze-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/499.The-Maze-III) (H) [787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) From 381497f625371ff61e214e0a450f38af91f111d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 11:26:42 -0800 Subject: [PATCH 1442/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2503.Maximum-Number-of-Points-From-Grid-Queries/Readme.md diff --git a/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries/Readme.md b/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries/Readme.md new file mode 100644 index 000000000..7d291bded --- /dev/null +++ b/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries/Readme.md @@ -0,0 +1,5 @@ +### 2503.Maximum-Number-of-Points-From-Grid-Queries + +根据题意,如果query越小,那么我们能够扩展的范围越小。query越大,扩展的范围是单调地增大的。所以我们必然会将queries排序,优先处理更小的query,比如常规的BFS来遍历所有小于query的格子;然后再处理更大的query,尝试重复利用已经探索过的网格区域。 + +此时,我们就发现此题很像`778.Swim-in-Rising-Water `,一开始只能在一个较矮的水平面游泳。后来水平面提升了,必然可以淹过一些在边界处相对地势较低的格子,不断往外溢出。于是,我们只要在BFS的时候,将队列里将格子按照地势从低到高排列。如果队列首元素的海拔小于query,那么它就确认被淹了,它的邻接格子就会成为新的堤岸被加入队列做下一步的考察。直至队列的首元素大于等于query,就意味着我们BFS的进程中被当前的边界所围住,已经占据了从左上角开始可以联络到的所有小于query的位置。 From f35dbc5447bc46e22507390a40354347254d1c84 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 14:33:16 -0800 Subject: [PATCH 1443/2729] Create 2445.Number-of-Nodes-With-Value-One.cpp --- .../2445.Number-of-Nodes-With-Value-One.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Tree/2445.Number-of-Nodes-With-Value-One/2445.Number-of-Nodes-With-Value-One.cpp diff --git a/Tree/2445.Number-of-Nodes-With-Value-One/2445.Number-of-Nodes-With-Value-One.cpp b/Tree/2445.Number-of-Nodes-With-Value-One/2445.Number-of-Nodes-With-Value-One.cpp new file mode 100644 index 000000000..d531339be --- /dev/null +++ b/Tree/2445.Number-of-Nodes-With-Value-One/2445.Number-of-Nodes-With-Value-One.cpp @@ -0,0 +1,25 @@ +class Solution { + int ret = 0; + unordered_mapMap; +public: + int numberOfNodes(int n, vector& queries) + { + for (int q: queries) + Map[q]++; + dfs(1,0,n); + return ret; + } + + void dfs(int cur, int flips, int n) + { + if (cur > n) return; + + if (Map.find(cur)!=Map.end()) + flips += Map[cur]; + if (flips%2==1) + ret++; + + dfs(cur*2, flips, n); + dfs(cur*2+1, flips, n); + } +}; From 9e79ef2aee01781043a0543b9bf26bebed9fba86 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 14:33:39 -0800 Subject: [PATCH 1444/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b0b44c6ec..86aa992ec 100644 --- a/Readme.md +++ b/Readme.md @@ -242,6 +242,7 @@ [2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) [2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) [2467.Most-Profitable-Path-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2467.Most-Profitable-Path-in-a-Tree) (M+) +[2445.Number-of-Nodes-With-Value-One](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2445.Number-of-Nodes-With-Value-One) (M+) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) From 7f83c1f73837ff6144ceb9e2d30d80f85dec28fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 14:37:27 -0800 Subject: [PATCH 1445/2729] Create Readme.md --- Tree/2445.Number-of-Nodes-With-Value-One/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Tree/2445.Number-of-Nodes-With-Value-One/Readme.md diff --git a/Tree/2445.Number-of-Nodes-With-Value-One/Readme.md b/Tree/2445.Number-of-Nodes-With-Value-One/Readme.md new file mode 100644 index 000000000..e4e236c1a --- /dev/null +++ b/Tree/2445.Number-of-Nodes-With-Value-One/Readme.md @@ -0,0 +1,3 @@ +### 2445.Number-of-Nodes-With-Value-One + +我们从根往下遍历每个节点,递归过程中累加所遇到的queries的数目,即意味着当前这个节点会被翻转多少次。 From a34b177c81135fcfed878b8bd7314969899315cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 14:52:45 -0800 Subject: [PATCH 1446/2729] Create 2498.Frog-Jump-II.cpp --- Greedy/2498.Frog-Jump-II/2498.Frog-Jump-II.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Greedy/2498.Frog-Jump-II/2498.Frog-Jump-II.cpp diff --git a/Greedy/2498.Frog-Jump-II/2498.Frog-Jump-II.cpp b/Greedy/2498.Frog-Jump-II/2498.Frog-Jump-II.cpp new file mode 100644 index 000000000..6f359b922 --- /dev/null +++ b/Greedy/2498.Frog-Jump-II/2498.Frog-Jump-II.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maxJump(vector& stones) + { + int n = stones.size(); + + if (n==2) + return stones[1]; + + int ret = 0; + for (int i=0; i+2 Date: Sun, 11 Dec 2022 14:53:09 -0800 Subject: [PATCH 1447/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 86aa992ec..45bdca404 100644 --- a/Readme.md +++ b/Readme.md @@ -1263,6 +1263,7 @@ [2122.Recover-the-Original-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2122.Recover-the-Original-Array) (H-) [1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) [2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) +[2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 6ee6be2bc06dfe768caa041f2f4eeff852803bb7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 15:10:17 -0800 Subject: [PATCH 1448/2729] Create Readme.md --- Greedy/2498.Frog-Jump-II/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2498.Frog-Jump-II/Readme.md diff --git a/Greedy/2498.Frog-Jump-II/Readme.md b/Greedy/2498.Frog-Jump-II/Readme.md new file mode 100644 index 000000000..ec0d244e5 --- /dev/null +++ b/Greedy/2498.Frog-Jump-II/Readme.md @@ -0,0 +1,9 @@ +### 2498.Frog-Jump-II + +本题是说从起点到终点找两条路径,除了端点外,不能有重合的点。问最大跨度距离的最小值是多少。 + +我们考虑是否可以在相邻的两块石头上连续跳跃?考虑a-b-c-d这个例子。对于b和c这两块石头,如果都是在去程是被踩到,那么在回程的时候必然有一步至少要跨越d->a这段距离。显然这个距离太大了,我们有更好的方案,那就是去程时a->c(其中a不见得一定踩),回程时d->b(其中b不见得一定踩),这样最大跨度是就是ac与bd中的较大值,但是肯定比ad的跨度要小。所以结论是,任何时候,连续踩相邻的石头都不会是最优解,比不过间隔一个地去踩。 + +那我们是否会跨越两个这样得去踩呢?同样,a->d这种踩法,显然也不如a->c和b->d这种踩法优秀。 + +所以,最优的解法就是间隔一个地去踩。找全局最大的`stones[i+1]-stones[i]`. From 746691d6f0230dca1ae5e42777b94caffa5a3ef1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 15:46:35 -0800 Subject: [PATCH 1449/2729] Update Readme.md --- Greedy/2498.Frog-Jump-II/Readme.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Greedy/2498.Frog-Jump-II/Readme.md b/Greedy/2498.Frog-Jump-II/Readme.md index ec0d244e5..c1b7936ab 100644 --- a/Greedy/2498.Frog-Jump-II/Readme.md +++ b/Greedy/2498.Frog-Jump-II/Readme.md @@ -1,9 +1,7 @@ ### 2498.Frog-Jump-II -本题是说从起点到终点找两条路径,除了端点外,不能有重合的点。问最大跨度距离的最小值是多少。 +本题可以看成两只青蛙从起点到终点,除了两处端点外,不能有重合的点。问任何青蛙最大跨度距离的最小值是多少。 -我们考虑是否可以在相邻的两块石头上连续跳跃?考虑a-b-c-d这个例子。对于b和c这两块石头,如果都是在去程是被踩到,那么在回程的时候必然有一步至少要跨越d->a这段距离。显然这个距离太大了,我们有更好的方案,那就是去程时a->c(其中a不见得一定踩),回程时d->b(其中b不见得一定踩),这样最大跨度是就是ac与bd中的较大值,但是肯定比ad的跨度要小。所以结论是,任何时候,连续踩相邻的石头都不会是最优解,比不过间隔一个地去踩。 +我们考察当前的石头i,此时的两者青蛙必然一个在前a,一个在后b,记做a->b->i->c。显然,我们应该让a处的青蛙先落地休息得到跨度a->i,而另一只青蛙则需要再跳至少b->c。相反,另外一种方案,让b处的青蛙先落地的话,那么a处的青蛙之后必然至少要跳跃一个更大的跨度a->c。显然这个方案是不及前者优秀的。所以得到一个结论,任何时候,都让离得更远的青蛙先落地。 -那我们是否会跨越两个这样得去踩呢?同样,a->d这种踩法,显然也不如a->c和b->d这种踩法优秀。 - -所以,最优的解法就是间隔一个地去踩。找全局最大的`stones[i+1]-stones[i]`. +这个结论的推论就非常有趣,该方案必然导致了两个青蛙轮流落地。所以,最优解法就是找全局最大的`stones[i+2]-stones[i]`. From 0c56fad3279d30663765947332b42c406cdb49a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 18:18:09 -0800 Subject: [PATCH 1450/2729] Create 2499.minimum-total-cost-to-make-arrays-unequal.cpp --- ...imum-total-cost-to-make-arrays-unequal.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Greedy/2499.minimum-total-cost-to-make-arrays-unequal/2499.minimum-total-cost-to-make-arrays-unequal.cpp diff --git a/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/2499.minimum-total-cost-to-make-arrays-unequal.cpp b/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/2499.minimum-total-cost-to-make-arrays-unequal.cpp new file mode 100644 index 000000000..25d40add1 --- /dev/null +++ b/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/2499.minimum-total-cost-to-make-arrays-unequal.cpp @@ -0,0 +1,49 @@ +using LL = long long; +class Solution { +public: + long long minimumTotalCost(vector& nums1, vector& nums2) + { + int n = nums1.size(); + unordered_mapcount; + int total = 0; + LL ret = 0; + for (int i=0; i n/2) return -1; + + if (maxCount <= total-maxCount) + return ret; + + int extra = maxCount - (total - maxCount); + for (int i=0; i Date: Sun, 11 Dec 2022 18:18:42 -0800 Subject: [PATCH 1451/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 45bdca404..71ed7a743 100644 --- a/Readme.md +++ b/Readme.md @@ -1264,6 +1264,7 @@ [1982.Find-Array-Given-Subset-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1982.Find-Array-Given-Subset-Sums) (H) [2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) +[2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 49bb2a2e3f653ecb4fb828658c88128b3ab31ba0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 20:36:20 -0800 Subject: [PATCH 1452/2729] Create Readme.md --- .../2499.minimum-total-cost-to-make-arrays-unequal/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2499.minimum-total-cost-to-make-arrays-unequal/Readme.md diff --git a/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/Readme.md b/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/Readme.md new file mode 100644 index 000000000..f93954a3d --- /dev/null +++ b/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/Readme.md @@ -0,0 +1,5 @@ +### 2499.minimum-total-cost-to-make-arrays-unequal + +首先我们考虑答案至少是多少?如果所有的same pairs能够在“内部调整”后满足要求,即交换只涉及same pairs所在的位置,那么答案就是这些same pairs的下标之和。显然,这个答案是最小的。 + +那么什么情况下我们能够保证所有的same pairs在“内部调整”后就能满足要求呢?只要其中的majority element不超过same pairs的总数的一半即可。举个例子`(2,2),(2,2),(2,2),(1,1),(3,3),(4,4),`我们必然可以 From b8399fae1f8e2abe01a2559d2764c8f3c86849a3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 20:48:24 -0800 Subject: [PATCH 1453/2729] Update Readme.md --- .../Readme.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/Readme.md b/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/Readme.md index f93954a3d..49383c45a 100644 --- a/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/Readme.md +++ b/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/Readme.md @@ -1,5 +1,11 @@ ### 2499.minimum-total-cost-to-make-arrays-unequal -首先我们考虑答案至少是多少?如果所有的same pairs能够在“内部调整”后满足要求,即交换只涉及same pairs所在的位置,那么答案就是这些same pairs的下标之和。显然,这个答案是最小的。 +首先我们考虑答案至少是多少?如果所有的same pairs能够在“内部调整”后满足要求,即交换只涉及same pairs所在的位置,那么答案就是这些same pairs的下标之和。显然,这个答案是最小的,记做ret。 -那么什么情况下我们能够保证所有的same pairs在“内部调整”后就能满足要求呢?只要其中的majority element不超过same pairs的总数的一半即可。举个例子`(2,2),(2,2),(2,2),(1,1),(3,3),(4,4),`我们必然可以 +那么什么情况下我们能够保证所有的same pairs在“内部调整”后就能满足要求呢?只要其中的majority element不超过same pairs的总数的一半即可。举个例子`(2,2),(2,2),(2,2),(1,1),(3,3),(4,4),`我们只要把2和非2元素交换,就可以满足同一个pair里的两个元素不同。但是如果有过半数的majority element,例如`(2,2),(2,2),(2,2),(2,2),(1,1),(3,3),`那么我们就无法找到足够多的非2元素来拆散`(2,2)`. + +对于上述的第一种情况,输出ret即可。对于第二种情况,我们就需要借助于其他pair的帮助。在这个例子中,“内部调整”后我们还有两对`(2,2)`没有被拆散,这就需要我们找其他distinc pairs来与之交换。显然,我们会按下标从小到大去尝试。例如我们考察`(a,b)`的时候,思考它是否能帮助拆散`(2,2)`,需要满足的条件有三个: +1. `a!=b`,否则这是一个same pair,已经在“内部调整”时用过了。 +2. `a!=2`且`b!=2`,否则交换之后仍然会有一个`(2,2)`。 + +满足上述两个条件,那么我们就再做一次`(a,b)`与`(2,2)`的交换即可。以此类推不断寻找下一个合适的distinct pair,直至将多余的`(2,2)`消耗掉。 From f022e11862ad1d6ccd4ab0720320edda6db2be48 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 11 Dec 2022 20:55:42 -0800 Subject: [PATCH 1454/2729] Update 2499.minimum-total-cost-to-make-arrays-unequal.cpp --- .../2499.minimum-total-cost-to-make-arrays-unequal.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/2499.minimum-total-cost-to-make-arrays-unequal.cpp b/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/2499.minimum-total-cost-to-make-arrays-unequal.cpp index 25d40add1..ac9f837af 100644 --- a/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/2499.minimum-total-cost-to-make-arrays-unequal.cpp +++ b/Greedy/2499.minimum-total-cost-to-make-arrays-unequal/2499.minimum-total-cost-to-make-arrays-unequal.cpp @@ -25,9 +25,7 @@ class Solution { for (auto& [val,freq]:count) if (freq==maxCount) maxVal = val; - - if (maxCount > n/2) return -1; - + if (maxCount <= total-maxCount) return ret; From e2a4f7e3f6f1e0f287fafcb4f5c4ab03560d94d4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 21 Dec 2022 18:25:50 -0800 Subject: [PATCH 1455/2729] Create 863.All-Nodes-Distance-K-in-Binary-Tree_v2.cpp --- ...All-Nodes-Distance-K-in-Binary-Tree_v2.cpp | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Tree/863.All-Nodes-Distance-K-in-Binary-Tree/863.All-Nodes-Distance-K-in-Binary-Tree_v2.cpp diff --git a/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/863.All-Nodes-Distance-K-in-Binary-Tree_v2.cpp b/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/863.All-Nodes-Distance-K-in-Binary-Tree_v2.cpp new file mode 100644 index 000000000..55e7743f9 --- /dev/null +++ b/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/863.All-Nodes-Distance-K-in-Binary-Tree_v2.cpp @@ -0,0 +1,61 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + unordered_map>adj; +public: + vector distanceK(TreeNode* root, TreeNode* target, int K) + { + if (K==0) return {target->val}; + + DFS(root); + + queue>q; + unordered_setvisited; + + q.push({target->val,0}); + visited.insert(target->val); + + vectorresults; + while (!q.empty()) + { + auto [cur, step] = q.front(); + q.pop(); + if (step>K) break; + + for (int next: adj[cur]) + { + if (visited.find(next)!=visited.end()) + continue; + q.push({next,step+1}); + visited.insert(next); + + if (step+1==K) results.push_back(next); + } + } + return results; + } + + void DFS(TreeNode* node) + { + if (node==NULL) return; + if (node->left!=NULL) + { + adj[node->val].push_back(node->left->val); + adj[node->left->val].push_back(node->val); + DFS(node->left); + } + if (node->right!=NULL) + { + adj[node->val].push_back(node->right->val); + adj[node->right->val].push_back(node->val); + DFS(node->right); + } + } +}; From 30acb22a3711a71e394a939d11a4027ec45d62cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 21 Dec 2022 18:28:12 -0800 Subject: [PATCH 1456/2729] Update Readme.md --- Tree/863.All-Nodes-Distance-K-in-Binary-Tree/Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/Readme.md b/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/Readme.md index f083b3eb5..c32ae972b 100644 --- a/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/Readme.md +++ b/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/Readme.md @@ -1,5 +1,6 @@ ### 863.All-Nodes-Distance-K-in-Binary-Tree +#### 解法1: 本题的关键点是,任何两个节点AB之间的路径,都可以想象成有一个“拐点”O,其中OA是沿左子树向下的路径,OB是沿右子树向下的路径。我们可以递归处理每一个节点node,设想它是这个拐点,A是target并位于其中一个分支,那么如何在另一个分支中找到B?显然,假设我们能得到target到node->left之间的距离是t,那么我们只需要从node->right出发往下走k-2-t步,所抵达的节点就都是符合要求的B点。同理,如果target位于node->right分支,类似的处理。 需要单独处理的情况就是```node==target```,此时我们找的就是从node开始往下走k步到达的节点。 @@ -8,5 +9,8 @@ 本题和```543.Diameter-of-Binary-Tree```的套路是一样的。也就是说,对于树里面任何两点之间的距离,优先去想它的拐点。 +#### 解法2: +将树的形式转化为图的形式。这样就可以target为起点进行BFS,寻找距离为k的点。 -[Leetcode Link](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree) From 52085434a60a54dc9f0ebde390588d834f8210d0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 21 Dec 2022 18:28:32 -0800 Subject: [PATCH 1457/2729] Rename 863.All-Nodes-Distance-K-in-Binary-Tree.cpp to 863.All-Nodes-Distance-K-in-Binary-Tree_v1.cpp --- ...ry-Tree.cpp => 863.All-Nodes-Distance-K-in-Binary-Tree_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/863.All-Nodes-Distance-K-in-Binary-Tree/{863.All-Nodes-Distance-K-in-Binary-Tree.cpp => 863.All-Nodes-Distance-K-in-Binary-Tree_v1.cpp} (100%) diff --git a/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/863.All-Nodes-Distance-K-in-Binary-Tree.cpp b/Tree/863.All-Nodes-Distance-K-in-Binary-Tree/863.All-Nodes-Distance-K-in-Binary-Tree_v1.cpp similarity index 100% rename from Tree/863.All-Nodes-Distance-K-in-Binary-Tree/863.All-Nodes-Distance-K-in-Binary-Tree.cpp rename to Tree/863.All-Nodes-Distance-K-in-Binary-Tree/863.All-Nodes-Distance-K-in-Binary-Tree_v1.cpp From a59c15856eebaba69cd3337018adc494ca9fb3a7 Mon Sep 17 00:00:00 2001 From: meng621 <111479526+meng621@users.noreply.github.com> Date: Thu, 22 Dec 2022 18:21:43 -0700 Subject: [PATCH 1458/2729] Added link to leetcode --- .../1533.Find-the-Index-of-the-Large-Integer/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Binary_Search/1533.Find-the-Index-of-the-Large-Integer/Readme.md b/Binary_Search/1533.Find-the-Index-of-the-Large-Integer/Readme.md index 4692c0f8c..ed157adc9 100644 --- a/Binary_Search/1533.Find-the-Index-of-the-Large-Integer/Readme.md +++ b/Binary_Search/1533.Find-the-Index-of-the-Large-Integer/Readme.md @@ -3,3 +3,5 @@ 本题本质是三分搜索。我们将一个区间分为三分ABC,其中A和B的区间大小相等。如果A、B区间和相等,那么异类就在区间C里面。如果A、B区间和不相等,那么异类就在A、B较大的区间里面。 注意外层循环的条件变成了```while (right-left+1 >= 3)```。原因是区间大学小于3的时候无法成功三分区间。 + +[Leetcode link](https://leetcode.com/problems/find-the-index-of-the-large-integer/) From 220d2de01d1e11350e66007644cd5be452602e06 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Dec 2022 15:40:20 -0800 Subject: [PATCH 1459/2729] Create 2518.Number-of-Great-Partitions.cpp --- .../2518.Number-of-Great-Partitions.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Dynamic_Programming/2518.Number-of-Great-Partitions/2518.Number-of-Great-Partitions.cpp diff --git a/Dynamic_Programming/2518.Number-of-Great-Partitions/2518.Number-of-Great-Partitions.cpp b/Dynamic_Programming/2518.Number-of-Great-Partitions/2518.Number-of-Great-Partitions.cpp new file mode 100644 index 000000000..3b15fa187 --- /dev/null +++ b/Dynamic_Programming/2518.Number-of-Great-Partitions/2518.Number-of-Great-Partitions.cpp @@ -0,0 +1,29 @@ +using LL = long long; +class Solution { + LL dp[1005][1005]; + LL M = 1e9+7; +public: + int countPartitions(vector& nums, int k) + { + int n = nums.size(); + + LL total = accumulate(nums.begin(), nums.end(), 0LL); + if (total < k*2) return 0; + + dp[0][0] = 1; + dp[0][min(k, nums[0])] = 1; + + for (int i=0; i Date: Sun, 25 Dec 2022 16:24:58 -0800 Subject: [PATCH 1460/2729] Create Readme.md --- .../2518.Number-of-Great-Partitions/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Dynamic_Programming/2518.Number-of-Great-Partitions/Readme.md diff --git a/Dynamic_Programming/2518.Number-of-Great-Partitions/Readme.md b/Dynamic_Programming/2518.Number-of-Great-Partitions/Readme.md new file mode 100644 index 000000000..dc7e020d6 --- /dev/null +++ b/Dynamic_Programming/2518.Number-of-Great-Partitions/Readme.md @@ -0,0 +1,11 @@ +### 2518.Number-of-Great-Partitions + +首先我们计算一下nums的总和,如果小于2k,那么直接返回无解。 + +从数据规模上来看,我们会写出类似于dp[i][s]的表达式,表示前i个元素里有多少种方案可以构造一组元素(称之为group A)其和是s。注意,我们无法穷举所有s的可能(否则上限会达到`1e9*1000`),但是本题里,因为元素和大于等于k对于我们来说没有区别,我们只需要计算`s=k`的dp值就是方案总数`2^i`(每个元素随机分入A或者B)所对应的补集。 + +那么如何计算dp[i][s]呢?这就是一个传统的背包问题。dp写法就是考虑是否选取第i个元素,如果选取则有`dp[i][s] = dp[i-1][s-nums[i]]`,如果不选取则有`dp[i][s] = dp[i-1][s]`,我们将这两种情况相加就是构造dp[i][s]的总的方案数。 + +于是,我们得到了`2^n - sum{dp[n][s], s=0,1,2,..k-1}`,表示构造group A元素和大于等于k的方案数。但是如何保证group B的元素和也大于等于k呢?我们就需要从中减去那些“group A元素和大等于k,且group B元素和小于k”的方案数。注意到,如果group A元素和大于等于k,言下之意必然有group B元素和小于k,这是我们在题目开头就保证的。所以“group A元素和大等于k,且group B元素和小于k”的方案数 => “group B元素和小于k”的方案数 => “group A元素和小于k”的方案数 => `sum{dp[n][s], s=0,1,2,..k-1}` + +所以最终答案就是`2^n - 2 * sum{dp[n][s], s=0,1,2,..k-1}` From da1285fef819301d7184873780ca04a67c77080c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Dec 2022 16:25:48 -0800 Subject: [PATCH 1461/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 71ed7a743..a3a1b0a02 100644 --- a/Readme.md +++ b/Readme.md @@ -730,6 +730,7 @@ [1449.Form-Largest-Integer-With-Digits-That-Add-up-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1449.Form-Largest-Integer-With-Digits-That-Add-up-to-Target) (H-) [1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements) (M+) [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) +[2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From edfad38af460aa64147af476992821e04da261d1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 25 Dec 2022 16:27:40 -0800 Subject: [PATCH 1462/2729] Update 2518.Number-of-Great-Partitions.cpp --- .../2518.Number-of-Great-Partitions.cpp | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/Dynamic_Programming/2518.Number-of-Great-Partitions/2518.Number-of-Great-Partitions.cpp b/Dynamic_Programming/2518.Number-of-Great-Partitions/2518.Number-of-Great-Partitions.cpp index 3b15fa187..c5765728f 100644 --- a/Dynamic_Programming/2518.Number-of-Great-Partitions/2518.Number-of-Great-Partitions.cpp +++ b/Dynamic_Programming/2518.Number-of-Great-Partitions/2518.Number-of-Great-Partitions.cpp @@ -4,26 +4,32 @@ class Solution { LL M = 1e9+7; public: int countPartitions(vector& nums, int k) - { - int n = nums.size(); - - LL total = accumulate(nums.begin(), nums.end(), 0LL); - if (total < k*2) return 0; + { + if (accumulate(nums.begin(), nums.end(), 0LL) < k*2) + return 0; + int n = nums.size(); + nums.insert(nums.begin(), 0); + dp[0][0] = 1; - dp[0][min(k, nums[0])] = 1; - for (int i=0; i=nums[i]) + dp[i][s] += dp[i-1][s-nums[i]]; + dp[i][s] %= M; } - LL d = 0; + LL total = 1; + for (int i=1; i<=n; i++) + total = total * 2 % M; + + LL invalid = 0; for (int s=0; s Date: Sun, 25 Dec 2022 17:25:31 -0800 Subject: [PATCH 1463/2729] Update 494.Target-Sum_DP_v3.cpp --- .../494.Target-Sum/494.Target-Sum_DP_v3.cpp | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/Dynamic_Programming/494.Target-Sum/494.Target-Sum_DP_v3.cpp b/Dynamic_Programming/494.Target-Sum/494.Target-Sum_DP_v3.cpp index c306e9fc6..bd109cb2c 100644 --- a/Dynamic_Programming/494.Target-Sum/494.Target-Sum_DP_v3.cpp +++ b/Dynamic_Programming/494.Target-Sum/494.Target-Sum_DP_v3.cpp @@ -1,28 +1,27 @@ class Solution { + int dp[25][2005]; public: int findTargetSumWays(vector& nums, int S) { int sum = accumulate(nums.begin(), nums.end(), 0); if (S>sum || S<-sum) return false; - int offset = sum; - vectordp(2*offset+1); - dp[0+offset] = 1; + int n = nums.size(); + nums.insert(nums.begin(), 0); + + int offset = 1000; + dp[0][offset] = 1; - for (auto x: nums) - { - auto temp = dp; - for (int i=-offset; i<=offset; i++) + for (int i=1; i<=n; i++) + for (int s = -1000; s<=1000; s++) { - dp[i+offset] = 0; - if (i-x>=-offset) - dp[i+offset] += temp[i-x+offset]; - if (i+x<=offset) - dp[i+offset] += temp[i+x+offset]; - //cout<=-1000) + dp[i][s+offset] += dp[i-1][s-nums[i]+offset]; + + if (s+nums[i]<=1000 && s+nums[i]>=-1000) + dp[i][s+offset] += dp[i-1][s+nums[i]+offset]; } - } - return dp[S+offset]; + return dp[n][S+offset]; } }; From 6dac5fdf8f60816c2dcd985b72b64244daad2751 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 12:06:50 -0800 Subject: [PATCH 1464/2729] Create 2459.Sort-Array-by-Moving-Items-to-Empty-Space.cpp --- ...t-Array-by-Moving-Items-to-Empty-Space.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space/2459.Sort-Array-by-Moving-Items-to-Empty-Space.cpp diff --git a/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space/2459.Sort-Array-by-Moving-Items-to-Empty-Space.cpp b/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space/2459.Sort-Array-by-Moving-Items-to-Empty-Space.cpp new file mode 100644 index 000000000..b81483211 --- /dev/null +++ b/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space/2459.Sort-Array-by-Moving-Items-to-Empty-Space.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int sortArray(vector& nums) + { + int ret1 = helper(nums); + nums.insert(nums.begin(), nums.back()); + nums.pop_back(); + int ret2 = helper(nums); + return min(ret1, ret2); + } + + int helper(vectornums) + { + int n = nums.size(); + int count = 0; + for (int i=0; i Date: Mon, 26 Dec 2022 12:07:19 -0800 Subject: [PATCH 1465/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a3a1b0a02..948121f48 100644 --- a/Readme.md +++ b/Readme.md @@ -1235,6 +1235,7 @@ [448.Find-All-Numbers-Disappeared-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/448.Find-All-Numbers-Disappeared-in-an-Array) (M) [645.Set-Mismatch](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/645.Set-Mismatch) (M) [2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level) (M+) +[2459.Sort-Array-by-Moving-Items-to-Empty-Space](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space) (H) * ``Parenthesis`` [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) [921.Minimum-Add-to-Make-Parentheses-Valid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/921.Minimum-Add-to-Make-Parentheses-Valid) (M+) From 1bd33d1c9866841f3e97f19fe34cd73bee0892f0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 12:37:38 -0800 Subject: [PATCH 1466/2729] Create Readme.md --- .../Readme.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space/Readme.md diff --git a/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space/Readme.md b/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space/Readme.md new file mode 100644 index 000000000..e5e8fb12b --- /dev/null +++ b/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space/Readme.md @@ -0,0 +1,42 @@ +2459.Sort-Array-by-Moving-Items-to-Empty-Space + +首先,我们发现,无论最终是要把0放在首位还是末位,都不影响操作的本质。对于后者,如果我们将nums的最后一个元素虚拟地认为是在head的位置,那么操作的方法完全可以与前者归并处理。即 +```cpp + vectornums2(nums.begin(), nums.end()-1); + nums2.insert(nums2.begin(), nums.back()); + return min(helper(nums), helper(nums2)); +``` + +其次,我们考虑如何实现上述的helper函数,即将nums里的元素排序为0,1,2,...,n-1. + +我们容易想到贪心的策略:如果当前的0在位置i且i!=0,那么我们必然将i拿过来交换一次使之归位。然后继续看此时0所在的位置j,如果仍然j!=0,那么同样必然把j拿过来使之归位。接着继续查看0,直至0到了队首。我们发现,可以用k次操作,将k+1个元素(包括0)归到正确的位置。这k+1个元素本质上val-index构成了一个环。 + +其实有另外一种等效的归位操作,我们称之为index sort:只盯着index=0上的数i,如果它不是0,那么就把它与nums[i]交换使得i归位;再看此时index=0上的数j,如果它还不是0,继续将其与nums[j]交换使得j归位。直至index=0上的数变成0. 同样的结论:如果交换了k次,意味着我们已经将k+1个元素(包括0)归到正确的位置。 + +接下来我们看其他的位置。如果某个位置i上的数字不是i,我们同样用上面的方法,通过若干次交换使得位置i上得到i。例如: +``` +idx: 1 2 3 +val: 3 1 2 +``` +第一次操作后: +``` +idx: 1 2 3 +val: 2 1 3 +``` +第二次操作后: +``` +idx: 1 2 3 +val: 1 2 3 +``` + +但是注意到这两次操作我们都没有利用到0,这是不符合要求的。那么该如何通过0来实现呢?其实只要开头增加一步,将之前已经归位的0与位置1上的元素再交换,即额外增加了一个没有归位的0: +``` +idx: 0 1 2 3 +val: 3 0 1 2 +``` +我们发现此时val-index的环上有四个元素了,同上的理论,我们只需要做三次index sort就能将这四个元素归位。加上之前额外的一次操作,总共是四次。 + +于是得出结论:如果某个非0的位置i上的数字不是i,并且通过k次交换(index sort)可以使得位置i上出现i的话,那么实际上借助0的话,我们需要k+2次交换(index sort)来实现。 + +综上:我们对每个位置i尝试index sort,假设k次操作后能够将数值i出现在位置i上,那么(1) 如果i是0,我们就将总操作数增加k;(2)如果i不是0,我们将总操作数增加k+2. + From d50c103cf0a78918aafac3c37ab98e21b6f15b3b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 18:05:34 -0800 Subject: [PATCH 1467/2729] Create 2516.Take-K-of-Each-Character-From-Left-and-Right_v1.cpp --- ...-Each-Character-From-Left-and-Right_v1.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v1.cpp diff --git a/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v1.cpp b/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v1.cpp new file mode 100644 index 000000000..2c90505a2 --- /dev/null +++ b/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v1.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int takeCharacters(string s, int k) + { + int n = s.size(); + int a = 0, b = 0, c = 0; + for (int i=0; i=len) + { + if (s[i-len]=='a') a--; + else if (s[i-len]=='b') b--; + else if (s[i-len]=='c') c--; + } + + if (i>=len-1) + { + if (a<=A && b<=B && c<=C) + return true; + } + } + return false; + } +}; From 5a55b5b5328036a5467a44c5f75fef491eb7000c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 18:06:01 -0800 Subject: [PATCH 1468/2729] Create 2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp --- ...-Each-Character-From-Left-and-Right_v2.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp diff --git a/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp b/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp new file mode 100644 index 000000000..fa4776024 --- /dev/null +++ b/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int takeCharacters(string s, int k) + { + if (k==0) return 0; + + int a = 0, b = 0, c = 0; + for (auto ch: s) + { + if (ch=='a') a++; + else if (ch=='b') b++; + else if (ch=='c') c++; + } + if (a=k && b>=k && c>=k) + ret = min(ret, n-1-i+j); + } + + return ret; + } +}; From 1460892208fd7d1e33c8e26861f74b6fa499ea33 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 18:06:31 -0800 Subject: [PATCH 1469/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 948121f48..446257fd7 100644 --- a/Readme.md +++ b/Readme.md @@ -46,7 +46,8 @@ [424.Longest-Repeating-Character-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/424.Longest-Repeating-Character-Replacement) (H-) [2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) [2401.Longest-Nice-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2401.Longest-Nice-Subarray) (H-) -[2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) +[2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) +[2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From df0a7aad47bd7407dd4cd40b20166387bf347720 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 18:06:56 -0800 Subject: [PATCH 1470/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 446257fd7..b4b6818e8 100644 --- a/Readme.md +++ b/Readme.md @@ -46,7 +46,7 @@ [424.Longest-Repeating-Character-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/424.Longest-Repeating-Character-Replacement) (H-) [2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) [2401.Longest-Nice-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2401.Longest-Nice-Subarray) (H-) -[2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) +[2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) [2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) From a82f7501466866fe9c46f72b5e8007e4e323d93c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 18:24:54 -0800 Subject: [PATCH 1471/2729] Update 2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp --- ...-Each-Character-From-Left-and-Right_v2.cpp | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp b/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp index fa4776024..b5ce392ec 100644 --- a/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp +++ b/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/2516.Take-K-of-Each-Character-From-Left-and-Right_v2.cpp @@ -2,37 +2,41 @@ class Solution { public: int takeCharacters(string s, int k) { - if (k==0) return 0; - int a = 0, b = 0, c = 0; + int A = 0, B = 0, C = 0; for (auto ch: s) { - if (ch=='a') a++; - else if (ch=='b') b++; - else if (ch=='c') c++; + if (ch=='a') A++; + else if (ch=='b') B++; + else if (ch=='c') C++; } - if (a=k && b>=k && c>=k) - ret = min(ret, n-1-i+j); + + if (s[i]=='a') a--; + else if (s[i]=='b') b--; + else if (s[i]=='c') c--; } - return ret; + return n - ret; } }; From d79806eacbbd890fb9de23b55806c40892586aba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 18:30:23 -0800 Subject: [PATCH 1472/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/Readme.md diff --git a/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/Readme.md b/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/Readme.md new file mode 100644 index 000000000..64b1abec8 --- /dev/null +++ b/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right/Readme.md @@ -0,0 +1,7 @@ +### 2516.Take-K-of-Each-Character-From-Left-and-Right + +#### 解法1:二分搜值 +从题意转换一下,我们可以知道,题目需要找中间一段符合条件的最长滑窗,使得里面a、b、c的个数分别不能多于各自的阈值A,B,C。我们可以二分猜值,假设滑窗长度是k,在数组上找一遍是否凑存在某个长度固定为k的滑窗满足上述关系。如果有的话,那么继续增大滑窗长度,否则就减小滑窗长度。 + +#### 解法2:滑窗 +如果我们固定左端点i,那么可以找到最远的右端点j使得满足滑窗里面a、b、c的个数分别不能多于各自的阈值A,B,C。此时我们再右移左端点i一步,abc可能会减少某个元素从而不再逼近阈值,这样右端点就有可能继续松弛往右前进,找到以新左端点对应的最长滑窗。以此类推,我们可以找到每个位置作为左端点的最长滑窗。最终答案就是n减去最大滑窗长度。 From 02c917a52e51dc7786c5c1ab8306f4d7c065f22c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 18:30:39 -0800 Subject: [PATCH 1473/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b4b6818e8..201cec7ef 100644 --- a/Readme.md +++ b/Readme.md @@ -47,7 +47,7 @@ [2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2106.Maximum-Fruits-Harvested-After-at-Most-K-Steps) (H) [2401.Longest-Nice-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2401.Longest-Nice-Subarray) (H-) [2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) -[2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (H-) +[2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 1ff9ec9e062a23adbd4795c9400fd15c343c13ac Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Dec 2022 22:59:00 -0800 Subject: [PATCH 1474/2729] Update 879.Profitable-Schemes.cpp --- .../879.Profitable-Schemes.cpp | 48 ++++++++----------- 1 file changed, 21 insertions(+), 27 deletions(-) diff --git a/Dynamic_Programming/879.Profitable-Schemes/879.Profitable-Schemes.cpp b/Dynamic_Programming/879.Profitable-Schemes/879.Profitable-Schemes.cpp index 61bdc8247..92a2bd443 100644 --- a/Dynamic_Programming/879.Profitable-Schemes/879.Profitable-Schemes.cpp +++ b/Dynamic_Programming/879.Profitable-Schemes/879.Profitable-Schemes.cpp @@ -1,40 +1,34 @@ class Solution { + int dp[105][105][105]; + int M = 1e9+7; public: - int profitableSchemes(int G, int P, vector& group, vector& profit) + int profitableSchemes(int n, int minProfit, vector& group, vector& profit) { - auto dp = vector>(G+1, vector(P+1,0)); - int M = 1e9+7; + dp[0][0][0] = 1; + + int m = group.size(); + group.insert(group.begin(), 0); + profit.insert(profit.begin(), 0); - dp[0][0] = 1; - - auto dp_new = dp; - - for (int k=0; k Date: Mon, 26 Dec 2022 23:15:15 -0800 Subject: [PATCH 1475/2729] Update Readme.md --- .../879.Profitable-Schemes/Readme.md | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/879.Profitable-Schemes/Readme.md b/Dynamic_Programming/879.Profitable-Schemes/Readme.md index 910333936..fdc785af1 100644 --- a/Dynamic_Programming/879.Profitable-Schemes/Readme.md +++ b/Dynamic_Programming/879.Profitable-Schemes/Readme.md @@ -1,10 +1,24 @@ ### 879.Profitable-Schemes -非常常规的DP题。设计状态变量dp[person][profit]表示:恰好用person个人力、并恰好达到profit的利润的方案数。我们遍历所有的project,根据这个project来更新dp状态。基本的状态转移方程是:对于一个project (x,y),我们有```dp[person+x][profit+y] += dp[person][profit]```。 +我们很容易设计状态变量dp[i][person][profit]来表示在前i个项目中,恰好用person个人力、并恰好达到profit的利润的方案数。 -需要注意的技巧。我们不需要对于利润大于P的dp开辟更多空间,即dp的第二个维度开到P就可以了。这是因为对于利润是P,P+1...P+M的情况,对于我们都没有区别(我们只在乎他们的总和),并且以后我们不会用这些状态给别的状态赋值。所以,我们把利润大于P的状态,都会累加进状态dp[person][P]里面去。 +常规的状态转移方程会长得像这样:考虑第i个项目(人力是x,利润是y)是否实施两种情况 +```cpp +dp[i][person][profit] = dp[i-1][person][profit] + dp[i-1][person-x][profit-y] +``` -因此最后的结果应该是 ```sum{dp[i][P]} over i=1,2,...,G```,其中P特殊地用来表示P及P以上的利润。 +但是这里有个问题。dp的第三个维度需要遍历的范围太大,达到100*100=1e4,那么整个dp的空间就太大了。我们容易发现,第三个维度其实只要开到minProfit就可以了,对于`profit = minProfit, minProfit+1, minProfit+2 ... `我们不关心它们各自的dp值,我们只在乎他们的总和。所以我们可以将这些dp值都累加存放在dp[i][person][minProfit]里。 +但是这里就又出现了一个问题,当你profit遍历到minProfit时,上述的状态转移方程就不成立了。因为minProfit其实不代表了利润恰好是它,而是代表了所有大于等于它的利润。此时你再从`dp[i-1][person-x][profit-y]`转移而来就没有道理。所以我们不能用这种传统的状态转移方法。 -[Leetcode Link](https://leetcode.com/problems/profitable-schemes) \ No newline at end of file +传统的状态转移方法:根据以往的dp求dp[i]。逆向的状态转移方法:根据当前已知的dp[i],推出对今后dp值的影响。 + +在本题中,我们假设已知`dp[i][person][profit]`,那么我们可以推测对i+1的影响: +```cpp +dp[i+1][j][p] += dp[i][j][p]; +dp[i+1][j+group[i+1]][min(minProfit, p+profit[i+1])] += dp[i][j][p]; +``` + +最终答案就是sum{dp[m][j][minProfit]},其中j=0,1,2...,n + +[Leetcode Link](https://leetcode.com/problems/profitable-schemes) From 0a5f33d7dd996e9e3e5c47c2debba92aeeacfaba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 00:33:23 -0800 Subject: [PATCH 1476/2729] Update 416.Partition-Equal-Subset-Sum_v2.cpp --- .../416.Partition-Equal-Subset-Sum_v2.cpp | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_v2.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_v2.cpp index e1111d020..c4f3c33a4 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_v2.cpp +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_v2.cpp @@ -1,24 +1,23 @@ class Solution { + int dp[205][20005]; public: bool canPartition(vector& nums) { - int sum = accumulate(nums.begin(),nums.end(),0); + int sum = accumulate(nums.begin(), nums.end(), 0); if (sum%2!=0) return false; - - unordered_setdp; - dp.insert(0); - for (auto x: nums) - { - vectortemp; - for (auto s: dp) + int n = nums.size(); + nums.insert(nums.begin(), 0); + + dp[0][0] = 1; + for (int i=1; i<=n; i++) + for (int s = 0; s<=sum/2; s++) { - if (s+x==sum/2) return true; - temp.push_back(s+x); + dp[i][s] |= dp[i-1][s]; + if (s>=nums[i]) + dp[i][s] |= dp[i-1][s-nums[i]]; } - for (auto a: temp) - dp.insert(a); - } - return false; + + return dp[n][sum/2]; } }; From 03e37c84ed4ca8b2ccbeac27f3ca575439229d8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 00:35:47 -0800 Subject: [PATCH 1477/2729] Update and rename 416.Partition-Equal-Subset-Sum_v3.cpp to 416.Partition-Equal-Subset-Sum_dp_v3.cpp --- .../416.Partition-Equal-Subset-Sum_dp_v3.cpp | 25 +++++++++++++++++++ .../416.Partition-Equal-Subset-Sum_v3.cpp | 22 ---------------- 2 files changed, 25 insertions(+), 22 deletions(-) create mode 100644 Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v3.cpp delete mode 100644 Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_v3.cpp diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v3.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v3.cpp new file mode 100644 index 000000000..0b03ab57a --- /dev/null +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v3.cpp @@ -0,0 +1,25 @@ +class Solution { + int dp[205][20005]; +public: + bool canPartition(vector& nums) + { + int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum%2!=0) return false; + + int n = nums.size(); + nums.insert(nums.begin(), 0); + + dp[0][0] = 1; + for (int i=0; i& nums) - { - int sum = accumulate(nums.begin(),nums.end(),0); - if (sum%2!=0) return false; - - vectordp(sum/2+1,0); - dp[0] = true; - - for (auto x: nums) - { - for (int s = sum/2; s>=0; s--) - { - if (dp[s]==false) continue; - if (s+x<=sum/2) - dp[s+x] = true; - } - } - return dp[sum/2]; - } -}; From 1b23f04468e1946a42f2de194a2d6fa2d390b212 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 00:35:59 -0800 Subject: [PATCH 1478/2729] Rename 416.Partition-Equal-Subset-Sum_v2.cpp to 416.Partition-Equal-Subset-Sum_dp_v2.cpp --- ...Subset-Sum_v2.cpp => 416.Partition-Equal-Subset-Sum_dp_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/416.Partition-Equal-Subset-Sum/{416.Partition-Equal-Subset-Sum_v2.cpp => 416.Partition-Equal-Subset-Sum_dp_v2.cpp} (100%) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_v2.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp similarity index 100% rename from Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_v2.cpp rename to Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp From fb91bb5c22fc6cd202f6fd4871f046aa9d6c63e5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 00:37:14 -0800 Subject: [PATCH 1479/2729] Update 416.Partition-Equal-Subset-Sum_dp_v2.cpp --- .../416.Partition-Equal-Subset-Sum_dp_v2.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp index c4f3c33a4..eb4d9ca7d 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp @@ -13,9 +13,7 @@ class Solution { for (int i=1; i<=n; i++) for (int s = 0; s<=sum/2; s++) { - dp[i][s] |= dp[i-1][s]; - if (s>=nums[i]) - dp[i][s] |= dp[i-1][s-nums[i]]; + dp[i][s] = dp[i-1][s] || (s>=snums[i] && dp[i-1][s-nums[i]]); } return dp[n][sum/2]; From cbf9b82b2aea9d0ec72e35570d907dbb229b8190 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 00:37:45 -0800 Subject: [PATCH 1480/2729] Update 416.Partition-Equal-Subset-Sum_dp_v2.cpp --- .../416.Partition-Equal-Subset-Sum_dp_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp index eb4d9ca7d..9463455f2 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dp_v2.cpp @@ -13,7 +13,7 @@ class Solution { for (int i=1; i<=n; i++) for (int s = 0; s<=sum/2; s++) { - dp[i][s] = dp[i-1][s] || (s>=snums[i] && dp[i-1][s-nums[i]]); + dp[i][s] = dp[i-1][s] || (s>=nums[i] && dp[i-1][s-nums[i]]); } return dp[n][sum/2]; From 7fdc6c8f0da7e80fb8adfd15c0cd944de1772bdd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 00:42:22 -0800 Subject: [PATCH 1481/2729] Update Readme.md --- .../416.Partition-Equal-Subset-Sum/Readme.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md index 2039724c2..82fdea751 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md @@ -5,18 +5,19 @@ 于是我们可以换一个“答案空间”去切入,那就是用背包问题的想法。DFS的解法其实是寻找在一个N维空间上搜索答案(1,0,0,....,0,1,1),其中0/1表示该数字我们是否选择。显然这个空间的候选数目的order达到了指数级别。“背包问题”就是改变解答空间,思考如果我们构建任意和为s的subset的话,是否能够实现目标。对于s而言,它的范围是从0到nums.size()*nums[i]=2e4. 这个空间是大大缩小的了。举个例子,假如dp[10]=true表示我们可以选择一部分数字加起来是10,那么我们试图思考,我们能否利用这部分数字再加上一些其他数字,使得总和是20呢?也就是说,我们能否通过dp[10]=true来帮助判断dp[20]=true呢? 这就是01背包问题的基本思想。如果dp的空间大小合理,那么我们就可以来解决之前DFS所无法处理的复杂度。基本的模板如下: -``` -for (auto x: nums) // 遍历物品 - for (auto s= sum/2 to 0) // 遍历容量 - if dp'[s-x] = true +```cpp +for (int i=0; i Date: Tue, 27 Dec 2022 00:43:04 -0800 Subject: [PATCH 1482/2729] Update Readme.md --- .../416.Partition-Equal-Subset-Sum/Readme.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md index 82fdea751..6240ed850 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md @@ -2,22 +2,21 @@ 本题是个NP问题。可以采用DFS的方法来暴力枚举,虽然可以利用各种剪枝优化的手段,但根本的时间复杂度仍然是o(2^N)。早期的时候DFS的版本是可以AC的,但是最近被TLE了。 -于是我们可以换一个“答案空间”去切入,那就是用背包问题的想法。DFS的解法其实是寻找在一个N维空间上搜索答案(1,0,0,....,0,1,1),其中0/1表示该数字我们是否选择。显然这个空间的候选数目的order达到了指数级别。“背包问题”就是改变解答空间,思考如果我们构建任意和为s的subset的话,是否能够实现目标。对于s而言,它的范围是从0到nums.size()*nums[i]=2e4. 这个空间是大大缩小的了。举个例子,假如dp[10]=true表示我们可以选择一部分数字加起来是10,那么我们试图思考,我们能否利用这部分数字再加上一些其他数字,使得总和是20呢?也就是说,我们能否通过dp[10]=true来帮助判断dp[20]=true呢? +于是我们可以换一个“答案空间”去切入,那就是用背包问题的想法。DFS的解法其实是寻找在一个N维空间上搜索答案(1,0,0,....,0,1,1),其中0/1表示该数字我们是否选择。显然这个空间的候选数目的order达到了指数级别。“背包问题”就是改变解答空间,思考如果我们构建任意和为s的subset的话,是否能够实现目标。对于s而言,它的范围是从0到`nums.size()*nums[i]=2e4`. 这个空间是大大缩小的了。举个例子,假如dp[10]=true表示我们可以选择一部分数字加起来是10,那么我们试图思考,我们能否利用这部分数字再加上一些其他数字,使得总和是20呢?也就是说,我们能否通过dp[10]=true来帮助判断dp[20]=true呢? 这就是01背包问题的基本思想。如果dp的空间大小合理,那么我们就可以来解决之前DFS所无法处理的复杂度。基本的模板如下: ```cpp for (int i=0; i Date: Tue, 27 Dec 2022 01:15:17 -0800 Subject: [PATCH 1483/2729] Update Readme.md --- Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md index 6240ed850..a715bc6fe 100644 --- a/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md +++ b/Dynamic_Programming/416.Partition-Equal-Subset-Sum/Readme.md @@ -8,7 +8,7 @@ ```cpp for (int i=0; i Date: Tue, 27 Dec 2022 11:19:21 -0800 Subject: [PATCH 1484/2729] Create 2464.Minimum-Subarrays-in-a-Valid-Split.cpp --- ...464.Minimum-Subarrays-in-a-Valid-Split.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split/2464.Minimum-Subarrays-in-a-Valid-Split.cpp diff --git a/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split/2464.Minimum-Subarrays-in-a-Valid-Split.cpp b/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split/2464.Minimum-Subarrays-in-a-Valid-Split.cpp new file mode 100644 index 000000000..be2439940 --- /dev/null +++ b/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split/2464.Minimum-Subarrays-in-a-Valid-Split.cpp @@ -0,0 +1,19 @@ +class Solution { + int dp[1005]; +public: + int validSubarraySplit(vector& nums) + { + memset(dp, 0x3f, sizeof(dp)); + int n = nums.size(); + for (int i=0; i1) + dp[i] = min(dp[i], j==0?1:(dp[j-1]+1)); + } + + if (dp[n-1]==0x3f3f3f3f) + return -1; + return dp[n-1]; + } +}; From 11732746c4d07428baef16cfa7cd678358e75f38 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 11:26:21 -0800 Subject: [PATCH 1485/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 201cec7ef..c1033a3b0 100644 --- a/Readme.md +++ b/Readme.md @@ -706,6 +706,7 @@ [2188.Minimum-Time-to-Finish-the-Race](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2188.Minimum-Time-to-Finish-the-Race) (H-) [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) [2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) +[2464.Minimum-Subarrays-in-a-Valid-Split](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split) (M) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) From 0e39231c47788bc30548505f5cca96fa06d97974 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 11:30:40 -0800 Subject: [PATCH 1486/2729] Create Readme.md --- .../2464.Minimum-Subarrays-in-a-Valid-Split/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split/Readme.md diff --git a/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split/Readme.md b/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split/Readme.md new file mode 100644 index 000000000..c3de6598f --- /dev/null +++ b/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split/Readme.md @@ -0,0 +1,3 @@ +### 2464.Minimum-Subarrays-in-a-Valid-Split + +本题包装着数论问题,但本质其实就是一个基础型的dp。根据数据范围,o(N^2)的复杂度可解,因此遍历最后一段subarray的范围即可。 From eee79b79c299c0bd599cf5c5a31a50b7826d4dc0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 18:06:19 -0800 Subject: [PATCH 1487/2729] Create 2473.Minimum-Cost-to-Buy-Apples.cpp --- .../2473.Minimum-Cost-to-Buy-Apples.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 BFS/2473.Minimum-Cost-to-Buy-Apples/2473.Minimum-Cost-to-Buy-Apples.cpp diff --git a/BFS/2473.Minimum-Cost-to-Buy-Apples/2473.Minimum-Cost-to-Buy-Apples.cpp b/BFS/2473.Minimum-Cost-to-Buy-Apples/2473.Minimum-Cost-to-Buy-Apples.cpp new file mode 100644 index 000000000..8cff24f9e --- /dev/null +++ b/BFS/2473.Minimum-Cost-to-Buy-Apples/2473.Minimum-Cost-to-Buy-Apples.cpp @@ -0,0 +1,44 @@ +using LL = long long; +using PII = pair; +class Solution { + vectornext[1005]; +public: + vector minCost(int n, vector>& roads, vector& appleCost, int k) + { + for (auto& road: roads) + { + int a = road[0], b = road[1], c = road[2]; + next[a].push_back({b,c}); + next[b].push_back({a,c}); + } + + vectorrets; + for (int i=1; i<=n; i++) + { + priority_queue, greater<>>pq; + pq.push({0, i}); + vectorvisited(n+1, -1); + while (!pq.empty()) + { + auto [dist, cur] = pq.top(); + pq.pop(); + if (visited[cur] == -1) + visited[cur] = dist; + + for (auto [nxt, len]: next[cur]) + { + if (visited[nxt]!=-1) continue; + pq.push({dist + len*(1+k), nxt}); + } + } + + LL ret = LLONG_MAX; + for (int i=1; i<=n; i++) + if (visited[i]!=-1) + ret = min(ret, appleCost[i-1]+visited[i]); + rets.push_back(ret); + } + + return rets; + } +}; From 8944615118e69ad94f4d814d4e5d0f3d8db99f62 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 18:06:49 -0800 Subject: [PATCH 1488/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c1033a3b0..abd369c8b 100644 --- a/Readme.md +++ b/Readme.md @@ -565,6 +565,7 @@ [1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (M+) [2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) +[2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From 1881f70d87ef1beaeaf59795c07d797196a50c47 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 18:07:31 -0800 Subject: [PATCH 1489/2729] Create Readme.md --- BFS/2473.Minimum-Cost-to-Buy-Apples/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 BFS/2473.Minimum-Cost-to-Buy-Apples/Readme.md diff --git a/BFS/2473.Minimum-Cost-to-Buy-Apples/Readme.md b/BFS/2473.Minimum-Cost-to-Buy-Apples/Readme.md new file mode 100644 index 000000000..051cb149a --- /dev/null +++ b/BFS/2473.Minimum-Cost-to-Buy-Apples/Readme.md @@ -0,0 +1,3 @@ +### 2473.Minimum-Cost-to-Buy-Apples + +无脑对每个起点都做一遍Dijkstra找到所有位置的最短路径即可。 From 2ae51f8ef0826e3dfbd5a501e8097afdf91f0292 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 23:20:04 -0800 Subject: [PATCH 1490/2729] Create 2517.Maximum-Tastiness-of-Candy-Basket.cpp --- ...2517.Maximum-Tastiness-of-Candy-Basket.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket/2517.Maximum-Tastiness-of-Candy-Basket.cpp diff --git a/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket/2517.Maximum-Tastiness-of-Candy-Basket.cpp b/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket/2517.Maximum-Tastiness-of-Candy-Basket.cpp new file mode 100644 index 000000000..d15ffb14c --- /dev/null +++ b/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket/2517.Maximum-Tastiness-of-Candy-Basket.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int maximumTastiness(vector& price, int k) + { + sort(price.begin(), price.end()); + + int left = 0, right = INT_MAX/2; + while (left < right) + { + int mid = right - (right-left)/2; + if (isOK(price, mid, k)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool isOK(vector& price, int diff, int k) + { + int count = 1; + for (int i=0; i= k) return true; + } + + return false; + + } +}; From 4b40bc363e4427ef77c683c1765b07ebeb9e6bd1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 23:20:29 -0800 Subject: [PATCH 1491/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index abd369c8b..40dfb0b34 100644 --- a/Readme.md +++ b/Readme.md @@ -116,6 +116,7 @@ [2141.Maximum-Running-Time-of-N-Computers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2141.Maximum-Running-Time-of-N-Computers) (M+) [2226.Maximum-Candies-Allocated-to-K-Children](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children) (M) [2439.Minimize-Maximum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2439.Minimize-Maximum-of-Array) (H-) +[2517.Maximum-Tastiness-of-Candy-Basket](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket) (M+) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 4594218a8007537f69204af0d139b64c06039653 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 27 Dec 2022 23:34:43 -0800 Subject: [PATCH 1492/2729] Create Readme.md --- .../2517.Maximum-Tastiness-of-Candy-Basket/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket/Readme.md diff --git a/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket/Readme.md b/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket/Readme.md new file mode 100644 index 000000000..8a7db0d39 --- /dev/null +++ b/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket/Readme.md @@ -0,0 +1,5 @@ +### 2517.Maximum-Tastiness-of-Candy-Basket + +很明显我们会将price排序,此时“最小的间隔”必然是某两个连续选取的元素(不见得是相邻的)之差。此时,为了最大化这个间隔,我们需要在这个有序数组里跳跃着取数,但是又不能跨越得太大,否则无法凑齐k个元素。 + +对于这种题目,二分搜值是非常常见的手段。我们猜测一个跨度d,必然会从第一个元素开始选起(尽可能地拉低下限),找到下一个跨度与之恰好大于d的元素,再找一下,直至看是否能够选到k个元素。可以的话,就试图增加d,否则就减小d。 From feb52a0eab84ce5aa63d609e0095f95157d5a1fc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 28 Dec 2022 22:48:51 -0800 Subject: [PATCH 1493/2729] Create 2513.Minimize-the-Maximum-of-Two-Arrays.cpp --- ...513.Minimize-the-Maximum-of-Two-Arrays.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/2513.Minimize-the-Maximum-of-Two-Arrays.cpp diff --git a/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/2513.Minimize-the-Maximum-of-Two-Arrays.cpp b/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/2513.Minimize-the-Maximum-of-Two-Arrays.cpp new file mode 100644 index 000000000..8cc6560e8 --- /dev/null +++ b/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/2513.Minimize-the-Maximum-of-Two-Arrays.cpp @@ -0,0 +1,29 @@ +using LL = long long; +class Solution { +public: + int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) + { + LL left = 1, right = LLONG_MAX/2; + while (left < right) + { + LL mid = left + (right-left)/2; + if (NotEnough(divisor1, divisor2, uniqueCnt1, uniqueCnt2, mid)) + left = mid+1; + else + right = mid; + } + return left; + } + + bool NotEnough(LL divisor1, LL divisor2, LL uniqueCnt1, LL uniqueCnt2, LL n) + { + LL a = n - n/divisor1; + LL b = n - n/divisor2; + LL c = n - (n/divisor1 + n/divisor2 - n/lcm(divisor1,divisor2)); + + if (a < uniqueCnt1) return true; + if (b < uniqueCnt2) return true; + if (a+b-c < uniqueCnt1 + uniqueCnt2) return true; + return false; + } +}; From da0f3352b21004010b092b1100e32525414c1090 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 28 Dec 2022 22:49:20 -0800 Subject: [PATCH 1494/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 40dfb0b34..aa946f02c 100644 --- a/Readme.md +++ b/Readme.md @@ -117,6 +117,7 @@ [2226.Maximum-Candies-Allocated-to-K-Children](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2226.Maximum-Candies-Allocated-to-K-Children) (M) [2439.Minimize-Maximum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2439.Minimize-Maximum-of-Array) (H-) [2517.Maximum-Tastiness-of-Candy-Basket](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket) (M+) +[2513.Minimize-the-Maximum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays) (H) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 5c82cff87314284e4494ae9528807f8244c56ac4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 00:09:33 -0800 Subject: [PATCH 1495/2729] Create Readme.md --- .../2513.Minimize-the-Maximum-of-Two-Arrays/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/Readme.md diff --git a/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/Readme.md b/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/Readme.md new file mode 100644 index 000000000..74a4560f1 --- /dev/null +++ b/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/Readme.md @@ -0,0 +1,11 @@ +### 2513.Minimize-the-Maximum-of-Two-Arrays + +本题如果直接去构造填充这两个数组的话,效率肯定非常低。于是反向思考是否能用二分搜值的方法。 + +假设这个最大值是n,那么我们可以计算出最多有a个元素可以放在集合A里(即不能被d1整除的元素),`a = n - n/d1`。同理,我们可以计算出最多有b个元素可以放在集合B里,`b = n - n/d2`. + +另外,我们知道有一些数字可以既在集合A里,也可以在集合B里(即既不能被d1整除,也不能被d2整除)。这部分数字的个数是n减去“能被d1或者d2整除的个数”。后者的计算方法用到容斥原理:`n/d1 + n/d2 - n / LCM(d1,d2)`. 所以我们记`c = n - (n/d1 + n/d2 - n/ LCM(d1,d2)`. + +接下来,我们考虑如果`a < uniqueCnt1`,那么意味着无法构造足够的元素装满A,说明n太小。同理,如果`b < uniqueCnt2`,那么意味着无法构造足够的元素装满B,也说明n太小。那么有人会问,如果`a >= uniqueCnt1 && b >= uniqueCnt2`,是不是意味着构造了太多的元素了呢?并不是,因为a和b有部分是重合的,其中有c的部分是可以在A与B之间自由调剂的,但是只能出现在A或B中的一个。所以实际可以构造的总数是`a+b-c`,如果`a+b-c < uniqueCnt1+uniqueCnt2`的话,那说明n太小了。 + +以上就是三个判定n太小(可构造的数字不够)的判据。以此我们可以二分搜索得到最小的n,使得恰好以上三个判据都不满足。 From b4b278dcdfad3078e226fc23ebb794c66d4ca3ec Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 00:37:04 -0800 Subject: [PATCH 1496/2729] Update 2513.Minimize-the-Maximum-of-Two-Arrays.cpp --- .../2513.Minimize-the-Maximum-of-Two-Arrays.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/2513.Minimize-the-Maximum-of-Two-Arrays.cpp b/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/2513.Minimize-the-Maximum-of-Two-Arrays.cpp index 8cc6560e8..a43994c05 100644 --- a/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/2513.Minimize-the-Maximum-of-Two-Arrays.cpp +++ b/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays/2513.Minimize-the-Maximum-of-Two-Arrays.cpp @@ -3,7 +3,7 @@ class Solution { public: int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) { - LL left = 1, right = LLONG_MAX/2; + LL left = 1, right = INT_MAX; while (left < right) { LL mid = left + (right-left)/2; From 96c73535031ea8b39c386cf8460f135150f50826 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 00:43:08 -0800 Subject: [PATCH 1497/2729] Create 2509.Cycle-Length-Queries-in-a-Tree.cpp --- .../2509.Cycle-Length-Queries-in-a-Tree.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Tree/2509.Cycle-Length-Queries-in-a-Tree/2509.Cycle-Length-Queries-in-a-Tree.cpp diff --git a/Tree/2509.Cycle-Length-Queries-in-a-Tree/2509.Cycle-Length-Queries-in-a-Tree.cpp b/Tree/2509.Cycle-Length-Queries-in-a-Tree/2509.Cycle-Length-Queries-in-a-Tree.cpp new file mode 100644 index 000000000..4e37a85fd --- /dev/null +++ b/Tree/2509.Cycle-Length-Queries-in-a-Tree/2509.Cycle-Length-Queries-in-a-Tree.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector cycleLengthQueries(int n, vector>& queries) + { + vectorrets; + for (auto& q: queries) + { + int a = q[0], b = q[1]; + int count = 0; + while (a!=b) + { + if (a>b) + a = a/2; + else + b = b/2; + count++; + } + rets.push_back(count+1); + } + return rets; + + } +}; From 07fd6249259f3226029e68dfaa6f32e6d9ef62f4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 00:43:38 -0800 Subject: [PATCH 1498/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index aa946f02c..6fe813fb8 100644 --- a/Readme.md +++ b/Readme.md @@ -277,6 +277,7 @@ [1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1650.Lowest-Common-Ancestor-of-a-Binary-Tree-III) (M) [1740.Find-Distance-in-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1740.Find-Distance-in-a-Binary-Tree) (H) [2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another) (M+) +[2509.Cycle-Length-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2509.Cycle-Length-Queries-in-a-Tree) (M) * ``N-ary Tree`` [428.Serialize-and-Deserialize-N-ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/428.Serialize-and-Deserialize-N-ary-Tree) (H) [431.Encode-N-ary-Tree-to-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/431.Encode-N-ary-Tree-to-Binary-Tree) (H-) From 5490a61f448030fa01233c8a8d67aff05c2b00b0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 00:48:22 -0800 Subject: [PATCH 1499/2729] Create Readme.md --- Tree/2509.Cycle-Length-Queries-in-a-Tree/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Tree/2509.Cycle-Length-Queries-in-a-Tree/Readme.md diff --git a/Tree/2509.Cycle-Length-Queries-in-a-Tree/Readme.md b/Tree/2509.Cycle-Length-Queries-in-a-Tree/Readme.md new file mode 100644 index 000000000..4ae71cbd3 --- /dev/null +++ b/Tree/2509.Cycle-Length-Queries-in-a-Tree/Readme.md @@ -0,0 +1,3 @@ +### 2509.Cycle-Length-Queries-in-a-Tree + +此题的本质就是找lowest common ancestor。本题的特殊之处在于每个节点指向其parent的路径其实非常简洁:val->val/2,数值是单调递减的。所以我们对于任意两个节点a和b,只要每次将其中的较小值减半,就一定最终让两者收敛一致,即LCA。减半操作的次数就是cycle的长度。 From cabb87f6f146919fa3169fb7a4a712f76ff357cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 16:00:45 -0800 Subject: [PATCH 1500/2729] Create 2489.Number-of-Substrings-With-Fixed-Ratio.cpp --- ....Number-of-Substrings-With-Fixed-Ratio.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Hash/2489.Number-of-Substrings-With-Fixed-Ratio/2489.Number-of-Substrings-With-Fixed-Ratio.cpp diff --git a/Hash/2489.Number-of-Substrings-With-Fixed-Ratio/2489.Number-of-Substrings-With-Fixed-Ratio.cpp b/Hash/2489.Number-of-Substrings-With-Fixed-Ratio/2489.Number-of-Substrings-With-Fixed-Ratio.cpp new file mode 100644 index 000000000..b29c51760 --- /dev/null +++ b/Hash/2489.Number-of-Substrings-With-Fixed-Ratio/2489.Number-of-Substrings-With-Fixed-Ratio.cpp @@ -0,0 +1,26 @@ +using LL = long long; +class Solution { + map, int>Map; +public: + long long fixedRatio(string s, int num1, int num2) + { + Map[{0,0}] = 1; + LL a = 0, b = 0; + LL ret = 0; + for (auto ch: s) + { + if (ch=='0') a++; + else b++; + + LL k = min(a/num1, b/num2); + LL x = a-k*num1, y = b-k*num2; + + if (Map.find({x,y})!=Map.end()) + ret += Map[{x,y}]; + + Map[{x,y}] += 1; + } + + return ret; + } +}; From c11858aad20e3fc45e53007c4775354dd97e1c13 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 16:02:08 -0800 Subject: [PATCH 1501/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6fe813fb8..f62217159 100644 --- a/Readme.md +++ b/Readme.md @@ -173,6 +173,7 @@ [1915.Number-of-Wonderful-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/1915.Number-of-Wonderful-Substrings) (M+) [2025.Maximum-Number-of-Ways-to-Partition-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array) (H) [2488.Count-Subarrays-With-Median-K](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2488.Count-Subarrays-With-Median-K) (H-) +[2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From afe16e6a8a0b0faf969d30ca1bac411c5ccc3b0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 16:17:17 -0800 Subject: [PATCH 1502/2729] Create Readme.md --- .../2489.Number-of-Substrings-With-Fixed-Ratio/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hash/2489.Number-of-Substrings-With-Fixed-Ratio/Readme.md diff --git a/Hash/2489.Number-of-Substrings-With-Fixed-Ratio/Readme.md b/Hash/2489.Number-of-Substrings-With-Fixed-Ratio/Readme.md new file mode 100644 index 000000000..e0d2a9144 --- /dev/null +++ b/Hash/2489.Number-of-Substrings-With-Fixed-Ratio/Readme.md @@ -0,0 +1,9 @@ +### 2489.Number-of-Substrings-With-Fixed-Ratio + +对于区间,我们固定会联想到前缀和的应用。在本题里,如果一个区间[a,b]里的0/1比是固定的num1:num2,那么对于前缀prefix[b]和prefix[a-1]应该有什么共同的性质呢? + +此前我们遇到过类似的题目:如果区间[a,b]的元素和能被k整除,那么必然prefix[b]和prefix[a-1]关于k的余数一定相同。 + +类似的,本题里,我们希望prefix[b]和prefix[a-1]应该是关于“num1个0 + num2个1"这个“循环节”的余数相同。怎么定义这个余数呢?假设前缀长度L里面有a个0与b个1,我们可以知道里面出现了k次“num1个0 + num2个1",其中`k=min(a/num1,b/num2)`。去除这些完整的循环节,剩下的零头的0与,就代表了“余数”。 + +所以我们定义hash表,key是“整除循环节后两种字符的零头”,value就是这个前缀出现了多少次。我们依次处理前缀,当该前缀的零头是{a,b},我们就看hash表里这样的零头pair已经出现过了多少次(前缀),这就意味着可以组成多少对区间,使得该区间里两种字符的个数恰好是“num1个0 + num2个1"的整数倍。 From 344b8288834119a277e1e5bcd8cbd82df84bd06d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 16:21:33 -0800 Subject: [PATCH 1503/2729] Create 2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees.cpp --- ...um-XOR-of-Two-Non-Overlapping-Subtrees.cpp | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees.cpp diff --git a/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees.cpp b/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees.cpp new file mode 100644 index 000000000..7147bfafe --- /dev/null +++ b/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees.cpp @@ -0,0 +1,97 @@ +using LL = long long; + +class Solution { + vectornext[50005]; + LL val[50005]; + vectorvalues; + + class TrieNode + { + public: + TrieNode* next[2]; + TrieNode(){ + for (int i=0; i<2; i++) + next[i] = NULL; + } + }; + TrieNode* root; + + LL ret = 0; + +public: + void insert(LL num) + { + TrieNode* node = root; + for (int i=63; i>=0; i--) + { + int d = ((num>>i)&1); + if (node->next[d]==NULL) + node->next[d] = new TrieNode(); + node = node->next[d]; + } + } + + LL find(LL num) + { + TrieNode* node = root; + if (root->next[0]==NULL && root->next[1]==NULL) return 0; + LL ret = 0; + for (int i=63; i>=0; i--) + { + int d = ((num>>i)&1); + if (node->next[1-d]!=NULL) + { + ret += (1LL<next[1-d]; + } + else + { + ret += 0; + node = node->next[d]; + } + } + return ret; + } + + long long maxXor(int n, vector>& edges, vector& values) + { + this->values = values; + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + + root = new TrieNode(); + + dfs(0, -1); + + dfs2(0, -1); + + return ret; + } + + LL dfs(int cur, int parent) + { + LL v = values[cur]; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + v = v + dfs(nxt, cur); + } + val[cur] = v; + return v; + } + + void dfs2(int cur, int parent) + { + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + ret = max(ret, find(val[nxt])); + dfs2(nxt, cur); + insert(val[nxt]); + } + } +}; From 6be44f9d2e648b8f579c061a05576a90f42a56fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 16:21:58 -0800 Subject: [PATCH 1504/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f62217159..0ecc57034 100644 --- a/Readme.md +++ b/Readme.md @@ -598,6 +598,7 @@ [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) [1803.Count-Pairs-With-XOR-in-a-Range](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1803.Count-Pairs-With-XOR-in-a-Range) (H) [1938.Maximum-Genetic-Difference-Query](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1938.Maximum-Genetic-Difference-Query) (H) +[2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees) (H) #### [Linked List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List) [061.Rotate-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/061.Rotate-List) (M) From cb763040e0ec87a467c9e281a28d7c737eb1d5ae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Dec 2022 16:42:14 -0800 Subject: [PATCH 1505/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees/Readme.md diff --git a/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees/Readme.md b/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees/Readme.md new file mode 100644 index 000000000..9a4d84b2f --- /dev/null +++ b/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees/Readme.md @@ -0,0 +1,7 @@ +### 2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees + +显然我们可以通过一遍dfs求得每个节点对应的子树元素和。另外,对于一个数组pool,和一个固定的元素n,我们知道可以用`1707.Maximum-XOR-With-an-Element-From-Array`的算法,高效地得到n在pool里的最大XOR值。但是本题的难点在于,如何添加元素进入pool的顺序,以及求max XOR的顺序,因为我们需要排除两个重合子树被XOR的可能性。 + +本题的精彩解法是设计一个后序遍历的dfs。对于每个节点node,我们依次处理它的子节点v,先在pool里查询v可以得到的最大XOR值,然后递归处理v,最后将v加入pool。这样处理完所有的孩子节点,我们会发现,所有的query都不会发生在节点v与它的直系下级之间,只会发生在v与亲戚节点之间。至于node本身,我们不会在当前的dfs里处理,而是由其parent所在的dfs里进行query、递归处理和添加。再次注意这三者之间的顺序,这保证了query任何一个节点的时候,它的子树都没有被处理,子节点和本身都还没有被添加进pool里。 + +另外,因为所有的节点都是依次加入pool的,而且入pool之前都与pool内的元素query过一次最大XOR的寻找,所以这个方法不会遗漏任何配对。 From bc68e22c8a7905e698bb85a3cf6f61572789689b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 14:39:55 -0800 Subject: [PATCH 1506/2729] Update Readme.md --- .../2463.Minimum-Total-Distance-Traveled/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/Readme.md b/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/Readme.md index f93903844..60ad3ff67 100644 --- a/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/Readme.md +++ b/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled/Readme.md @@ -5,7 +5,7 @@ 于是本题就是一个非常典型的第一类区间型DP。我们令dp[i][j]表示前i个工厂覆盖了前j个机器人时,所需要的最小路径和。显然,对于状态转移方程,我们关心的就是最后一个工厂的覆盖范围,我们遍历一下最后一个工厂所覆盖的机器人数目即可: ```cpp for (int k=0; k<=factory[i][1]; k++) { - dp[i][j] = min(dp[i][j] + dp[i-1][j-k] + dist[i][j-k+1][j]); + dp[i][j] = min(dp[i][j], dp[i-1][j-k] + dist[i][j-k+1][j]); } ``` 其中`dist[i][j-k+1][k]`表示最后k个机器人都送到第i个工厂时,所对应的总路程。 From 7bb49d9b1275caa863112ccf88c1638220b4bb8f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 17:13:20 -0800 Subject: [PATCH 1507/2729] Create 898.Bitwise-ORs-of-Subarrays.cpp --- .../898.Bitwise-ORs-of-Subarrays.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/898.Bitwise-ORs-of-Subarrays.cpp diff --git a/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/898.Bitwise-ORs-of-Subarrays.cpp b/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/898.Bitwise-ORs-of-Subarrays.cpp new file mode 100644 index 000000000..ca4351c02 --- /dev/null +++ b/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/898.Bitwise-ORs-of-Subarrays.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int subarrayBitwiseORs(vector& A) + { + unordered_setSet; + unordered_setAll; + for (int x: A) + { + unordered_settemp; + for (int y: Set) + { + temp.insert(y | x); + All.insert(y | x); + } + temp.insert(x); + All.insert(x); + Set = temp; + + } + return All.size(); + } +}; From 657f7dd65d7e3c00dc63accaccea6cca3b896d96 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 17:14:08 -0800 Subject: [PATCH 1508/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0ecc57034..04e9ce5c6 100644 --- a/Readme.md +++ b/Readme.md @@ -845,6 +845,7 @@ [371.Sum-of-Two-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/371.Sum-of-Two-Integers) (H) [318.Maximum-Product-of-Word-Lengths](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/318.Maximum-Product-of-Word-Lengths) (M+) 342.Power-of-Four (H) +[898.Bitwise-ORs-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays) (H-) [957.Prison-Cells-After-N-Days](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/957.Prison-Cells-After-N-Days) (H) 1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K (TBD) [1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) From 9e747cb7f8c30c3e0f1767d261f2e0cdc0001d1a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 17:19:21 -0800 Subject: [PATCH 1509/2729] Create Readme.md --- Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md diff --git a/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md b/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md new file mode 100644 index 000000000..bdc506663 --- /dev/null +++ b/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md @@ -0,0 +1,3 @@ +### 898.Bitwise-ORs-of-Subarrays + +本题的突破口在于,OR的结果不会特别多,因为OR得越多,越趋近于`111.11`. 我们能够存储下以每一个元素为右端点时所有subarray的可能OR值。 From f0b8d5a7d01f3ce9216a2ec8bfb086cc05107915 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 17:26:36 -0800 Subject: [PATCH 1510/2729] Update Readme.md --- Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md b/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md index bdc506663..b762fa856 100644 --- a/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md +++ b/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md @@ -1,3 +1,7 @@ ### 898.Bitwise-ORs-of-Subarrays -本题的突破口在于,OR的结果不会特别多,因为OR得越多,越趋近于`111.11`. 我们能够存储下以每一个元素为右端点时所有subarray的可能OR值。 +本题的突破口在于,OR的结果不会特别多。任何一个元素作为左端点的时候,随着右端点的移动,OR的结果只会是单调地变大(某个bit的0变成1),因此最多只有32种可能。同理,以任何一个元素可以作为佑端点,那么所有subarray的OR结果做多也是32种。 + +因此我们可以用类似背包问题的算法,穷举上一个元素为右端点时所有subarray的OR值,来更新该元素为右端点时所有subarray的OR值。 + +最终的答案是o(32N)数量级,因为可以全部存下来。 From d3acaa732ee4cbdb67c9e61da9b0ed688c54df93 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 17:27:04 -0800 Subject: [PATCH 1511/2729] Update Readme.md --- Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md b/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md index b762fa856..987e3a92b 100644 --- a/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md +++ b/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays/Readme.md @@ -1,6 +1,6 @@ ### 898.Bitwise-ORs-of-Subarrays -本题的突破口在于,OR的结果不会特别多。任何一个元素作为左端点的时候,随着右端点的移动,OR的结果只会是单调地变大(某个bit的0变成1),因此最多只有32种可能。同理,以任何一个元素可以作为佑端点,那么所有subarray的OR结果做多也是32种。 +本题的突破口在于,OR的结果不会特别多。任何一个元素作为左端点的时候,随着右端点的移动,OR的结果只会是单调地变大(某个bit的0变成1),因此最多只有32种可能。同理,以任何一个元素可以作为右端点,那么所有subarray的OR结果做多也是32种。 因此我们可以用类似背包问题的算法,穷举上一个元素为右端点时所有subarray的OR值,来更新该元素为右端点时所有subarray的OR值。 From d1fd1ef9b5a3799fe2df45d2c7c138a35b54147e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 23:37:41 -0800 Subject: [PATCH 1512/2729] Create 2505.Bitwise-OR-of-All-Subsequence-Sums.cpp --- .../2505.Bitwise-OR-of-All-Subsequence-Sums.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums/2505.Bitwise-OR-of-All-Subsequence-Sums.cpp diff --git a/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums/2505.Bitwise-OR-of-All-Subsequence-Sums.cpp b/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums/2505.Bitwise-OR-of-All-Subsequence-Sums.cpp new file mode 100644 index 000000000..cdbbeed7c --- /dev/null +++ b/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums/2505.Bitwise-OR-of-All-Subsequence-Sums.cpp @@ -0,0 +1,16 @@ +using LL = long long; +class Solution { +public: + long long subsequenceSumOr(vector& nums) + { + LL ret = 0; + LL sum = 0; + for (int x: nums) + { + ret = ret | x; + sum += x; + ret = ret | sum; + } + return ret; + } +}; From fbfc783b1249050099d11e4a978132b401407f44 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 23:38:23 -0800 Subject: [PATCH 1513/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 04e9ce5c6..68a72c0d1 100644 --- a/Readme.md +++ b/Readme.md @@ -849,6 +849,7 @@ [957.Prison-Cells-After-N-Days](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/957.Prison-Cells-After-N-Days) (H) 1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K (TBD) [1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) +[2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 3628b15bf11577e2f7a5891c7b1dea2e5b130c96 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 30 Dec 2022 23:48:49 -0800 Subject: [PATCH 1514/2729] Create Readme.md --- .../2505.Bitwise-OR-of-All-Subsequence-Sums/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums/Readme.md diff --git a/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums/Readme.md b/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums/Readme.md new file mode 100644 index 000000000..5108f5102 --- /dev/null +++ b/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums/Readme.md @@ -0,0 +1,9 @@ +### 2505.Bitwise-OR-of-All-Subsequence-Sums + +首先我们知道一个大方向:OR的操作越多,就有越多的bit能被置1. + +因为单个元素也属于一个subsequence,所以可以将所有的nums[i]都OR起来。即如果任何一个元素的任何一个bit位上是1,那么最终答案里该bit上也一定是1. + +那么如果某个bit位上,没有任何一个现成的nums[i]是1,那么怎么判定呢?因为还存在一种可能,就是某些元素(即subsequence)的加和,恰好使得在该bit位上因为进位从而置1. 我们如何知道是否存在这样的进位呢?为了判定这样的“进位”是否会发生,我们就尽可能多地进行加法操作即可。极端一点,就是将所有元素都加起来,查看这个这个过程中,该bit位上是否曾经出现过1. 如果始终都没有出现过1,那么意味着任何一个subsequence的加和也不会在该bit位产生进位的1. + +所以最终的答案,就是将nums[i]和所有presum[i]进行OR操作即可。 From d23cd19b0d8a7414cead4a4cfb71d39f98b72de3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 31 Dec 2022 00:11:47 -0800 Subject: [PATCH 1515/2729] Create 2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even.cpp --- ...dges-to-Make-Degrees-of-All-Nodes-Even.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even.cpp diff --git a/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even.cpp b/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even.cpp new file mode 100644 index 000000000..dba8fbe78 --- /dev/null +++ b/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even.cpp @@ -0,0 +1,51 @@ +class Solution { + unordered_setnext[100005]; +public: + bool isPossible(int n, vector>& edges) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].insert(b); + next[b].insert(a); + } + + vectorodds; + for (int i=1; i<=n; i++) + { + if ((next[i].size()) % 2 == 1) + odds.push_back(i); + } + + if (odds.size()==0) return true; + + if (odds.size()==2) + { + int a = odds[0], b= odds[1]; + if (next[a].find(b)==next[a].end()) + return true; + else for (int i=1; i<=n; i++) + { + if (i==a || i==b) continue; + if (next[i].find(a)==next[i].end() && next[i].find(b)==next[i].end() ) + return true; + } + + return false; + } + + if (odds.size() == 4) + { + int a = odds[0], b= odds[1], c= odds[2], d=odds[3]; + if (next[a].find(b)==next[a].end() && next[c].find(d)==next[c].end()) + return true; + if (next[a].find(c)==next[a].end() && next[b].find(d)==next[b].end()) + return true; + if (next[a].find(d)==next[a].end() && next[b].find(c)==next[b].end()) + return true; + return false; + } + + return false; + } +}; From bff2bc36556ecfade864c7e07829eef769191ed1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 31 Dec 2022 00:12:09 -0800 Subject: [PATCH 1516/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 68a72c0d1..0cfd922fa 100644 --- a/Readme.md +++ b/Readme.md @@ -1023,6 +1023,7 @@ [1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph) (M+) [1782.Count-Pairs-Of-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1782.Count-Pairs-Of-Nodes) (H) [2360.Longest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2360.Longest-Cycle-in-a-Graph) (M+) +[2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even) (H-) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 368c3fa635a4534865b355fb6ec34cd046806181 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 31 Dec 2022 00:19:41 -0800 Subject: [PATCH 1517/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even/Readme.md diff --git a/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even/Readme.md b/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even/Readme.md new file mode 100644 index 000000000..155a303f7 --- /dev/null +++ b/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even/Readme.md @@ -0,0 +1,13 @@ +### 2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even + +本题没有特别的,就是考虑对图的几何分析。令度为奇数的点的数目为m,分情况讨论: + +如果m等于1,那么任何新连接到m的边,都会破坏另一个节点度的偶性。 + +如果m等于2,那么(1) 如果这两点之间没有边,那么就一条边将其相邻即可。(2) 如果这两点a,b之间已经有边,那么我们需要令找一个(度为偶数)的点c,且该点ac和bc都能再连一条边。 + +如果m等于3,我们无法用两条边,仅改变这三个点的度的奇性。 + +如果m等于4,我们令其为a,b,c,d。只有ab、cd可连边,或者ac、bd可连边,或者ad、bc可连边,三种情况能符合要求。 + +如果m大于等于5,我们无法用两条边连到5个或更多的点(改变它们的度),返回false。 From c0591285e298dfec6079b571f11792304303f175 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 31 Dec 2022 00:20:32 -0800 Subject: [PATCH 1518/2729] Create 2514.Count-Anagrams.cpp --- .../2514.Count-Anagrams.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Math/2514.Count-Anagrams/2514.Count-Anagrams.cpp diff --git a/Math/2514.Count-Anagrams/2514.Count-Anagrams.cpp b/Math/2514.Count-Anagrams/2514.Count-Anagrams.cpp new file mode 100644 index 000000000..0a0e50312 --- /dev/null +++ b/Math/2514.Count-Anagrams/2514.Count-Anagrams.cpp @@ -0,0 +1,44 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL inv[100005]; +public: + int countAnagrams(string s) + { + vectorstr_arr; + istringstream in(s); + int k = 0; + for (string word; in>>word; k++) + str_arr.push_back(word); + + inv[1] = 1; + for(int i=2; i<=100000; ++i) + inv[i]=(M-M/i) * inv[M%i] % M; + + LL ret = 1; + for (auto& str: str_arr) + { + ret = ret * helper(str) % M; + } + return ret; + } + + LL helper(string& s) + { + unordered_mapMap; + for (auto ch: s) + Map[ch]+=1; + + int N = s.size(); + LL ret = 1; + for (int i=1; i<=N; i++) + ret = ret * i % M; + + for (auto [k,v]:Map) + { + for (int i=1; i<=v; i++) + ret = ret * inv[i] % M; + } + return ret; + } +}; From 79bdb2f0d1e12fa626c4d0d9f67ed45cc2f9873e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 31 Dec 2022 00:20:58 -0800 Subject: [PATCH 1519/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0cfd922fa..7be97836c 100644 --- a/Readme.md +++ b/Readme.md @@ -1104,6 +1104,7 @@ [1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony](https://github.com/wisdompeak/LeetCode/tree/master/Math/1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony) (H) [2221.Find-Triangular-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Math/2221.Find-Triangular-Sum-of-an-Array) (M) [2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps) (M+) +[2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From b36bb1b5f9989cc2b850f3689a62e94b1e4da5bf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 31 Dec 2022 00:26:08 -0800 Subject: [PATCH 1520/2729] Create Readme.md --- Math/2514.Count-Anagrams/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Math/2514.Count-Anagrams/Readme.md diff --git a/Math/2514.Count-Anagrams/Readme.md b/Math/2514.Count-Anagrams/Readme.md new file mode 100644 index 000000000..a0600ff82 --- /dev/null +++ b/Math/2514.Count-Anagrams/Readme.md @@ -0,0 +1,7 @@ +### 2514.Count-Anagrams + +本题的本质就是计算每个单词的distinct permutation的乘积。 + +对于一个单词长度为n,则distinct permutation的数目就是`n! / prod{k_i !}`,其中k_i就是每个字母在该单词中出现的频次。 + +本题的难点在于模下计算。上述公式中ki的阶乘是在分母上,所以需要取逆元。即转换为 `n! * prod{inv[k_i]!}`。因为ki的频次不超过1e5,所以我们可以提前预处理,用线性时间算出1e5以内所有的inv[i]. From 5242e428632ccac33def3904c771b2d28d08f7e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 31 Dec 2022 14:38:20 -0800 Subject: [PATCH 1521/2729] Update 1568.Minimum-Number-of-Days-to-Disconnect-Island.cpp --- ...um-Number-of-Days-to-Disconnect-Island.cpp | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/BFS/1568.Minimum-Number-of-Days-to-Disconnect-Island/1568.Minimum-Number-of-Days-to-Disconnect-Island.cpp b/BFS/1568.Minimum-Number-of-Days-to-Disconnect-Island/1568.Minimum-Number-of-Days-to-Disconnect-Island.cpp index 2346de173..26695a44b 100644 --- a/BFS/1568.Minimum-Number-of-Days-to-Disconnect-Island/1568.Minimum-Number-of-Days-to-Disconnect-Island.cpp +++ b/BFS/1568.Minimum-Number-of-Days-to-Disconnect-Island/1568.Minimum-Number-of-Days-to-Disconnect-Island.cpp @@ -6,26 +6,25 @@ class Solution { m = grid.size(); n = grid[0].size(); - int count = islands(grid); - if (count > 1) return 0; + int count = island(grid); + if (count > 1 || count == 0) return 0; for (int i=0; i 1) return 1; + int count = island(grid); + if (count>1 || count==0) return 1; grid[i][j] = 1; } - return 2; } - int islands(vector>& grid) + int island(vector>& grid) { - auto dir = vector>({{1,0},{-1,0},{0,1},{0,-1}}); auto visited = vector>(m, vector(n,0)); + auto dir = vector>({{1,0},{-1,0},{0,1},{0,-1}}); int count = 0; for (int i=0; i>q; q.push({i,j}); visited[i][j] = 1; - - count++; while (!q.empty()) { @@ -50,14 +47,16 @@ class Solution { int a = x+dir[k].first; int b = y+dir[k].second; if (a<0||a>=m||b<0||b>=n) continue; - if (grid[a][b]==0) continue; if (visited[a][b]==1) continue; + if (grid[a][b]==0) continue; + q.push({a,b}); - visited[a][b] = 1; + visited[a][b]=1; } } - if (count == 2) return 2; + count+=1; + if (count>1) return 2; } return count; } From 23861648892263c7dc4d979bc1b22f33d9feb16e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 31 Dec 2022 14:40:12 -0800 Subject: [PATCH 1522/2729] Update Readme.md --- .../Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/BFS/1568.Minimum-Number-of-Days-to-Disconnect-Island/Readme.md b/BFS/1568.Minimum-Number-of-Days-to-Disconnect-Island/Readme.md index b89ff211a..911bb9928 100644 --- a/BFS/1568.Minimum-Number-of-Days-to-Disconnect-Island/Readme.md +++ b/BFS/1568.Minimum-Number-of-Days-to-Disconnect-Island/Readme.md @@ -8,6 +8,8 @@ 再看一下例子,发现sample里的答案没有超过2的。细想一下,确实无论什么几何形状,都会有“角落”的格子。所谓的“角落”,指的是只有两个邻接点是与大陆相连。所以答案又可以缩小为不会超过2. -如今答案的可能只有0,1,2。答案是否为零很好判断,扫一遍全局看是否只有一个岛。答案是否为1呢?如果只要删除一块陆地就能使得岛的数量大于等于2,那么我们就遍历每一块陆地,假设删除它,再查看一下剩下的地形的岛的数量即可。遍历一块“删除之地”大概是o(900),然后每次搜索全局数一下剩余岛的个数也是o(900),总共的时间复杂度是o(810000),是可以接受的。如果答案不为1,那么答案就肯定是2了。 +如今答案的可能只有0,1,2。答案是否为零很好判断,扫一遍全局看是否已经存在多于一个岛,或者压根没有岛。 + +答案是否为1呢?这意味着只要删除一块陆地,就能使得岛的数量大于等于2,或者没有任何岛。于是我们可以遍历每一块陆地,假设删除它,再查看一下剩下的地形的岛的数量即可。遍历一块“删除之地”大概是o(900),然后每次搜索全局数一下剩余岛的个数也是o(900),总共的时间复杂度是o(810000),是可以接受的。如果答案不为1,那么答案就肯定是2了。 所以本题的本质就是一个暴力枚举+BFS搜索判断岛数量。 From 4b0893341ad390b7e0300cb71365729625e2e3f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 Jan 2023 12:38:20 -0800 Subject: [PATCH 1523/2729] Create 2528.Maximize-the-Minimum-Powered-City.cpp --- ...2528.Maximize-the-Minimum-Powered-City.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Binary_Search/2528.Maximize-the-Minimum-Powered-City/2528.Maximize-the-Minimum-Powered-City.cpp diff --git a/Binary_Search/2528.Maximize-the-Minimum-Powered-City/2528.Maximize-the-Minimum-Powered-City.cpp b/Binary_Search/2528.Maximize-the-Minimum-Powered-City/2528.Maximize-the-Minimum-Powered-City.cpp new file mode 100644 index 000000000..28e57289f --- /dev/null +++ b/Binary_Search/2528.Maximize-the-Minimum-Powered-City/2528.Maximize-the-Minimum-Powered-City.cpp @@ -0,0 +1,44 @@ +using LL = long long; +class Solution { +public: + long long maxPower(vector& stations, int r, int k) + { + LL left = 0, right = LLONG_MAX; + while (left < right) + { + LL mid = right-(right-left)/2; + if (isOK(stations, r, k, mid)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool isOK(vectorstations, int r, LL k, LL m) + { + int n = stations.size(); + LL sum = 0; + for (int i=0; i<=min(n-1, r-1); i++) + sum += stations[i]; + + for (int i=0; i= 0) + sum -= stations[i-r-1]; + + if (sum >= m) continue; + + LL diff = m - sum; + if (diff > k) + return false; + stations[min(n-1, i+r)] += diff; + sum = m; + k -= diff; + } + return true; + } +}; From fcefccc2fd87c33200fdb8fc231fb66562657bdd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 Jan 2023 12:38:49 -0800 Subject: [PATCH 1524/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7be97836c..61fe94d00 100644 --- a/Readme.md +++ b/Readme.md @@ -118,6 +118,7 @@ [2439.Minimize-Maximum-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2439.Minimize-Maximum-of-Array) (H-) [2517.Maximum-Tastiness-of-Candy-Basket](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket) (M+) [2513.Minimize-the-Maximum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays) (H) +[2528.Maximize-the-Minimum-Powered-City](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2528.Maximize-the-Minimum-Powered-City) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From b87575a61a1519d0b06d8cdb4e0e09452595f322 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 Jan 2023 12:47:53 -0800 Subject: [PATCH 1525/2729] Create Readme.md --- Binary_Search/2528.Maximize-the-Minimum-Powered-City/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Binary_Search/2528.Maximize-the-Minimum-Powered-City/Readme.md diff --git a/Binary_Search/2528.Maximize-the-Minimum-Powered-City/Readme.md b/Binary_Search/2528.Maximize-the-Minimum-Powered-City/Readme.md new file mode 100644 index 000000000..10bd5dee7 --- /dev/null +++ b/Binary_Search/2528.Maximize-the-Minimum-Powered-City/Readme.md @@ -0,0 +1,3 @@ +### 2528.Maximize-the-Minimum-Powered-City + +我们假设The minimum power of a city是m,那么意味着每个城市都可以得到至少m的供应。我们就顺着走一遍每个城市,看它是否已经实现了周围[i-r,i+r]范围内的滑窗和大于等于m。如果不够m,那么我们必然会贪心地增加最优端的那个城市的供给(因为它能覆盖更多未来的城市)补齐至m。一路走下去,如果总共需要补建的电力站小于等于k,那么就说明m是可以实现的,于是可以尝试猜测更大的m。如果需要补建的电力站大于k,那么就说明m不可行,就尝试猜测更小的m。 From 1123207b21e87fa6cf3bbb3e738f07fb3496eda5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 Jan 2023 12:49:20 -0800 Subject: [PATCH 1526/2729] Create 2527.Find-Xor-Beauty-of-Array.cpp --- .../2527.Find-Xor-Beauty-of-Array.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Bit_Manipulation/2527.Find-Xor-Beauty-of-Array/2527.Find-Xor-Beauty-of-Array.cpp diff --git a/Bit_Manipulation/2527.Find-Xor-Beauty-of-Array/2527.Find-Xor-Beauty-of-Array.cpp b/Bit_Manipulation/2527.Find-Xor-Beauty-of-Array/2527.Find-Xor-Beauty-of-Array.cpp new file mode 100644 index 000000000..d9ba6f743 --- /dev/null +++ b/Bit_Manipulation/2527.Find-Xor-Beauty-of-Array/2527.Find-Xor-Beauty-of-Array.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int xorBeauty(vector& nums) + { + int sum = 0; + for (int x: nums) + sum ^= x; + return sum; + + } +}; From 54556821ad36b8b4052f062062d0d5da4579aecd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 7 Jan 2023 12:50:36 -0800 Subject: [PATCH 1527/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 61fe94d00..0045ee8a0 100644 --- a/Readme.md +++ b/Readme.md @@ -860,6 +860,7 @@ [1734.Decode-XORed-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1734.Decode-XORed-Permutation) (M+) [1738.Find-Kth-Largest-XOR-Coordinate-Value](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1738.Find-Kth-Largest-XOR-Coordinate-Value) (M+) [1835.Find-XOR-Sum-of-All-Pairs-Bitwise-AND](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1835.Find-XOR-Sum-of-All-Pairs-Bitwise-AND) (M) +[2527.Find-Xor-Beauty-of-Array](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2527.Find-Xor-Beauty-of-Array) (H) * ``Bit Mask`` [320.Generalized-Abbreviation](https://github.com/wisdompeak/LeetCode/tree/master/String/320.Generalized-Abbreviation) (M) [1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters) (M+) From f9c4c3c3d904733c6bd6bf6254341a110d96cc78 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Jan 2023 17:04:09 -0800 Subject: [PATCH 1528/2729] Create Readme.md --- .../2527.Find-Xor-Beauty-of-Array/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Bit_Manipulation/2527.Find-Xor-Beauty-of-Array/Readme.md diff --git a/Bit_Manipulation/2527.Find-Xor-Beauty-of-Array/Readme.md b/Bit_Manipulation/2527.Find-Xor-Beauty-of-Array/Readme.md new file mode 100644 index 000000000..0a7137376 --- /dev/null +++ b/Bit_Manipulation/2527.Find-Xor-Beauty-of-Array/Readme.md @@ -0,0 +1,11 @@ +### 2527.Find-Xor-Beauty-of-Array + +因为bit之间彼此互不影响,所以我们这里仅考虑一个bit位的情况。 + +我们要把所有可能的`(a|b)&c`进行异或。这里要注意,异或的本质是就是bit 1的个数。如果有奇数个bit 1进行异或,答案就是1;否则答案就是0. 所以在这里,我们只需要考虑数值为1的c。数值为0的c,只会贡献`(a|b)&c=0`,不影响结果。 + +当我们固定了c,接下来考虑所有`a|b`的配对,我们需要将这些0或1都异或起来。假设有总共有n个元素,其中有x个元素在这个bit上是1,剩下y个元素在这个bit上是0,那么我们选取到`a|b=1`的个数就是`(n^2-y^2)`个(即排除掉选到两个0的可能性)。我们发现`(n^2-y^2)=(n+y)(n-y)=(n+y)x=(2n-x)x`,说明`(n^2-y^2)`的奇偶性取决于x的奇偶性。也就是说,如果在这个bit位上有奇数个1,那么就有奇数个`a|b`的值是1,它们异或的结果就是1. 反之,它们异或的结果就是0. 如果用一个公示表达,那就是等于将所有元素的该bit都异或起来。 + +以上分析是针对固定的c。那么遍历所有的c,会遇到类似的情况。如果固定c对应的`sum(a|b)`是1,那么说明有奇数个c是1,再将奇数个答案异或起来,那还是1. 如果固定c对应的答案是0,那么说明所有的`sum(a|b)`都是0,最终答案还是0. + +所以最终答案只需要将所有元素异或起来即可。 From 3fea66cfeca2717a793ad4d1b9f860dbb7863b81 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Jan 2023 18:39:38 -0800 Subject: [PATCH 1529/2729] Create 2522.Partition-String-Into-Substrings-With-Values-at-Most-K.cpp --- ...-Into-Substrings-With-Values-at-Most-K.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K/2522.Partition-String-Into-Substrings-With-Values-at-Most-K.cpp diff --git a/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K/2522.Partition-String-Into-Substrings-With-Values-at-Most-K.cpp b/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K/2522.Partition-String-Into-Substrings-With-Values-at-Most-K.cpp new file mode 100644 index 000000000..8f0ae14a5 --- /dev/null +++ b/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K/2522.Partition-String-Into-Substrings-With-Values-at-Most-K.cpp @@ -0,0 +1,28 @@ +class Solution { + int dp[100005]; +public: + int minimumPartition(string s, int k) + { + int n = s.size(); + int m = to_string(k).size(); + for (int i=0; ik) + return -1; + } + + s = "#"+s; + dp[0] = 0; + + for (int i=1; i<=n; i++) + { + if (i-m+1>=1 && stoi(s.substr(i-m+1, m)) <= k) + dp[i] = dp[i-m] + 1; + else + dp[i] = dp[max(0, i-m+1)] + 1; + } + + return dp[n]; + + } +}; From 2dc3ac5551851905ee39a8d0a9b6fb7c50342676 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Jan 2023 18:40:03 -0800 Subject: [PATCH 1530/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0045ee8a0..1ec2d061c 100644 --- a/Readme.md +++ b/Readme.md @@ -714,6 +714,7 @@ [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) [2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) [2464.Minimum-Subarrays-in-a-Valid-Split](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split) (M) +[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) From 9396d488155dee1d8d99c4910d36bb0e569cf8e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Jan 2023 20:18:22 -0800 Subject: [PATCH 1531/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K/Readme.md diff --git a/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K/Readme.md b/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K/Readme.md new file mode 100644 index 000000000..f6072cc60 --- /dev/null +++ b/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K/Readme.md @@ -0,0 +1,7 @@ +### 2522.Partition-String-Into-Substrings-With-Values-at-Most-K + +这是一个很常规的dp题。我们令dp[i]表示前i个元素能够分成的最少分组。着眼点就是寻找最后一个区间的范围[j:i]。如果s[j:i]是小于等于k的,那么就有`dp[i] = dp[j-1]+1`。 + +那么我们是否需要遍历j找到最小的dp[j-1]呢?这样就是一个n^2的算法。事实上因为dp[i]必然是单调递增的,所以我们只需要找尽可能小的j,即能找到尽可能小的dp[j-1]。考虑k的长度是m,那么我们只需要考察最后一个区间长度如果是m能否可行。不可行的话,取最后一个区间的长度是m-1即可。 + +注意一下无解的情况。如果m长度是1,且s[i]里有一个字符大于k,那么说明即使区间长度是1也无法满足要求。 From 6535e5b5da14ab3aa698047e4426eebf76d1f0ca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 9 Jan 2023 01:50:26 -0800 Subject: [PATCH 1532/2729] Create 2532.Time-to-Cross-a-Bridge.cpp --- .../2532.Time-to-Cross-a-Bridge.cpp | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Simulation/2532.Time-to-Cross-a-Bridge/2532.Time-to-Cross-a-Bridge.cpp diff --git a/Simulation/2532.Time-to-Cross-a-Bridge/2532.Time-to-Cross-a-Bridge.cpp b/Simulation/2532.Time-to-Cross-a-Bridge/2532.Time-to-Cross-a-Bridge.cpp new file mode 100644 index 000000000..7fdeac17d --- /dev/null +++ b/Simulation/2532.Time-to-Cross-a-Bridge/2532.Time-to-Cross-a-Bridge.cpp @@ -0,0 +1,71 @@ +using PII = pair; +class Solution { +public: + int findCrossingTime(int n, int k, vector>& time) + { + priority_queue, greater<>>leftArrive; + priority_queue, greater<>>rightArrive; + for (int i=0; ileftWait; + priority_queuerightWait; + + int ret = 0; + int count = 0; + int taken = 0; + + while (count < n) + { + while (!leftArrive.empty() && leftArrive.top().first <= nextFree) + { + auto [arriveTime, id] = leftArrive.top(); + leftArrive.pop(); + leftWait.push({time[id][0]+time[id][2], id}); + } + while (!rightArrive.empty() && rightArrive.top().first <= nextFree) + { + auto [arriveTime, id] = rightArrive.top(); + rightArrive.pop(); + rightWait.push({time[id][0]+time[id][2], id}); + } + + if (leftWait.empty() && rightWait.empty()) + { + int t1 = leftArrive.empty() ? INT_MAX : leftArrive.top().first; + int t2 = rightArrive.empty() ? INT_MAX : rightArrive.top().first; + nextFree = min(t1, t2); + continue; + } + + if (!rightWait.empty()) // R -> L + { + auto [_, id] = rightWait.top(); + rightWait.pop(); + nextFree += time[id][2]; + leftArrive.push({nextFree+time[id][3], id}); + + count++; + ret = max(ret, nextFree); + } + else if (!leftWait.empty()) // L -> R + { + if (taken == n) + { + while (!leftWait.empty()) + leftWait.pop(); + } else + { + auto [_, id] = leftWait.top(); + leftWait.pop(); + nextFree += time[id][0]; + rightArrive.push({nextFree+time[id][1], id}); + taken++; + } + } + } + + return nextFree; + } +}; From 4cb83354e1a11ac566c2f5655e619e7e8fe72edd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 9 Jan 2023 01:51:26 -0800 Subject: [PATCH 1533/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1ec2d061c..8bee0aab7 100644 --- a/Readme.md +++ b/Readme.md @@ -1286,6 +1286,7 @@ #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) [2069.Walking-Robot-Simulation-II](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2069.Walking-Robot-Simulation-II) (M+) +[2532.Time-to-Cross-a-Bridge](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2532.Time-to-Cross-a-Bridge) (H) #### [Others](https://github.com/wisdompeak/LeetCode/tree/master/Others)   [007.Reverse-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/007.Reverse-Integer) (M) From 9797471f2d4da993ce742606b1b9bd4c6ee2a22d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 9 Jan 2023 13:13:23 -0800 Subject: [PATCH 1534/2729] Update 2532.Time-to-Cross-a-Bridge.cpp --- .../2532.Time-to-Cross-a-Bridge.cpp | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/Simulation/2532.Time-to-Cross-a-Bridge/2532.Time-to-Cross-a-Bridge.cpp b/Simulation/2532.Time-to-Cross-a-Bridge/2532.Time-to-Cross-a-Bridge.cpp index 7fdeac17d..19f4b1e0e 100644 --- a/Simulation/2532.Time-to-Cross-a-Bridge/2532.Time-to-Cross-a-Bridge.cpp +++ b/Simulation/2532.Time-to-Cross-a-Bridge/2532.Time-to-Cross-a-Bridge.cpp @@ -13,11 +13,19 @@ class Solution { priority_queuerightWait; int ret = 0; - int count = 0; - int taken = 0; + int crossed = 0; + int returned = 0; - while (count < n) + while (returned < n) { + if (crossed == n) + { + while (!leftWait.empty()) + leftWait.pop(); + while (!leftArrive.empty()) + leftArrive.pop(); + } + while (!leftArrive.empty() && leftArrive.top().first <= nextFree) { auto [arriveTime, id] = leftArrive.top(); @@ -44,25 +52,17 @@ class Solution { auto [_, id] = rightWait.top(); rightWait.pop(); nextFree += time[id][2]; - leftArrive.push({nextFree+time[id][3], id}); - - count++; + leftArrive.push({nextFree+time[id][3], id}); + returned++; ret = max(ret, nextFree); } - else if (!leftWait.empty()) // L -> R + else if (!leftWait.empty() && crossed < n) // L -> R { - if (taken == n) - { - while (!leftWait.empty()) - leftWait.pop(); - } else - { - auto [_, id] = leftWait.top(); - leftWait.pop(); - nextFree += time[id][0]; - rightArrive.push({nextFree+time[id][1], id}); - taken++; - } + auto [_, id] = leftWait.top(); + leftWait.pop(); + nextFree += time[id][0]; + rightArrive.push({nextFree+time[id][1], id}); + crossed++; } } From e95916812b1cd67be886370e12f0e57da471b13f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 9 Jan 2023 14:37:03 -0800 Subject: [PATCH 1535/2729] Create Readme.md --- Simulation/2532.Time-to-Cross-a-Bridge/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Simulation/2532.Time-to-Cross-a-Bridge/Readme.md diff --git a/Simulation/2532.Time-to-Cross-a-Bridge/Readme.md b/Simulation/2532.Time-to-Cross-a-Bridge/Readme.md new file mode 100644 index 000000000..3867500d0 --- /dev/null +++ b/Simulation/2532.Time-to-Cross-a-Bridge/Readme.md @@ -0,0 +1,15 @@ +### 2532.Time-to-Cross-a-Bridge + +首先注意,这是一个模拟题,不是一个优化策略问题。所有的规则已经完备地定义了所有工人该如何运作。我们需要设计代码将这个模拟过程实现。 + +我们针对左岸设立两个优先队列。leftArrive收集所有预期到达左岸(准备渡河)的工人id和时间,按照到达时间从早到晚排序。leftWait收集截止nextFree(桥空闲)时刻已经在等待渡河的工人id,按照efficiency排序。同理我们设计rightArrive和rightWait。 + +初始状态:所有的工人都在leftArrive里,到达时刻是0. 另外nextFree就是0. + +每个回合,我们根据当前的nextFree,将leftArrive里面所有到达时间早于nextFree的工人都转移到leftWait里。同理,将rightArrive里面所有到达时间早于nextFree的工人都转移到rightWait里。这意味着,在nextFree时刻,我们会在leftWait和rightWait这两个队列里按照规则选择一个人过桥。但是注意,此时可能出现一种情况,那就是leftWait和rightWait依然都为空。这是因为nextFree可能太早,即桥已经空闲的时候,左右两边还没有人到。这个时候,我们需要调整nextFree,将其延后至leftArrive和rightArrive队列中各自队首元素的较小值,然后根据更新后的nextFree重复上述过程,将一个或若干个工人加入wait队列。 + +在leftWait或rightWait有了人之后,我们就按照规则选取一个人过河。如果rightWait队列有人,我们就取排位第一的工人(记做id)去渡河,那么nextFree就会延后time[id][2](即过桥的过程),同时leftArrive就会新增一个预期的到达,即id会在时刻`nextFree+time[id][2]+time[id][3]`重回左岸。如果右边队列没人,我们就取leftWait排位第一的工人(记做id)去渡河,那么nextFree就会延后time[id][0],同时rightArrive就会新增一个预期的到达,即id会在时刻`nextFree+time[id][0]+time[id][1]`重回右岸。 + +当我们发现有n个人(次)从右岸到了左岸,那么第n次右岸到左岸的nextFree就是答案。 + +此外本题有个坑。我们只需要n个人(次)从左岸到右岸,如何之后继续允许左岸到右岸的操作,有可能会延误右岸的人的回归。所以当第n次左岸到右岸操作后,我们需要将永久性地将leftArrive和leftWait清空。 From 5d7bd870ec548f06ad4ac88430c63a12acc1c6c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jan 2023 11:58:55 -0800 Subject: [PATCH 1536/2729] Create 2536.Increment-Submatrices-by-One.cpp --- .../2536.Increment-Submatrices-by-One.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Others/2536.Increment-Submatrices-by-One/2536.Increment-Submatrices-by-One.cpp diff --git a/Others/2536.Increment-Submatrices-by-One/2536.Increment-Submatrices-by-One.cpp b/Others/2536.Increment-Submatrices-by-One/2536.Increment-Submatrices-by-One.cpp new file mode 100644 index 000000000..124e71d7a --- /dev/null +++ b/Others/2536.Increment-Submatrices-by-One/2536.Increment-Submatrices-by-One.cpp @@ -0,0 +1,54 @@ +class Diff2d { +public: + vector>f; + vector>diff; + int m,n; + Diff2d(int m, int n) + { + this->m = m; + this->n = n; + diff.resize(m+1); + f.resize(m+1); + for (int i=0; i> rangeAddQueries(int n, vector>& queries) { + Diff2d diff(n,n); + for (auto& query: queries) + { + diff.set(query[0], query[1], query[2], query[3], 1); + } + diff.compute(); + vector>rets(n, vector(n)); + for (int i=0; i Date: Sun, 15 Jan 2023 11:59:19 -0800 Subject: [PATCH 1537/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8bee0aab7..1f18da9c4 100644 --- a/Readme.md +++ b/Readme.md @@ -1370,6 +1370,7 @@ * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) +[2536.Increment-Submatrices-by-One](https://github.com/wisdompeak/LeetCode/tree/master/Others/2536.Increment-Submatrices-by-One) (H-) * ``Enumeration`` [479.Largest-Palindrome-Product](https://github.com/wisdompeak/LeetCode/tree/master/Others/479.Largest-Palindrome-Product) (M+) [866.Prime-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/Others/866.Prime-Palindrome) (H-) From a839cf35ece3aa5fb8bb64a39277b3a7d3eb34d8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jan 2023 12:00:36 -0800 Subject: [PATCH 1538/2729] Create Readme.md --- Others/2536.Increment-Submatrices-by-One/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/2536.Increment-Submatrices-by-One/Readme.md diff --git a/Others/2536.Increment-Submatrices-by-One/Readme.md b/Others/2536.Increment-Submatrices-by-One/Readme.md new file mode 100644 index 000000000..c51eaf71d --- /dev/null +++ b/Others/2536.Increment-Submatrices-by-One/Readme.md @@ -0,0 +1,3 @@ +### 2536.Increment-Submatrices-by-One + +此题就是二维差分数组的模板题。套用模板即可。 From e350f154792ed7154cfe6cfb49559ef546948ed4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jan 2023 17:48:23 -0800 Subject: [PATCH 1539/2729] Create 2537.Count-the-Number-of-Good-Subarrays.cpp --- ...537.Count-the-Number-of-Good-Subarrays.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Two_Pointers/2537.Count-the-Number-of-Good-Subarrays/2537.Count-the-Number-of-Good-Subarrays.cpp diff --git a/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays/2537.Count-the-Number-of-Good-Subarrays.cpp b/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays/2537.Count-the-Number-of-Good-Subarrays.cpp new file mode 100644 index 000000000..79eb7b551 --- /dev/null +++ b/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays/2537.Count-the-Number-of-Good-Subarrays.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { + LL total = 0; + LL ret = 0; +public: + long long countGood(vector& nums, int k) + { + int n = nums.size(); + int j = 0; + unordered_mapcount; + + for (int i=0; i= k) + ret += n-j+1; + + total += diff(count, nums[i], -1); + count[nums[i]]--; + } + + return ret; + } + + LL diff(unordered_map&count, int num, int d) + { + LL m = count[num]; + LL old = m*(m-1)/2; + m += d; + LL now = m*(m-1)/2; + return now - old; + } +}; From 704fe52fcbb92fe7556d1418b9faf3aa4c849ce3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jan 2023 17:48:53 -0800 Subject: [PATCH 1540/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1f18da9c4..a8d828107 100644 --- a/Readme.md +++ b/Readme.md @@ -55,6 +55,7 @@ [340.Longest-Substring-with-At-Most-K-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/340.Longest-Substring-with-At-Most-K-Distinct-Characters) (H) [992.Subarrays-with-K-Different-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/992.Subarrays-with-K-Different-Integers) (H-) [2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K) (M) +[2537.Count-the-Number-of-Good-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays) (M+) * ``Two pointers for two seuqences`` [986.Interval-List-Intersections](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/986.Interval-List-Intersections) (M) [1229.Meeting-Scheduler](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1229.Meeting-Scheduler) (M+) From cfd0e3777b8d0963b891b57fa91af3cff4529bd7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jan 2023 20:13:32 -0800 Subject: [PATCH 1541/2729] Create Readme.md --- .../2537.Count-the-Number-of-Good-Subarrays/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2537.Count-the-Number-of-Good-Subarrays/Readme.md diff --git a/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays/Readme.md b/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays/Readme.md new file mode 100644 index 000000000..0d018d7e5 --- /dev/null +++ b/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays/Readme.md @@ -0,0 +1,5 @@ +### 2537.Count-the-Number-of-Good-Subarrays + +pairs的计算取决于每种数字出现的频次。如果一个subarray里某个数值出现了m次,那么它就能贡献`m/(m-1)/2`个pairs. 很明显,窗口越大,就能够得到越多的pairs。 + +因此我们遍历每个元素i作为窗口的左端点,然后探索右端点的位置j使得窗口内恰好能有k对pairs,那么意味着右端点从j到n-1都是可行的,故有n-j个以i为左端点的合法滑窗。每一个回合,向右移动i一位,j必然是单调右移的。故双指针o(n)时间可解。 From ef980ce77483f90880f68a199f0d8e6982b85f21 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 16 Jan 2023 00:13:33 -0800 Subject: [PATCH 1542/2729] Create 2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp --- ...-Between-Maximum-and-Minimum-Price-Sum.cpp | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp diff --git a/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp b/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp new file mode 100644 index 000000000..e8f8e51ef --- /dev/null +++ b/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp @@ -0,0 +1,87 @@ +using LL = long long; +using PLL = pair; +class Solution { + vectornext[100005]; + LL sum1[100005]; + LL sum2[100005]; + LL ret = 0; + int n; +public: + long long maxOutput(int n, vector>& edges, vector& price) + { + this->n = n; + + // if (n==1) return 0; + + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + + dfs(0, -1, price); + + dfs2(0, -1, price); + + return ret; + } + + void dfs(int cur, int prev, vector& price) + { + if ((next[cur].size()==1 && next[cur][0] == prev) || next[cur].size() == 0) + { + sum1[cur] = 0; + sum2[cur] = price[cur]; + return; + } + + LL maxSum1 = 0, maxSum2 = 0; + for (int nxt: next[cur]) + { + if (nxt==prev) continue; + dfs(nxt, cur, price); + maxSum1 = max(maxSum1, sum1[nxt]); + maxSum2 = max(maxSum2, sum2[nxt]); + } + + sum1[cur] = maxSum1 + price[cur]; + sum2[cur] = maxSum2 + price[cur]; + } + + void dfs2(int cur, int prev, vector& price) + { + if (next[cur].size()==1 && next[cur][0] == prev) + return; + + LL ans = max(sum1[cur], sum2[cur]-price[cur]); + + vectorarr1; + vectorarr2; + + for (int nxt: next[cur]) + { + if (nxt==prev) continue; + arr1.push_back({sum1[nxt], nxt}); + arr2.push_back({sum2[nxt], nxt}); + } + sort(arr1.rbegin(), arr1.rend()); + sort(arr2.rbegin(), arr2.rend()); + + if (arr1.size()>=2) + { + if (arr1[0].second!=arr2[0].second) + ans = max(ans, arr1[0].first+arr2[0].first+price[cur]); + else + ans = max(ans, max(arr1[0].first+arr2[1].first+price[cur], arr1[1].first+arr2[0].first+price[cur])); + } + + ret = max(ret, ans); + + for (int nxt: next[cur]) + { + if (nxt==prev) continue; + dfs2(nxt, cur, price); + } + } +}; From 2fae36be7f14d0d0d74dca096c910f78f5ed1fc2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 16 Jan 2023 00:13:57 -0800 Subject: [PATCH 1543/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a8d828107..78a176744 100644 --- a/Readme.md +++ b/Readme.md @@ -256,6 +256,7 @@ [1522.Diameter-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1522.Diameter-of-N-Ary-Tree) (M) [2049.Count-Nodes-With-the-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2049.Count-Nodes-With-the-Highest-Score) (M+) [2246.Longest-Path-With-Different-Adjacent-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2246.Longest-Path-With-Different-Adjacent-Characters) (M+) +[2538.Difference-Between-Maximum-and-Minimum-Price-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum) (H) * ``Serialization & Hashing`` [297.Serialize-and-Deserialize-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/297.Serialize-and-Deserialize-Binary-Tree) (H-) [652.Find-Duplicate-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/652.Find-Duplicate-Subtrees) (H) From 1447926694463572ee50df29884efd421ba3681d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 16 Jan 2023 00:50:10 -0800 Subject: [PATCH 1544/2729] Create Readme.md --- .../Readme.md | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/Readme.md diff --git a/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/Readme.md b/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/Readme.md new file mode 100644 index 000000000..9ffc44f4e --- /dev/null +++ b/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/Readme.md @@ -0,0 +1,40 @@ +### 2538.Difference-Between-Maximum-and-Minimum-Price-Sum + +因为选定了root之后的Min Price必然对应的就是root节点本身,所以所谓的“Difference-Between-Maximum-and-Minimum-Price-Sum”就是从root的邻接节点开始找一条最大路径。既然是求最大路径,必然我们会将另一个端点取到某个叶子节点。综上,本题的本质是在树里找一条最大路径,一端是叶子节点,另一端是非叶子节点(这样它必然有一个邻接节点可以作为root)。 + +在树里找最大路径,最常见的方法就是遍历“拐点”。我们以任意一个节点为根来观察图,树里的任何一条路径都有一个“拐点”。我们就是需要给这个拐点找两个“下垂”的分支路径,一个延伸到叶子节点,另一个不能包括叶子节点。当然,还有第三种情况,就是“拐点”本身就是一个端点,那样的话我们只需要找一条“下垂”的分支路径,该路径不能延伸到叶子节点。 + +我们可以提前用递归预处理整棵树。对于每个节点,我们可以计算出该节点向下到非叶子节点的最大路径(记做sum1),以及该节点向下到叶子节点的最大路径(记做sum2)。显然,对于sum1而言,只需要在递归的时候不加入叶子节点即可。代码如下: +```cpp + void dfs(int cur, int prev, vector& price) + { + if (当前节点cur是叶子节点) + { + sum1[cur] = 0; + sum2[cur] = price[cur]; + return; + } + + LL maxSum1 = 0, maxSum2 = 0; + for (int nxt: next[cur]) + { + if (nxt==prev) continue; + dfs(nxt, cur, price); + maxSum1 = max(maxSum1, sum1[nxt]); + maxSum2 = max(maxSum2, sum2[nxt]); + } + + sum1[cur] = maxSum1 + price[cur]; + sum2[cur] = maxSum2 + price[cur]; + } +``` + +然后我们第二步递归整棵树,对于每个节点cur,有两种构造路径的情况: +1. 该节点就是路径的端点,于是路径的值就是`sum1[cur]` +2. 该节点是拐点,且至少有两条向下的路径,那么我们在cur的所有孩子里找最大的sum1和最大的sum2,这两段拼接起来即可。但是有可能这两段向下的路径对应的是同一条支路。这样的话,我们需要选取“最大的sum1和次大的sum2”,以及“次大的sum1和最大的sum2”。 + +在以上三个答案中,我们挑选最大的一个,作为以cur为拐点的最大路径。最终遍历所有的节点,取全局最大值。 + +特别注意,当n=1时,全图只有一个节点,根和叶子节点重合,`if (当前节点cur是叶子节点)`的代码需要格外小心。 + + From 55f2e8d80f2437ada7478c425ea6447b5700943a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 16 Jan 2023 00:50:57 -0800 Subject: [PATCH 1545/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/Readme.md b/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/Readme.md index 9ffc44f4e..f0cefd8b5 100644 --- a/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/Readme.md +++ b/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/Readme.md @@ -29,7 +29,7 @@ } ``` -然后我们第二步递归整棵树,对于每个节点cur,有两种构造路径的情况: +然后我们第二遍递归整棵树,对于每个节点cur,有两种构造路径的情况: 1. 该节点就是路径的端点,于是路径的值就是`sum1[cur]` 2. 该节点是拐点,且至少有两条向下的路径,那么我们在cur的所有孩子里找最大的sum1和最大的sum2,这两段拼接起来即可。但是有可能这两段向下的路径对应的是同一条支路。这样的话,我们需要选取“最大的sum1和次大的sum2”,以及“次大的sum1和最大的sum2”。 From 990892aa6df928d7e515398018b3cf1ec6e3a30c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 16 Jan 2023 01:34:37 -0800 Subject: [PATCH 1546/2729] Update 2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp --- ...-Between-Maximum-and-Minimum-Price-Sum.cpp | 79 ++++++++----------- 1 file changed, 35 insertions(+), 44 deletions(-) diff --git a/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp b/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp index e8f8e51ef..8a22d6b13 100644 --- a/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp +++ b/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum/2538.Difference-Between-Maximum-and-Minimum-Price-Sum.cpp @@ -1,87 +1,78 @@ using LL = long long; -using PLL = pair; class Solution { - vectornext[100005]; - LL sum1[100005]; - LL sum2[100005]; + vector next[100005]; + LL sum1[100005]; // sum1[node]: the maximum path from node to its non-leaf child + LL sum2[100005]; // sum2[node]: the maximum path from node to its leaf child LL ret = 0; - int n; public: long long maxOutput(int n, vector>& edges, vector& price) { - this->n = n; - - // if (n==1) return 0; - + if (n==1) return 0; + for (auto& edge: edges) { int a = edge[0], b = edge[1]; next[a].push_back(b); - next[b].push_back(a); + next[b].push_back(a); } - + dfs(0, -1, price); - + dfs2(0, -1, price); - - return ret; + + return ret; } - - void dfs(int cur, int prev, vector& price) + + void dfs(int cur, int parent, vector& price) { - if ((next[cur].size()==1 && next[cur][0] == prev) || next[cur].size() == 0) + if (next[cur].size()==1 && next[cur][0] == parent) { sum1[cur] = 0; sum2[cur] = price[cur]; - return; + return; } - + LL maxSum1 = 0, maxSum2 = 0; for (int nxt: next[cur]) { - if (nxt==prev) continue; + if (nxt == parent) continue; dfs(nxt, cur, price); maxSum1 = max(maxSum1, sum1[nxt]); maxSum2 = max(maxSum2, sum2[nxt]); } - sum1[cur] = maxSum1 + price[cur]; sum2[cur] = maxSum2 + price[cur]; } - - void dfs2(int cur, int prev, vector& price) + + void dfs2(int cur, int parent, vector& price) { - if (next[cur].size()==1 && next[cur][0] == prev) - return; - - LL ans = max(sum1[cur], sum2[cur]-price[cur]); - - vectorarr1; - vectorarr2; - + vector>arr1; // {SumVal, childNodeId} + vector>arr2; + + LL ans = sum1[cur]; + if (cur!=0) ans = max(ans, sum2[cur]); + for (int nxt: next[cur]) { - if (nxt==prev) continue; + if (nxt==parent) continue; arr1.push_back({sum1[nxt], nxt}); - arr2.push_back({sum2[nxt], nxt}); + arr2.push_back({sum2[nxt], nxt}); + dfs2(nxt, cur, price); } sort(arr1.rbegin(), arr1.rend()); sort(arr2.rbegin(), arr2.rend()); - - if (arr1.size()>=2) + + if (arr1.size() >= 2) { if (arr1[0].second!=arr2[0].second) - ans = max(ans, arr1[0].first+arr2[0].first+price[cur]); + ans = max(ans, arr1[0].first + arr2[0].first + price[cur]); else - ans = max(ans, max(arr1[0].first+arr2[1].first+price[cur], arr1[1].first+arr2[0].first+price[cur])); + ans = max(ans, max(arr1[0].first + arr2[1].first, arr1[1].first + arr2[0].first) + price[cur]); } - + ret = max(ret, ans); - - for (int nxt: next[cur]) - { - if (nxt==prev) continue; - dfs2(nxt, cur, price); - } } }; + + +// Find a maximum path, for which one end is leaf, and the other is not. From 49dfc6f3846fc5678568d3a3eadbed954c14a677 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 16 Jan 2023 18:02:57 -0800 Subject: [PATCH 1547/2729] Create Notes.md --- SQL/Notes.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 SQL/Notes.md diff --git a/SQL/Notes.md b/SQL/Notes.md new file mode 100644 index 000000000..1eb38dce7 --- /dev/null +++ b/SQL/Notes.md @@ -0,0 +1,20 @@ +#### greatest, least +在多个列中选择最大/最小的一个 +```sql +greatest(columnA, columnB) +least(columnA, columnB) +``` + +#### 日期类型的操作 +##### between +```sql +purchase_date between Prices.start_date and Prices.end_date +``` + + +#### Join +##### Join Condition 可以有复杂的表达式 +```sql +join UnitsSold on Prices.product_id = UnitsSold.product_id + and UnitsSold.purchase_date between Prices.start_date and Prices.end_date +``` From eed9884de4edd05653bf77c6faa4ad4ec5d5b1e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 16 Jan 2023 20:50:23 -0800 Subject: [PATCH 1548/2729] Update Notes.md --- SQL/Notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SQL/Notes.md b/SQL/Notes.md index 1eb38dce7..d2065d8f5 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -1,5 +1,5 @@ #### greatest, least -在多个列中选择最大/最小的一个 +在同一行的多个列中选择最大/最小的一个 ```sql greatest(columnA, columnB) least(columnA, columnB) From 72a584785e2a43bae1d5b310f69237ba7187b49d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Jan 2023 21:33:11 -0800 Subject: [PATCH 1549/2729] Update Notes.md --- SQL/Notes.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/SQL/Notes.md b/SQL/Notes.md index d2065d8f5..122b6a253 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -10,7 +10,11 @@ least(columnA, columnB) ```sql purchase_date between Prices.start_date and Prices.end_date ``` - +##### left +选择一个date数据“2020-19-12”的左七位数字作为month的标记。 +```sql +left(trans_date, 7) as month +``` #### Join ##### Join Condition 可以有复杂的表达式 From 9e4360c863cfb340ada8bc1061c2919060d8b745 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Jan 2023 21:52:01 -0800 Subject: [PATCH 1550/2729] Update Notes.md --- SQL/Notes.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/SQL/Notes.md b/SQL/Notes.md index 122b6a253..916923fbb 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -22,3 +22,19 @@ left(trans_date, 7) as month join UnitsSold on Prices.product_id = UnitsSold.product_id and UnitsSold.purchase_date between Prices.start_date and Prices.end_date ``` + +#### 临时表 +```sql +with Temp1 as +( + select winner_id + from Winners +), Temp2 as +( + select player_id + from Players +) + +select + Round((select count(*) from Winner) / (select count(*) from Players), 2) AS fraction +``` From 1b60b20bbda18530963b6652c27679e18f81f110 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 18 Jan 2023 19:09:07 -0800 Subject: [PATCH 1551/2729] Update Notes.md --- SQL/Notes.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/SQL/Notes.md b/SQL/Notes.md index 916923fbb..b22226c8a 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -38,3 +38,16 @@ with Temp1 as select Round((select count(*) from Winner) / (select count(*) from Players), 2) AS fraction ``` + +#### 分组最大 +在原表里插入rank存为新表。再在新表里选择rank=1的行。 +```sql +with temp as +( + select *, rank() over (partition by student_id order by grade desc, course_id) as rnk + from Enrollments +) +select student_id, course_id, grade +from temp +where rnk = 1 +``` From 8d05c422e58bd0520cb1bfb4568e8489cd480534 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 19 Jan 2023 18:43:42 -0800 Subject: [PATCH 1552/2729] Update Notes.md --- SQL/Notes.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/SQL/Notes.md b/SQL/Notes.md index b22226c8a..855a0d10d 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -5,6 +5,21 @@ greatest(columnA, columnB) least(columnA, columnB) ``` +#### Union +```sql +将两段类型相同的列纵向拼接起来(组成新表)。在第一个select里可以重命名。 +with temp as +( + select user1_id as id + from Friendship + where user2_id = 1 + union + select user2_id + from Friendship + where user1_id = 1 +) +``` + #### 日期类型的操作 ##### between ```sql From 65094f9a42c0265961211838c6a8b15dc4296ed2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 20 Jan 2023 22:19:39 -0800 Subject: [PATCH 1553/2729] Update Notes.md --- SQL/Notes.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/SQL/Notes.md b/SQL/Notes.md index 855a0d10d..2a4fcea2b 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -66,3 +66,12 @@ select student_id, course_id, grade from temp where rnk = 1 ``` + +### Join +#### out join +不指定`on`的话,会将表A与表B的所有row都两两配对。 +```sql +select * +from A +join B +``` From aec452c0aced1285929170ac5e62fea061fd5603 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Jan 2023 15:45:40 -0800 Subject: [PATCH 1554/2729] Create 2542.Maximum-Subsequence-Score.cpp --- .../2542.Maximum-Subsequence-Score.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Priority_Queue/2542.Maximum-Subsequence-Score/2542.Maximum-Subsequence-Score.cpp diff --git a/Priority_Queue/2542.Maximum-Subsequence-Score/2542.Maximum-Subsequence-Score.cpp b/Priority_Queue/2542.Maximum-Subsequence-Score/2542.Maximum-Subsequence-Score.cpp new file mode 100644 index 000000000..25a21096c --- /dev/null +++ b/Priority_Queue/2542.Maximum-Subsequence-Score/2542.Maximum-Subsequence-Score.cpp @@ -0,0 +1,33 @@ +using LL = long long; +class Solution { +public: + long long maxScore(vector& nums1, vector& nums2, int k) + { + int n = nums1.size(); + vector>arr; + for (int i=0; i, greater<>>pq; + LL minVal = INT_MAX; + LL sum = 0; + LL ret = 0; + for (int i=0; ik) + { + sum -= pq.top(); + pq.pop(); + } + if (pq.size()==k) + ret = max(ret, sum * minVal); + } + return ret; + + } +}; From e0a88a7961e8829b18d24c734e3d7a9f1a8fe9e9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Jan 2023 15:46:11 -0800 Subject: [PATCH 1555/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 78a176744..08d02e65f 100644 --- a/Readme.md +++ b/Readme.md @@ -442,6 +442,7 @@ [1834.Single-Threaded-CPU](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1834.Single-Threaded-CPU) (M) [1851.Minimum-Interval-to-Include-Each-Query](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1851.Minimum-Interval-to-Include-Each-Query) (H) [2406.Divide-Intervals-Into-Minimum-Number-of-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2406.Divide-Intervals-Into-Minimum-Number-of-Groups) (M+) +[2542.Maximum-Subsequence-Score](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2542.Maximum-Subsequence-Score) (M+) * ``Arrangement with Stride`` [767.Reorganize-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/767.Reorganize-String) (M+) [1054.Distant-Barcodes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1054.Distant-Barcodes) (M+) From 1e3098ee7119e07a9a77f70ed9b0deece8a53120 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Jan 2023 15:59:48 -0800 Subject: [PATCH 1556/2729] Create Readme.md --- Priority_Queue/2542.Maximum-Subsequence-Score/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Priority_Queue/2542.Maximum-Subsequence-Score/Readme.md diff --git a/Priority_Queue/2542.Maximum-Subsequence-Score/Readme.md b/Priority_Queue/2542.Maximum-Subsequence-Score/Readme.md new file mode 100644 index 000000000..e04ff8898 --- /dev/null +++ b/Priority_Queue/2542.Maximum-Subsequence-Score/Readme.md @@ -0,0 +1,7 @@ +### 2542.Maximum-Subsequence-Score + +此题和`1383.Maximum Performance of a Team`一模一样。 + +对于此类题目,我们无法同时遍历两个变量。必然是遍历一个变量,然后找另一个变量的最优值。 + +我们观察第二个因子`min(...)`有一个特性,就是随着数量的增多,其值是单调的递减。于是我们想到,将nums按照降序排列,依次考察它的前缀,就可以依次得到所有可能的min值。如果固定了一个团队中的最小值x,那么这个团队里的最大和是多少?显然是将所有大于等于x的成员里挑最大的k个相加即可,一个PQ即可实现。 From 8ccaa767efe193c1e5ff29452e2f024c9b58d0d8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Jan 2023 17:21:28 -0800 Subject: [PATCH 1557/2729] Create 2543.Check-if-Point-Is-Reachable.cpp --- .../2543.Check-if-Point-Is-Reachable.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Math/2543.Check-if-Point-Is-Reachable/2543.Check-if-Point-Is-Reachable.cpp diff --git a/Math/2543.Check-if-Point-Is-Reachable/2543.Check-if-Point-Is-Reachable.cpp b/Math/2543.Check-if-Point-Is-Reachable/2543.Check-if-Point-Is-Reachable.cpp new file mode 100644 index 000000000..377b52fc4 --- /dev/null +++ b/Math/2543.Check-if-Point-Is-Reachable/2543.Check-if-Point-Is-Reachable.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + bool isReachable(int targetX, int targetY) + { + int g = gcd((LL)targetX, (LL)targetY); + while (g%2==0) g/=2; + return g==1; + } +}; From 02ab1eea18a1a4aa20c46bb40f77bdeb3313916d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Jan 2023 17:21:52 -0800 Subject: [PATCH 1558/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 08d02e65f..e04df9232 100644 --- a/Readme.md +++ b/Readme.md @@ -1119,6 +1119,7 @@ [1819.Number-of-Different-Subsequences-GCDs](https://github.com/wisdompeak/LeetCode/tree/master/Math/1819.Number-of-Different-Subsequences-GCDs) (H-) [2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) [2344.Minimum-Deletions-to-Make-Array-Divisible](https://github.com/wisdompeak/LeetCode/tree/master/Math/2344.Minimum-Deletions-to-Make-Array-Divisible) (E) +[2543.Check-if-Point-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Math/2543.Check-if-Point-Is-Reachable) (H) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) From 028cb5d73c5f7d3c3624a6dd30efd15f95845cab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Jan 2023 17:43:04 -0800 Subject: [PATCH 1559/2729] Create Readme.md --- Math/2543.Check-if-Point-Is-Reachable/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Math/2543.Check-if-Point-Is-Reachable/Readme.md diff --git a/Math/2543.Check-if-Point-Is-Reachable/Readme.md b/Math/2543.Check-if-Point-Is-Reachable/Readme.md new file mode 100644 index 000000000..be3bf3987 --- /dev/null +++ b/Math/2543.Check-if-Point-Is-Reachable/Readme.md @@ -0,0 +1,15 @@ +### 2543.Check-if-Point-Is-Reachable + +我们反过来思考从(x,y)走到(1,1)的操作。将原操作逆过来就是 +1. (x,y)->(x+y, y) +2. (x,y)->(x, x+y) +3. (x,y)->(x/2, y) if (x%2==0) +4. (x,y)->(x, y/2) if (y%2==0) + +如果我们不看第三和第四条规则,我们可以发现,从(x,y)走到任意的(a,b),其中a必然写作mx+ny的形式。mx+ny必然含有gcd(x,y)。再考虑第三和第四条,我们只能除以2来降低数字的大小,所以如果gcd(x,y)包含非2的因子,我们是如论如何都无法除掉的,最终也不可能达到1. + +那么如果`gcd(x,y)`不含2的次方之外的元素,那么如何证明一定能转化为`(1,1)`呢?方案如下: +1. 如果x和y任意一个是偶数,就将该数字除以2。 +2. 如果x和y都是奇数,就转化为`(x,(x+y)/2)`或者`((x+y)/2,y)`,目的就是将数字变小。 + +以上两个操作都一定会将数字变小,除非`x=y=odd`。因为之前说过gcd(x,y)不含2的次方之外的元素,所以只有`x=y=1`是最终的归宿。 From 0c75bb7d5b9bfcd7ef3268a830a82e7064beabea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Jan 2023 23:38:24 -0800 Subject: [PATCH 1560/2729] Update Notes.md --- SQL/Notes.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/SQL/Notes.md b/SQL/Notes.md index 2a4fcea2b..d78a015aa 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -39,6 +39,7 @@ join UnitsSold on Prices.product_id = UnitsSold.product_id ``` #### 临时表 +定义临时表 ```sql with Temp1 as ( @@ -53,6 +54,17 @@ with Temp1 as select Round((select count(*) from Winner) / (select count(*) from Players), 2) AS fraction ``` +取临时表的某一列 +```sql +with temp as +( + select count(x) as total + from table +) +select name, total +from table, temp +``` + #### 分组最大 在原表里插入rank存为新表。再在新表里选择rank=1的行。 From e11bfe0dbbef70fd3ec975288273d6ffd0a30cfb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 15:36:14 -0800 Subject: [PATCH 1561/2729] Create 2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp --- ...Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp diff --git a/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp b/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp new file mode 100644 index 000000000..d2c1baca5 --- /dev/null +++ b/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp @@ -0,0 +1,11 @@ +### 2546.Apply-Bitwise-Operations-to-Make-Strings-Equal + +因为所有的元素都是0或者1,所以任意一对元素的操作只有四种情况: +1. (0,0)->(0,0) +2. (0,1)->(1,1) +3. (1,0)->(1,1) +4. (1,1)->(1,0) + +从中我们发现,只要s中存在一个1,它就可以将其他任何位置上的0->1或者1->0,可以进行任何想要的变化。变化之后,我们需要考虑s里的这个1本身是否需要调整。如果它不需要调整(即target对应的元素也是1),那么就ok。如果它需要调整(即target对应的元素是0),那么我们需要s里的其他已经变换过的位置上存在1来帮助我们调整,对应这意味着target上也必须存在着1. + +所以,只有当s里面有1,且t里面也有一个1(可以与s里的那个1在同一个位置,对应第一种情况;也可以在不同的位置,对应第二种情况),那么就可以实现变化。反之,如果s里面都是0,或者t里面都是0的话,就无法实现变换。 From 8ec43a6bf74b2dc5bf5d5eadbe0397a42dfacdd8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 15:36:35 -0800 Subject: [PATCH 1562/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/Readme.md diff --git a/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/Readme.md b/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/Readme.md new file mode 100644 index 000000000..d2c1baca5 --- /dev/null +++ b/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/Readme.md @@ -0,0 +1,11 @@ +### 2546.Apply-Bitwise-Operations-to-Make-Strings-Equal + +因为所有的元素都是0或者1,所以任意一对元素的操作只有四种情况: +1. (0,0)->(0,0) +2. (0,1)->(1,1) +3. (1,0)->(1,1) +4. (1,1)->(1,0) + +从中我们发现,只要s中存在一个1,它就可以将其他任何位置上的0->1或者1->0,可以进行任何想要的变化。变化之后,我们需要考虑s里的这个1本身是否需要调整。如果它不需要调整(即target对应的元素也是1),那么就ok。如果它需要调整(即target对应的元素是0),那么我们需要s里的其他已经变换过的位置上存在1来帮助我们调整,对应这意味着target上也必须存在着1. + +所以,只有当s里面有1,且t里面也有一个1(可以与s里的那个1在同一个位置,对应第一种情况;也可以在不同的位置,对应第二种情况),那么就可以实现变化。反之,如果s里面都是0,或者t里面都是0的话,就无法实现变换。 From 050561959f1ef8c9426fe6bdf2c52107147ce7da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 15:37:36 -0800 Subject: [PATCH 1563/2729] Update 2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp --- ...twise-Operations-to-Make-Strings-Equal.cpp | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp b/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp index d2c1baca5..e61dea755 100644 --- a/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp +++ b/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp @@ -1,11 +1,18 @@ -### 2546.Apply-Bitwise-Operations-to-Make-Strings-Equal - -因为所有的元素都是0或者1,所以任意一对元素的操作只有四种情况: -1. (0,0)->(0,0) -2. (0,1)->(1,1) -3. (1,0)->(1,1) -4. (1,1)->(1,0) - -从中我们发现,只要s中存在一个1,它就可以将其他任何位置上的0->1或者1->0,可以进行任何想要的变化。变化之后,我们需要考虑s里的这个1本身是否需要调整。如果它不需要调整(即target对应的元素也是1),那么就ok。如果它需要调整(即target对应的元素是0),那么我们需要s里的其他已经变换过的位置上存在1来帮助我们调整,对应这意味着target上也必须存在着1. - -所以,只有当s里面有1,且t里面也有一个1(可以与s里的那个1在同一个位置,对应第一种情况;也可以在不同的位置,对应第二种情况),那么就可以实现变化。反之,如果s里面都是0,或者t里面都是0的话,就无法实现变换。 +class Solution { +public: + bool makeStringsEqual(string s, string target) + { + if (s==target) return true; + return containOne(s) && containOne(target); + } + + bool containOne(string& s) + { + for (auto ch: s) + { + if (ch=='1') + return true; + } + return false; + } +}; From 42116876eeff10af348a4d4de48cde50792d7006 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 15:40:27 -0800 Subject: [PATCH 1564/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e04df9232..680232030 100644 --- a/Readme.md +++ b/Readme.md @@ -1189,6 +1189,7 @@ [2371.Minimize-Maximum-Value-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2371.Minimize-Maximum-Value-in-a-Grid) (M+) [2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar) (M+) [2457.Minimum-Addition-to-Make-Integer-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful) (M) +[2546.Apply-Bitwise-Operations-to-Make-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal) (M+) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From 565fbf6490ad227518c136a6ad9d2c1807c1f45b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 18:43:54 -0800 Subject: [PATCH 1565/2729] Create 2547.Minimum-Cost-to-Split-an-Array.cpp --- .../2547.Minimum-Cost-to-Split-an-Array.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/2547.Minimum-Cost-to-Split-an-Array.cpp diff --git a/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/2547.Minimum-Cost-to-Split-an-Array.cpp b/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/2547.Minimum-Cost-to-Split-an-Array.cpp new file mode 100644 index 000000000..0a3ec08a3 --- /dev/null +++ b/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/2547.Minimum-Cost-to-Split-an-Array.cpp @@ -0,0 +1,31 @@ +using LL = long long; +class Solution { + LL dp[1005]; +public: + int minCost(vector& nums, int k) + { + int n = nums.size(); + unordered_mapMap; + for (int i=0; i=0; j--) + { + Map[nums[j]]++; + if (Map[nums[j]]==2) + v+=2; + else if (Map[nums[j]]>2) + v+=1; + + if (j>=1) + dp[i] = min(dp[i], dp[j-1] + v+k); + else + dp[i] = min(dp[i], v+k); + } + } + return dp[n-1]; + + } +}; From 4acd9e3df7254358ce26ad37a434def39f65759d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 18:44:17 -0800 Subject: [PATCH 1566/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 680232030..720bba550 100644 --- a/Readme.md +++ b/Readme.md @@ -765,6 +765,7 @@ [2463.Minimum-Total-Distance-Traveled](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled) (M+) [2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings) (M+) [2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) +[2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From 7b0096a49e52d31c9c44978e6367a1b2d139465a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 18:50:02 -0800 Subject: [PATCH 1567/2729] Create Readme.md --- .../2547.Minimum-Cost-to-Split-an-Array/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/Readme.md diff --git a/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/Readme.md b/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/Readme.md new file mode 100644 index 000000000..fa212038a --- /dev/null +++ b/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/Readme.md @@ -0,0 +1,3 @@ +### 2547.Minimum-Cost-to-Split-an-Array + +很明显这是一个动态规划。我们令dp[i]表示前i个元素进行分组能够得到的最大值。我们关注截止到i为止最后一个分组的区间,故遍历一个变量j从i往前走一遍,则有dp[i]=dp[j-1]+score[j:i]。注意到移动j的过程中,score[j:i]可以用o(1)的时间得到更新。算法的整体时间复杂度就是o(n^2)。 From 79763973545a695a2ac003950906789bfcc8f027 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 19:05:48 -0800 Subject: [PATCH 1568/2729] Update 2547.Minimum-Cost-to-Split-an-Array.cpp --- .../2547.Minimum-Cost-to-Split-an-Array.cpp | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/2547.Minimum-Cost-to-Split-an-Array.cpp b/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/2547.Minimum-Cost-to-Split-an-Array.cpp index 0a3ec08a3..6a2189e12 100644 --- a/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/2547.Minimum-Cost-to-Split-an-Array.cpp +++ b/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array/2547.Minimum-Cost-to-Split-an-Array.cpp @@ -1,31 +1,29 @@ -using LL = long long; class Solution { - LL dp[1005]; + int dp[1005]; public: int minCost(vector& nums, int k) { - int n = nums.size(); - unordered_mapMap; + int n = nums.size(); + for (int i=0; iMap; + int score = 0; + dp[i] = INT_MAX; for (int j=i; j>=0; j--) { Map[nums[j]]++; if (Map[nums[j]]==2) - v+=2; + score += 2; else if (Map[nums[j]]>2) - v+=1; - + score += 1; + if (j>=1) - dp[i] = min(dp[i], dp[j-1] + v+k); + dp[i] = min(dp[i], dp[j-1] + score + k); else - dp[i] = min(dp[i], v+k); - } + dp[i] = min(dp[i], score + k); + } } return dp[n-1]; - } }; From 5aa91a0a34ac1ff577ba6e8c11e1cc9bcfa29788 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 19:15:35 -0800 Subject: [PATCH 1569/2729] Update Notes.md --- SQL/Notes.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/SQL/Notes.md b/SQL/Notes.md index d78a015aa..f23ae3d42 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -87,3 +87,12 @@ select * from A join B ``` + +### 遍历双表 +#### 相当于两个for循环遍历两张表里的row,判定相互关系 +```sql +select distinct c1.seat_id +from Cinema c1, Cinema c2 +where (c1.seat_id = c2.seat_id - 1 or c1.seat_id = c2.seat_id + 1) and c1.free = 1 and c2.free +order by c1.seat_id +``` From ef699db593d948aa3f3c87b7bc141fbbf2b08957 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jan 2023 20:08:40 -0800 Subject: [PATCH 1570/2729] Update Notes.md --- SQL/Notes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SQL/Notes.md b/SQL/Notes.md index f23ae3d42..d882134a4 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -89,9 +89,9 @@ join B ``` ### 遍历双表 -#### 相当于两个for循环遍历两张表里的row,判定相互关系 +#### 相当于两个for循环遍历两张表里的row,类似于join ```sql -select distinct c1.seat_id +select c1.seat_id, c2.seat_id from Cinema c1, Cinema c2 where (c1.seat_id = c2.seat_id - 1 or c1.seat_id = c2.seat_id + 1) and c1.free = 1 and c2.free order by c1.seat_id From c127e38a7d2ef171a7949b534127d427cefec8ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Jan 2023 19:26:00 -0800 Subject: [PATCH 1571/2729] Update Notes.md --- SQL/Notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/SQL/Notes.md b/SQL/Notes.md index d882134a4..bb2f0b7e7 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -5,6 +5,10 @@ greatest(columnA, columnB) least(columnA, columnB) ``` +#### ifnull(A, B) +Output A if A is not null, otherwise B. + + #### Union ```sql 将两段类型相同的列纵向拼接起来(组成新表)。在第一个select里可以重命名。 From 9b25dda9cf8c49edf72e738e2dbf2737add81b91 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Jan 2023 19:36:19 -0800 Subject: [PATCH 1572/2729] Update Notes.md --- SQL/Notes.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/SQL/Notes.md b/SQL/Notes.md index bb2f0b7e7..65b695fe3 100644 --- a/SQL/Notes.md +++ b/SQL/Notes.md @@ -29,11 +29,16 @@ with temp as ```sql purchase_date between Prices.start_date and Prices.end_date ``` -##### left +##### left/right 选择一个date数据“2020-19-12”的左七位数字作为month的标记。 ```sql left(trans_date, 7) as month ``` +##### datediff +计算两个时间之差(前者减后者) +```sql +datediff(a.visited_on, b.visited_on) between 0 and 6 +``` #### Join ##### Join Condition 可以有复杂的表达式 From 9df1b817def66314a9d62148cd1cd3f711e01adc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Jan 2023 19:36:37 -0800 Subject: [PATCH 1573/2729] Rename Notes.md to Read.md --- SQL/{Notes.md => Read.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename SQL/{Notes.md => Read.md} (100%) diff --git a/SQL/Notes.md b/SQL/Read.md similarity index 100% rename from SQL/Notes.md rename to SQL/Read.md From 991cc98159cdb18e720c199fb4d230a96084751f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Jan 2023 19:37:12 -0800 Subject: [PATCH 1574/2729] Rename Read.md to README.md --- SQL/{Read.md => README.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename SQL/{Read.md => README.md} (100%) diff --git a/SQL/Read.md b/SQL/README.md similarity index 100% rename from SQL/Read.md rename to SQL/README.md From 74d63245e02ed11485d35d55a3fc6b10442342df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Jan 2023 19:37:41 -0800 Subject: [PATCH 1575/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 720bba550..485a49d32 100644 --- a/Readme.md +++ b/Readme.md @@ -1430,3 +1430,5 @@ [二维子矩阵求和](https://github.com/wisdompeak/LeetCode/tree/master/Template/Sub_Rect_Sum_2D) [二维差分数组](https://github.com/wisdompeak/LeetCode/tree/master/Template/Diff_Array_2D) [CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) + +#### [SQL](https://github.com/wisdompeak/LeetCode/tree/master/SQL) From 369b471ac60a37ebba44efdebb8facf7cc0d6c36 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Jan 2023 19:38:17 -0800 Subject: [PATCH 1576/2729] Update README.md --- SQL/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SQL/README.md b/SQL/README.md index 65b695fe3..ae4376224 100644 --- a/SQL/README.md +++ b/SQL/README.md @@ -37,7 +37,7 @@ left(trans_date, 7) as month ##### datediff 计算两个时间之差(前者减后者) ```sql -datediff(a.visited_on, b.visited_on) between 0 and 6 +join XXX on datediff(a.visited_on, b.visited_on) between 0 and 6 ``` #### Join From 3ae514cac93ef2d9aa2a097934ad18aea15b9bf5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 25 Jan 2023 18:39:06 -0800 Subject: [PATCH 1577/2729] Update 076.Minimum-Window-Substring.cpp --- .../076.Minimum-Window-Substring.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/076.Minimum-Window-Substring/076.Minimum-Window-Substring.cpp b/Two_Pointers/076.Minimum-Window-Substring/076.Minimum-Window-Substring.cpp index 6bc453cea..f1343228b 100644 --- a/Two_Pointers/076.Minimum-Window-Substring/076.Minimum-Window-Substring.cpp +++ b/Two_Pointers/076.Minimum-Window-Substring/076.Minimum-Window-Substring.cpp @@ -6,6 +6,8 @@ class Solution { for (int i=0; iMap; int i=0; @@ -22,7 +24,8 @@ class Solution { if (Len>j-i+1) { Len = j-i+1; - result = s.substr(i,Len); + ret_start = i; + ret_len = Len; } Map[s[i]]--; if (Map[s[i]]==Table[s[i]]-1) @@ -30,6 +33,6 @@ class Solution { i++; } } - return result; + return s.substr(ret_start, ret_len); } }; From 67fde3ef3a30229e62b48b9fd99b0becda9fd1a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 26 Jan 2023 20:58:50 -0800 Subject: [PATCH 1578/2729] Update README.md --- SQL/README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/SQL/README.md b/SQL/README.md index ae4376224..282db8edf 100644 --- a/SQL/README.md +++ b/SQL/README.md @@ -74,8 +74,8 @@ select name, total from table, temp ``` - -#### 分组最大 +### 窗口函数 +#### 利用rank()求分区间的最大值 在原表里插入rank存为新表。再在新表里选择rank=1的行。 ```sql with temp as @@ -88,6 +88,13 @@ from temp where rnk = 1 ``` +#### 利用sum()求分区间的累积前缀 +按天数累积 +```sql +SELECT gender, day, SUM(score_points) OVER(PARTITION BY gender ORDER BY day) AS total +FROM Scores +``` + ### Join #### out join 不指定`on`的话,会将表A与表B的所有row都两两配对。 From 618589943b008a5212ef04b38bc1c6c858959c5d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 27 Jan 2023 19:48:21 -0800 Subject: [PATCH 1579/2729] Update README.md --- SQL/README.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/SQL/README.md b/SQL/README.md index 282db8edf..f468925f5 100644 --- a/SQL/README.md +++ b/SQL/README.md @@ -47,8 +47,8 @@ join UnitsSold on Prices.product_id = UnitsSold.product_id and UnitsSold.purchase_date between Prices.start_date and Prices.end_date ``` -#### 临时表 -定义临时表 +### 临时表 +#### 定义临时表 ```sql with Temp1 as ( @@ -63,7 +63,7 @@ with Temp1 as select Round((select count(*) from Winner) / (select count(*) from Players), 2) AS fraction ``` -取临时表的某一列 +#### 取临时表的某一列 ```sql with temp as ( @@ -73,6 +73,7 @@ with temp as select name, total from table, temp ``` +#### 临时表不能嵌套或者建立多于两个 ### 窗口函数 #### 利用rank()求分区间的最大值 @@ -95,6 +96,16 @@ SELECT gender, day, SUM(score_points) OVER(PARTITION BY gender ORDER BY day) AS FROM Scores ``` +#### 优先操作累积函数,再操作窗口函数 +在下面的代码里,优先考虑group by Orders.product_id, customer_id,group之后每一行就可以定义count(Orders.product_id),再按照该列对所有行进行rank +```sql +select Orders.product_id, product_name, customer_id, + rank() over (partition by customer_id order by count(Orders.product_id) desc) as rnk +from Orders +left join Products on Orders.product_id = Products.product_id +group by Orders.product_id, customer_id +``` + ### Join #### out join 不指定`on`的话,会将表A与表B的所有row都两两配对。 From 5f2af2c1a2596937c86f32d157c7041d0a64cc79 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 28 Jan 2023 17:58:23 -0800 Subject: [PATCH 1580/2729] Update 662.Maximum-Width-of-Binary-Tree.cpp --- .../662.Maximum-Width-of-Binary-Tree.cpp | 33 ++++++++++++------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/Tree/662.Maximum-Width-of-Binary-Tree/662.Maximum-Width-of-Binary-Tree.cpp b/Tree/662.Maximum-Width-of-Binary-Tree/662.Maximum-Width-of-Binary-Tree.cpp index 63d3f829d..34cb9d379 100644 --- a/Tree/662.Maximum-Width-of-Binary-Tree/662.Maximum-Width-of-Binary-Tree.cpp +++ b/Tree/662.Maximum-Width-of-Binary-Tree/662.Maximum-Width-of-Binary-Tree.cpp @@ -12,33 +12,42 @@ class Solution { int widthOfBinaryTree(TreeNode* root) { root->val = 0; - dequeq; + vectorq; q.push_back(root); int ans = 1; while (!q.empty()) { int len = q.size(); - ans = max(ans, q.back()->val - q.front()->val + 1); + ans = max(ans, q.back()->val - q[0]->val + 1); - int base = q.front()->val; + vectorvals; + vectorp; - while (len--) - { - TreeNode* node = q.front(); - q.pop_front(); - + for (int i=0; ileft) { - node->left->val = (node->val-base)*2+1; - q.push_back(node->left); + vals.push_back((long long)node->val * 2 + 1); + p.push_back(node->left); } if (node->right) { - node->right->val = (node->val-base)*2+2; - q.push_back(node->right); + vals.push_back((long long)node->val * 2 + 2); + p.push_back(node->right); } } + + if (!p.empty()) + { + for (int i=0; ival = (int)(vals[i] - vals[0]); + } + } + + q = p; } return ans; } From ee1b49009f92fec39529b4cb23c52bb93d4f77b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jan 2023 00:38:21 -0800 Subject: [PATCH 1581/2729] Update README.md --- SQL/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/SQL/README.md b/SQL/README.md index f468925f5..69f5d2147 100644 --- a/SQL/README.md +++ b/SQL/README.md @@ -106,6 +106,14 @@ left join Products on Orders.product_id = Products.product_id group by Orders.product_id, customer_id ``` +#### 窗口函数内排序后用lead求某列的下一行 +对于每个user_id,按时间先后排序visit_data。用`lead(visit_date, 1, '2021-01-01')`可以求出此时表里visit_date的下一行,其中第三个参数表示没有下一行时的默认值。 +```sql +select lead(visit_date, 1, '2021-01-01') over (partition by user_id order by visit_date) as next +from UserVisits +``` + + ### Join #### out join 不指定`on`的话,会将表A与表B的所有row都两两配对。 From f5a735a86a31936fabaa978b816dc9fd2082a11e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jan 2023 09:48:02 -0800 Subject: [PATCH 1582/2729] Update README.md --- SQL/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/SQL/README.md b/SQL/README.md index 69f5d2147..bbe96abe7 100644 --- a/SQL/README.md +++ b/SQL/README.md @@ -96,6 +96,12 @@ SELECT gender, day, SUM(score_points) OVER(PARTITION BY gender ORDER BY day) AS FROM Scores ``` +#### 各种rank函数 +rank():正常排名,允许并列。两个第一名的话,则没有第二名。 +dense_rank():正常排名,允许并列。两个第一名的话,依然有第二名。 +row_number(); 排名不允许有并列。 + + #### 优先操作累积函数,再操作窗口函数 在下面的代码里,优先考虑group by Orders.product_id, customer_id,group之后每一行就可以定义count(Orders.product_id),再按照该列对所有行进行rank ```sql From 1d6b6d6bf1c5cb7f449ff30868d0e798d4482002 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jan 2023 11:01:19 -0800 Subject: [PATCH 1583/2729] Create 2552.Count-Increasing-Quadruplets_v1.cpp --- .../2552.Count-Increasing-Quadruplets_v1.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Others/2552.Count-Increasing-Quadruplets/2552.Count-Increasing-Quadruplets_v1.cpp diff --git a/Others/2552.Count-Increasing-Quadruplets/2552.Count-Increasing-Quadruplets_v1.cpp b/Others/2552.Count-Increasing-Quadruplets/2552.Count-Increasing-Quadruplets_v1.cpp new file mode 100644 index 000000000..b5b17e2b8 --- /dev/null +++ b/Others/2552.Count-Increasing-Quadruplets/2552.Count-Increasing-Quadruplets_v1.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { +public: + long long countQuadruplets(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + LL ret = 0; + + vector>pre(n+5, vector(n+5)); + vector>post(n+5, vector(n+5)); + + for (int i=1; i<=n; i++) + for (int v=1; v<=n; v++) + { + if (nums[i] < v) + pre[i][v] = pre[i-1][v]+1; + else + pre[i][v] = pre[i-1][v]; + } + + for (int i=n; i>=1; i--) + for (int v=1; v<=n; v++) + { + if (nums[i] > v) + post[i][v] = post[i+1][v]+1; + else + post[i][v] = post[i+1][v]; + } + + for (int j=1; j<=n; j++) + for (int k=j+1; k<=n; k++) + { + if (nums[j]>nums[k]) + ret += pre[j-1][nums[k]] * post[k+1][nums[j]]; + } + + return ret; + } +}; From fc6779800c7ff9b959d31041b3b36429a1b7ba73 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jan 2023 11:01:42 -0800 Subject: [PATCH 1584/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 485a49d32..41895ea37 100644 --- a/Readme.md +++ b/Readme.md @@ -1387,6 +1387,7 @@ [1714.Sum-Of-Special-Evenly-Spaced-Elements-In-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1714.Sum-Of-Special-Evenly-Spaced-Elements-In-Array) (H) [1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/Others/1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions) (M+) [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) +[2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 76d8d1cbe91756dcd1904c7346ed4bf0b557c3ab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jan 2023 12:36:44 -0800 Subject: [PATCH 1585/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Others/2552.Count-Increasing-Quadruplets/Readme.md diff --git a/Others/2552.Count-Increasing-Quadruplets/Readme.md b/Others/2552.Count-Increasing-Quadruplets/Readme.md new file mode 100644 index 000000000..b1ea2c163 --- /dev/null +++ b/Others/2552.Count-Increasing-Quadruplets/Readme.md @@ -0,0 +1,21 @@ +### 2552.Count-Increasing-Quadruplets + +从数据规模来看,我们可以尝试n^2的时间复杂度。这意味着我们可以遍历两个变量,然后看其他两个变量能否快速得到。 + +通过尝试,我们可以试图遍历j和k的位置。一旦确定之后,就意味着我们需要在[1:j-1]里找有多少个小于nums[k]的元素,以及在[k+1:n]里找有多少个大于nums[j]的元素。将两者乘起来,就是类似(x,j,k,x)的组合的数目。 + +接下来考虑如何求[1:j-1]里找有多少个小于nums[k]的元素。这里我们利用到另一个条件,就是nums是一个permutation,即每个元素的大小不超过n。所以我们考虑将数值的大小作为一个维度。令pre[i][v]表示前i个元素里小于v的元素有多少个。我们就有递归的表达式: +```cpp +if (nums[i] < v) + pre[i][v] = pre[i-1][v] + 1; // 多了一个nums[i]满足小于v +else + pre[i][v] = pre[i-1][v]; // nums[i]>=v,对于小于v的计数没有影响。 +``` +同理,我们可以递归算出post[i][v]表示后i个元素里大于v的元素有多少个。 + +最后,我们遍历j和k,累加结果 +```cpp +for (int j=1; j<=n; j++) + for (int k=j+1; k<=n; k++) + ret += pre[j-1][nums[k]] * post[k+1][nums[j]]; +``` From 3022c75446aab79eab0b612fbc0a39d09cadc558 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jan 2023 17:28:08 -0800 Subject: [PATCH 1586/2729] Create 2551.Put-Marbles-in-Bags.cpp --- .../2551.Put-Marbles-in-Bags.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Greedy/2551.Put-Marbles-in-Bags/2551.Put-Marbles-in-Bags.cpp diff --git a/Greedy/2551.Put-Marbles-in-Bags/2551.Put-Marbles-in-Bags.cpp b/Greedy/2551.Put-Marbles-in-Bags/2551.Put-Marbles-in-Bags.cpp new file mode 100644 index 000000000..a6d00c9c3 --- /dev/null +++ b/Greedy/2551.Put-Marbles-in-Bags/2551.Put-Marbles-in-Bags.cpp @@ -0,0 +1,24 @@ +using LL = long long; +class Solution { +public: + long long putMarbles(vector& weights, int k) + { + int n = weights.size(); + if (n==1) return 0; + + vectorarr; + for (int i=0; i Date: Sun, 29 Jan 2023 17:28:40 -0800 Subject: [PATCH 1587/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 41895ea37..0153186b1 100644 --- a/Readme.md +++ b/Readme.md @@ -1191,6 +1191,7 @@ [2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2449.Minimum-Number-of-Operations-to-Make-Arrays-Similar) (M+) [2457.Minimum-Addition-to-Make-Integer-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful) (M) [2546.Apply-Bitwise-Operations-to-Make-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal) (M+) +[2551.Put-Marbles-in-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2551.Put-Marbles-in-Bags) (M+) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From 24fd0ca9964392498f903f268be58c467be7c780 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jan 2023 17:33:31 -0800 Subject: [PATCH 1588/2729] Create Readme.md --- Greedy/2551.Put-Marbles-in-Bags/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2551.Put-Marbles-in-Bags/Readme.md diff --git a/Greedy/2551.Put-Marbles-in-Bags/Readme.md b/Greedy/2551.Put-Marbles-in-Bags/Readme.md new file mode 100644 index 000000000..93019eabb --- /dev/null +++ b/Greedy/2551.Put-Marbles-in-Bags/Readme.md @@ -0,0 +1,5 @@ +### 2551.Put-Marbles-in-Bags + +显然,无论怎么分组,weights[0]和weights[n-1]是必然会计入score。接下来我们需要在n个元素中间插入k-1块隔板。每块隔板引入的score就是隔板两边的相邻元素weights之和。显然要使score最大,我们只需要选取最大的k-1个“相邻元素weight之和”即可。同理,要使score最小,我们只需要选取最小的k-1个“相邻元素weight之和”即可。 + +所以本题只需要将n-1个`weights[i]+weights[i+1]`排序即可。取最大的k-1个元素之和,减去最小的k-1个元素之和。 From f9ed4002ee62dae617fc6150855f7cd4b026f9a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 3 Feb 2023 04:25:43 -0800 Subject: [PATCH 1589/2729] test --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0153186b1..83b66c3ba 100644 --- a/Readme.md +++ b/Readme.md @@ -1,3 +1,4 @@ +test #### My YouTube Channel: [LeetCode Daily Live Coding and Interpretation](https://docs.google.com/spreadsheets/d/1kBGyRsSdbGDu7DzjQcC-UkZjZERdrP8-_QyVGXHSrB8/edit#gid=0) #### My LeetCode Daily Problem & Contest Group: [See rules and score board here](https://wisdompeak.github.io/lc-score-board/) From 7b509c5db9c7aa7efeadcaccbc11847f2bb7ac95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 3 Feb 2023 04:26:04 -0800 Subject: [PATCH 1590/2729] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index 83b66c3ba..0153186b1 100644 --- a/Readme.md +++ b/Readme.md @@ -1,4 +1,3 @@ -test #### My YouTube Channel: [LeetCode Daily Live Coding and Interpretation](https://docs.google.com/spreadsheets/d/1kBGyRsSdbGDu7DzjQcC-UkZjZERdrP8-_QyVGXHSrB8/edit#gid=0) #### My LeetCode Daily Problem & Contest Group: [See rules and score board here](https://wisdompeak.github.io/lc-score-board/) From c8ba63570919ac100a98e2a07f467f9b173d2341 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Feb 2023 15:58:17 -0800 Subject: [PATCH 1591/2729] Create 2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip.cpp --- ...in-a-Binary-Matrix-by-at-Most-One-Flip.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip.cpp diff --git a/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip.cpp b/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip.cpp new file mode 100644 index 000000000..5788b4d30 --- /dev/null +++ b/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + bool isPossibleToCutPath(vector>& grid) + { + int m = grid.size(); + int n = grid[0].size(); + for (int i=m-1; i>=0; i--) + for (int j=n-1; j>=0; j--) + { + if (i==m-1 && j==n-1) continue; + if ((i+1>=m || grid[i+1][j]==0) && (j+1>=n || grid[i][j+1]==0)) + grid[i][j] = 0; + } + if (grid[0][0]==0) return true; + + int x1=0, y1=0, x2=0, y2=0; + for (int k=0; k Date: Sat, 4 Feb 2023 15:59:00 -0800 Subject: [PATCH 1592/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0153186b1..e9ef3eaec 100644 --- a/Readme.md +++ b/Readme.md @@ -1031,6 +1031,7 @@ [1782.Count-Pairs-Of-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1782.Count-Pairs-Of-Nodes) (H) [2360.Longest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2360.Longest-Cycle-in-a-Graph) (M+) [2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even) (H-) +[2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From c6c6ade60bccf38da5f7f5fe93e7da95175f9a09 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Feb 2023 16:21:29 -0800 Subject: [PATCH 1593/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/Readme.md diff --git a/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/Readme.md b/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/Readme.md new file mode 100644 index 000000000..712a24940 --- /dev/null +++ b/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip/Readme.md @@ -0,0 +1,9 @@ +### 2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip + +本题的基本思想是构造两条尽量不相交的合法路径(即能到达终点),他们一个靠近上轮廓,一个靠近下轮廓,如果两条路径在任何一点相交,那么该点必然就是“割点”,即critical point。这里,靠近上轮廓的路径指的是贪心地优先往右走,靠近下轮廓的路径指的是贪心地优先往下走。 + +但是注意,如果完全按照贪心的策略,路径有可能进入dead end而不会到达终点,他们不能算是“轮廓”。所以我们必须去除掉那些不可能到达终点的干扰点。怎么办呢?巧妙的方法是从右下角逆向(即向左和向上)走一遍。如果某一点的下方和右方都不是1,那么说明该点无法到达终点,即使该点grid值是1,我们也将其更改赋值为0. 这样我们得到一个新的grid,每个点都能到达终点。这样我们就可以得到上轮廓和下轮廓了。 + +注意到,上轮廓和下轮廓所走的步数必然是相等的,都是从起点开始通过`m+n-2`步走到终点。所以我们只需要用一个for循环,查看到达终点前的每一步时两条路径是否重合。 + +本题的另一个思想就是对于每个位置(i,j),求起点到达该位置的方案数dp1[i][j],另外求终点逆向到达该位置的方案数dp2[i][j]。如果`dp1[i][j]*dp2[i][j] = dp1[m-1][n-1]`,说明该点就是割点。但是对于本题的数据量,dp的值是`2^1000`,所以需要实时取模并会有冲突的风险。 From d1e53ac62fc33adac1806cd838ad6f9d00f642a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Feb 2023 17:19:26 -0800 Subject: [PATCH 1594/2729] Create 2555.-Maximize-Win-From-Two-Segments.cpp --- .../2555.-Maximize-Win-From-Two-Segments.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/2555.-Maximize-Win-From-Two-Segments/2555.-Maximize-Win-From-Two-Segments.cpp diff --git a/Greedy/2555.-Maximize-Win-From-Two-Segments/2555.-Maximize-Win-From-Two-Segments.cpp b/Greedy/2555.-Maximize-Win-From-Two-Segments/2555.-Maximize-Win-From-Two-Segments.cpp new file mode 100644 index 000000000..17e809565 --- /dev/null +++ b/Greedy/2555.-Maximize-Win-From-Two-Segments/2555.-Maximize-Win-From-Two-Segments.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int maximizeWin(vector& p, int k) + { + int n = p.size(); + if (p[n-1]-p[0] <= 2*k) return p.size(); + + vectorpre(n); + vectorpost(n); + + int i = 0; + int mx = 0; + for (int j=0; jk) + i++; + mx = max(mx, j-i+1); + pre[j] = mx; + } + + int j = n-1; + mx = 0; + for (int i=n-1; i>=0; i--) + { + while (p[j]-p[i]>k) + j--; + mx = max(mx, j-i+1); + post[i] = mx; + } + + int ret = 0; + for (int i=0; i+1 Date: Sat, 4 Feb 2023 17:20:05 -0800 Subject: [PATCH 1595/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e9ef3eaec..2d92750f6 100644 --- a/Readme.md +++ b/Readme.md @@ -1224,6 +1224,7 @@ [1888.Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1888.Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating) (M+) [2163.Minimum-Difference-in-Sums-After-Removal-of-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements) (M+) [2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods) (H-) +[2555.-Maximize-Win-From-Two-Segments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2555.-Maximize-Win-From-Two-Segments) (M+) * ``State Machine`` [524.Longest-Word-in-Dictionary-through-Deleting](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/524.Longest-Word-in-Dictionary-through-Deleting) (M+) [727.Minimum-Window-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/727.Minimum-Window-Subsequence) (H-) From 5915c6128f707a81aa96758ca2d58483f10873df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Feb 2023 22:35:25 -0800 Subject: [PATCH 1596/2729] Rename 2555.-Maximize-Win-From-Two-Segments.cpp to 2555.Maximize-Win-From-Two-Segments.cpp --- ...m-Two-Segments.cpp => 2555.Maximize-Win-From-Two-Segments.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/2555.-Maximize-Win-From-Two-Segments/{2555.-Maximize-Win-From-Two-Segments.cpp => 2555.Maximize-Win-From-Two-Segments.cpp} (100%) diff --git a/Greedy/2555.-Maximize-Win-From-Two-Segments/2555.-Maximize-Win-From-Two-Segments.cpp b/Greedy/2555.-Maximize-Win-From-Two-Segments/2555.Maximize-Win-From-Two-Segments.cpp similarity index 100% rename from Greedy/2555.-Maximize-Win-From-Two-Segments/2555.-Maximize-Win-From-Two-Segments.cpp rename to Greedy/2555.-Maximize-Win-From-Two-Segments/2555.Maximize-Win-From-Two-Segments.cpp From b1fb28223c8c17e9bb01a6bbc1e73c609d058dc2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Feb 2023 22:56:59 -0800 Subject: [PATCH 1597/2729] Rename Greedy/2555.-Maximize-Win-From-Two-Segments/2555.Maximize-Win-From-Two-Segments.cpp to Greedy/2555.Maximize-Win-From-Two-Segments/2555.Maximize-Win-From-Two-Segments.cpp --- .../2555.Maximize-Win-From-Two-Segments.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/{2555.-Maximize-Win-From-Two-Segments => 2555.Maximize-Win-From-Two-Segments}/2555.Maximize-Win-From-Two-Segments.cpp (100%) diff --git a/Greedy/2555.-Maximize-Win-From-Two-Segments/2555.Maximize-Win-From-Two-Segments.cpp b/Greedy/2555.Maximize-Win-From-Two-Segments/2555.Maximize-Win-From-Two-Segments.cpp similarity index 100% rename from Greedy/2555.-Maximize-Win-From-Two-Segments/2555.Maximize-Win-From-Two-Segments.cpp rename to Greedy/2555.Maximize-Win-From-Two-Segments/2555.Maximize-Win-From-Two-Segments.cpp From 8f60e63661ec4daf2d90b0b141ab1da3d889251e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Feb 2023 22:58:06 -0800 Subject: [PATCH 1598/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2d92750f6..f058aedb1 100644 --- a/Readme.md +++ b/Readme.md @@ -1224,7 +1224,7 @@ [1888.Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1888.Minimum-Number-of-Flips-to-Make-the-Binary-String-Alternating) (M+) [2163.Minimum-Difference-in-Sums-After-Removal-of-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements) (M+) [2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods) (H-) -[2555.-Maximize-Win-From-Two-Segments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2555.-Maximize-Win-From-Two-Segments) (M+) +[2555.Maximize-Win-From-Two-Segments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2555.Maximize-Win-From-Two-Segments) (M+) * ``State Machine`` [524.Longest-Word-in-Dictionary-through-Deleting](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/524.Longest-Word-in-Dictionary-through-Deleting) (M+) [727.Minimum-Window-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/727.Minimum-Window-Subsequence) (H-) From 20e67e45259fa779a1697a85e8d6fc823980d869 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Feb 2023 23:29:43 -0800 Subject: [PATCH 1599/2729] Create Readme.md --- Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md diff --git a/Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md b/Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md new file mode 100644 index 000000000..0e704b278 --- /dev/null +++ b/Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md @@ -0,0 +1,7 @@ +### 2555.Maximize-Win-From-Two-Segments + +为了尽量大地增加收益,我们肯定不会让这两段区间重叠,即会让两段区间各自占满k的长度;除非总长度小于2k,那样的话,我们就取全部的点即可。 + +接下来我们考虑,如何取一段长度为k的区间,使得区间内包含的点的数目最多。这个也很容易,只要确定了左端点i,那么单向移动右端点j即可,当恰好`p[j]-p[i]>k`时,说明`j-i`就是以i为左端点的最大区间,我们记做left[i]。同理,我们也可以计算以j为右端点的最大区间right[j]。 + +那么回到两个区间的问题。因为两段区间不重合,所以我们只要找一个分界点k,在k左边找一个最大区间,在k右边找一个最大区间,两者之和就是以k为分界点所能得到的两个区间。显然,前者就是right[j]的前缀Max,后者就是left[i]的后缀Max。 From 5eec18ab3aeb0a50cdb5df283279176d946e7923 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Feb 2023 23:32:35 -0800 Subject: [PATCH 1600/2729] Update Readme.md --- Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md b/Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md index 0e704b278..99aaed330 100644 --- a/Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md +++ b/Greedy/2555.Maximize-Win-From-Two-Segments/Readme.md @@ -2,6 +2,6 @@ 为了尽量大地增加收益,我们肯定不会让这两段区间重叠,即会让两段区间各自占满k的长度;除非总长度小于2k,那样的话,我们就取全部的点即可。 -接下来我们考虑,如何取一段长度为k的区间,使得区间内包含的点的数目最多。这个也很容易,只要确定了左端点i,那么单向移动右端点j即可,当恰好`p[j]-p[i]>k`时,说明`j-i`就是以i为左端点的最大区间,我们记做left[i]。同理,我们也可以计算以j为右端点的最大区间right[j]。 +接下来我们考虑,如何取一段长度为k的区间,使得区间内包含的点的数目最多。这个也很容易,只要确定了左端点i,那么单向移动右端点j即可,当恰好`p[j]-p[i]>k`时,说明`j-i`就是以i为左端点的、长度为k的区间的最大元素数目,我们记做left[i]。同理,我们也可以计算以j为右端点的、长度为k的区间的最大元素数目right[j]。 -那么回到两个区间的问题。因为两段区间不重合,所以我们只要找一个分界点k,在k左边找一个最大区间,在k右边找一个最大区间,两者之和就是以k为分界点所能得到的两个区间。显然,前者就是right[j]的前缀Max,后者就是left[i]的后缀Max。 +那么回到两个区间的问题。因为两段区间不重合,所以我们只要找一个分界点k,在k左边找一个最大数目区间(注意其右端点不一定就是在k),在k右边找一个最大数目区间(注意其左端点也不一定就是k),两者之和就是以k为分界点所能得到的两个区间。注意到,前者是right[j]的前缀Max,后者是left[i]的后缀Max。 From 6dfd9570e3f9a0389d059ed3c81ed4323358f447 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Feb 2023 19:01:58 -0800 Subject: [PATCH 1601/2729] Update README.md --- SQL/README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/SQL/README.md b/SQL/README.md index bbe96abe7..85b52364c 100644 --- a/SQL/README.md +++ b/SQL/README.md @@ -73,8 +73,15 @@ with temp as select name, total from table, temp ``` -#### 临时表不能嵌套或者建立多于两个 - +#### 多个临时表 +```sql +with temp as +(...), +temp2 as +(...) +select * +from temp2 +``` ### 窗口函数 #### 利用rank()求分区间的最大值 在原表里插入rank存为新表。再在新表里选择rank=1的行。 From 095fe5540e0424bd3ab5c05bc9f4f9ceaf40d0a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Feb 2023 19:15:47 -0800 Subject: [PATCH 1602/2729] Create 2560.House-Robber-IV.cpp --- .../2560.House-Robber-IV.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp diff --git a/Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp b/Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp new file mode 100644 index 000000000..d75ed2a06 --- /dev/null +++ b/Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp @@ -0,0 +1,43 @@ +class Solution { + int dp[100005][2]; +public: + int minCapability(vector& nums, int k) + { + int left = 0, right = INT_MAX/2; + while (left < right) + { + int mid = left+(right-left)/2; + if (isOK(mid, nums, k)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(int cap, vector& nums, int k) + { + int n = nums.size(); + dp[0][0] = 0; + if (nums[0] <= cap) + dp[0][1] = 1; + else + dp[0][1] = INT_MIN/2; + + for (int i=1; i cap) + { + dp[i][0] = max(dp[i-1][0], dp[i-1][1]); + dp[i][1] = INT_MIN/2; + } + else + { + dp[i][0] = max(dp[i-1][0], dp[i-1][1]); + dp[i][1] = dp[i-1][0]+1; + } + } + + return max(dp[n-1][0], dp[n-1][1]) >= k; + } +}; From be5807bb19cddb15ae2a0b5d45f3468dbd4934a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Feb 2023 19:16:27 -0800 Subject: [PATCH 1603/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f058aedb1..be0ad73dc 100644 --- a/Readme.md +++ b/Readme.md @@ -120,6 +120,7 @@ [2517.Maximum-Tastiness-of-Candy-Basket](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket) (M+) [2513.Minimize-the-Maximum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays) (H) [2528.Maximize-the-Minimum-Powered-City](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2528.Maximize-the-Minimum-Powered-City) (H-) +[2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 2fb854cd573578125d43b9a302e0b59c265faa92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Feb 2023 20:41:35 -0800 Subject: [PATCH 1604/2729] Create 2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp --- ...-of-Integers-to-Choose-From-a-Range-II.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp diff --git a/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp b/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp new file mode 100644 index 000000000..ce7a78ee7 --- /dev/null +++ b/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp @@ -0,0 +1,32 @@ +class Solution { + vectorpresum; +public: + int maxCount(vector& banned, int n, long long maxSum) + { + sort(banned.begin(), banned.end()); + + presum.resize(banned.size()); + for (int i=0; i& banned, int n, long long maxSum) + { + int t = upper_bound(banned.begin(), banned.end(), m) - banned.begin(); + long long sum = (1+m)*m/2 - (t==0?0:presum[t-1]); + return sum > maxSum; + } +}; From 3d153b086001518f9a913a4ade77e979f85faa07 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Feb 2023 22:37:29 -0800 Subject: [PATCH 1605/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/Readme.md diff --git a/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/Readme.md b/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/Readme.md new file mode 100644 index 000000000..f5a716dcc --- /dev/null +++ b/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/Readme.md @@ -0,0 +1,9 @@ +### 2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II + +我们猜测能够取到的最大的数值为m。只要确定了m,我们可以计算出[1,m]之间能够取到的元素的和sum是多少。如果sum大于maxSum,那么我们就猜测更小的m,否则就猜更大的数。 + +如何计算sum呢?首先就是计算1到m的等差数列之和。然后在排序后的banned里用upper_bound定位第一个大于m的位置。如果这个位置的index是t,那么就意味着banned里面有t个元素小于等于m,那么我们就需要将banned的前t个元素的和减去。 + +我们二分搜索求出m之后,还需要减去t,才是最后的答案。 + +注意,二分搜索的收敛值m有可能是banned中的元素,但是对于本题的解没有影响。因为本题的答案是最终取多少个元素。m终究是会被减去的。 From 49dcfd3c83200bf9f77b87a2ee4f43b8572e7a55 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Feb 2023 23:29:29 -0800 Subject: [PATCH 1606/2729] Create Readme.md --- Binary_Search/2560.House-Robber-IV/Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Binary_Search/2560.House-Robber-IV/Readme.md diff --git a/Binary_Search/2560.House-Robber-IV/Readme.md b/Binary_Search/2560.House-Robber-IV/Readme.md new file mode 100644 index 000000000..b5d00e82c --- /dev/null +++ b/Binary_Search/2560.House-Robber-IV/Readme.md @@ -0,0 +1,17 @@ +### 2560.House-Robber-IV + +这道题的题意需要仔细理解。最小化capability意味着我们需要尽量挑数值小的house,但是如果我们挑的数值都太小的话,就没有足够的house来满足“at least k houses”的约束。于是我们就发现了单调性的变化:capability越小,那么可选的house就越少。capability越大,那么可选的house就越多。于是我们需要找恰好的capability,使得可选的house恰好大于等于k。因此,这是一个二分搜值的算法。 + +我们猜测需要的capability是c,那么可以选多少house呢?满足两个条件:挑选的house的数值不能大于c,挑选的house不能相邻。对于后者,我们知道house robber的一个通用技巧,就是对每一个house都讨论取还是不取两种策略。所以我们令`dp[i][0]`表示第i个house不抢的策略下所能选中的house数目,`dp[i][1]`表示第i个house抢的策略下所能选中的house数目。 + +考虑第i个房子,如果`house[i]>c`,我们终归是不能抢的,故第i-1个house抢不抢无所谓。 +```cpp +dp[i][0] = max(dp[i-1][0], dp[i-1][1]); +dp[i][1] = INT_MIN/2; +``` +考虑第i个房子,如果`house[i]<=c`,我们可以选择抢,也可以选择不抢 +```cpp +dp[i][0] = max(dp[i-1][0], dp[i-1][1]); +dp[i][1] = dp[i-1][0]; +``` +由此将所有的dp[i][x]都更新。最后考察dp[n-1][x]能否大于k,即意味着在当前c的设置下,能否实现至少抢k个房子。 From af693877986fad6d81a2e546ae1b8162446e86f4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Feb 2023 23:29:48 -0800 Subject: [PATCH 1607/2729] Update 2560.House-Robber-IV.cpp --- Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp b/Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp index d75ed2a06..045399b45 100644 --- a/Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp +++ b/Binary_Search/2560.House-Robber-IV/2560.House-Robber-IV.cpp @@ -7,7 +7,7 @@ class Solution { while (left < right) { int mid = left+(right-left)/2; - if (isOK(mid, nums, k)) + if (atLeastK(mid, nums, k)) right = mid; else left = mid+1; @@ -15,7 +15,7 @@ class Solution { return left; } - bool isOK(int cap, vector& nums, int k) + bool atLeastK(int cap, vector& nums, int k) { int n = nums.size(); dp[0][0] = 0; From c9f0623b8f57a250f11d07005b263087d090744a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Feb 2023 00:07:54 -0800 Subject: [PATCH 1608/2729] Create 689.Maximum-Sum-of-3-Non-Overlapping-Subarrays.cpp --- ...mum-Sum-of-3-Non-Overlapping-Subarrays.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays.cpp diff --git a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays.cpp b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays.cpp new file mode 100644 index 000000000..6329128b2 --- /dev/null +++ b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + vector maxSumOfThreeSubarrays(vector& nums, int k) + { + int n = nums.size(); + vectorpresum(n); + for (int i=0; ileftMax(n,0); + vectorleftIdx(n,0); + int maxSum = 0; + int maxIdx = 0; + for (int i=k-1; i maxSum) + { + maxSum = sum; + maxIdx = i-k+1; + } + leftMax[i] = maxSum; + leftIdx[i] = maxIdx; + } + + vectorrightMax(n,0); + vectorrightIdx(n,0); + maxSum = 0; + maxIdx = 0; + for (int i=n-k; i>=0; i--) + { + // [i : i+k-1] + int sum = presum[i+k-1] - (i==0?0:presum[i-1]); + if (sum >= maxSum) + { + maxSum = sum; + maxIdx = i; + } + rightMax[i] = maxSum; + rightIdx[i] = maxIdx; + } + + vectorrets; + maxSum = 0; + for (int i=k; i+2*k<=n; i++) + { + int sum = presum[i+k-1] - (i==0?0:presum[i-1]); + if (sum + leftMax[i-1] + rightMax[i+k] > maxSum) + { + maxSum = sum + leftMax[i-1] + rightMax[i+k]; + rets = {leftIdx[i-1], i, rightIdx[i+k]}; + } + } + + return rets; + } +}; From f31c258253b66012c80386e02c6b8b119fa929b3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Feb 2023 00:08:27 -0800 Subject: [PATCH 1609/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index be0ad73dc..d34f67f94 100644 --- a/Readme.md +++ b/Readme.md @@ -1215,6 +1215,7 @@ * ``Three-pass`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H-) [334.Increasing-Triplet-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/334.Increasing-Triplet-Subsequence) (H-) +[689.Maximum-Sum-of-3-Non-Overlapping-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays) (M+) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H) [1525.Number-of-Good-Ways-to-Split-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1525.Number-of-Good-Ways-to-Split-a-String) (M) [1638.Count-Substrings-That-Differ-by-One-Character](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1638.Count-Substrings-That-Differ-by-One-Character) (M+) @@ -1308,7 +1309,6 @@ [311.Sparse-Matrix-Multiplication](https://github.com/wisdompeak/LeetCode/tree/master/Others/311.Sparse-Matrix-Multiplication) (M) 168.Excel-Sheet-Column-Title (H) 453.Minimum-Moves-to-Equal-Array-Elements (M) -689.Maximum-Sum-of-3-Non-Overlapping-Subarrays (M+) [782.Transform-to-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/Others/782.Transform-to-Chessboard) (H+) [466.Count-The-Repetitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/466.Count-The-Repetitions) (H) [810.Chalkboard-XOR-Game](https://github.com/wisdompeak/LeetCode/tree/master/Others/810.Chalkboard-XOR-Game) (H) From 4b5a563ed0ba1d59151e7fd0eecba04465bc7048 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Feb 2023 00:18:53 -0800 Subject: [PATCH 1610/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md diff --git a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md new file mode 100644 index 000000000..9d21a5e08 --- /dev/null +++ b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md @@ -0,0 +1,7 @@ +### 689.Maximum-Sum-of-3-Non-Overlapping-Subarrays + +这道题可以用动态规划很方便地求解最大值,但是如果要记录最大值所对应的区间的位置,则会略显麻烦。 + +考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是[i:i+k-1],那么我们只需要求在[0:i-1]内最大的长度为k的区间,以及在[i+1:n-1]内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1]+sum[i:i+k-1]+rightMax[i+k]`即可。 + +除此之外,我们还需要记录下leftMax[i]所对应的最大滑窗的位置,即为leftIdx[i]。这里要注意一个细节,因为题意要求,如果有多个总和相同的解,取index位置最小的解。所以我们从左往右遍历的时候,只有在leftMax大于历史最大值的时候才更新leftIdx,这样在相同的leftMax的时候我们保留的是较小的index。同理,我们在从右往左遍历的时候,当rightMax大于等于历史最大值,就可以更新rightIdx,这样在相同的rightMax的时候我们保留的是较小的index。 From 4836a651c559abcf7ac116c469539b14f322764c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Feb 2023 00:19:30 -0800 Subject: [PATCH 1611/2729] Update Readme.md --- Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md index 9d21a5e08..0ba37f12e 100644 --- a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md +++ b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md @@ -2,6 +2,6 @@ 这道题可以用动态规划很方便地求解最大值,但是如果要记录最大值所对应的区间的位置,则会略显麻烦。 -考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是[i:i+k-1],那么我们只需要求在[0:i-1]内最大的长度为k的区间,以及在[i+1:n-1]内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1]+sum[i:i+k-1]+rightMax[i+k]`即可。 +考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是`[i:i+k-1]`,那么我们只需要求在`[0:i-1]`内最大的长度为k的区间,以及在`[i+1:n-1]`内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1] +sum[i:i+k-1] +rightMax[i+k]`即可。 除此之外,我们还需要记录下leftMax[i]所对应的最大滑窗的位置,即为leftIdx[i]。这里要注意一个细节,因为题意要求,如果有多个总和相同的解,取index位置最小的解。所以我们从左往右遍历的时候,只有在leftMax大于历史最大值的时候才更新leftIdx,这样在相同的leftMax的时候我们保留的是较小的index。同理,我们在从右往左遍历的时候,当rightMax大于等于历史最大值,就可以更新rightIdx,这样在相同的rightMax的时候我们保留的是较小的index。 From d0faee5541f3062b2788fe8047d10fc32eeed2e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 9 Feb 2023 00:19:50 -0800 Subject: [PATCH 1612/2729] Update Readme.md --- Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md index 0ba37f12e..6050ccedc 100644 --- a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md +++ b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md @@ -2,6 +2,6 @@ 这道题可以用动态规划很方便地求解最大值,但是如果要记录最大值所对应的区间的位置,则会略显麻烦。 -考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是`[i:i+k-1]`,那么我们只需要求在`[0:i-1]`内最大的长度为k的区间,以及在`[i+1:n-1]`内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1] +sum[i:i+k-1] +rightMax[i+k]`即可。 +考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是`[i:i+k-1]`,那么我们只需要求在`[0:i-1]`内最大的长度为k的区间,以及在`[i+1:n-1]`内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1] + sum[i:i+k-1] + rightMax[i+k]`即可。 除此之外,我们还需要记录下leftMax[i]所对应的最大滑窗的位置,即为leftIdx[i]。这里要注意一个细节,因为题意要求,如果有多个总和相同的解,取index位置最小的解。所以我们从左往右遍历的时候,只有在leftMax大于历史最大值的时候才更新leftIdx,这样在相同的leftMax的时候我们保留的是较小的index。同理,我们在从右往左遍历的时候,当rightMax大于等于历史最大值,就可以更新rightIdx,这样在相同的rightMax的时候我们保留的是较小的index。 From c2b704068bd0737799c366aafa74ea9222039cc5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 00:02:15 -0800 Subject: [PATCH 1613/2729] Create 2561.Rearranging-Fruits.cpp --- .../2561.Rearranging-Fruits.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Greedy/2561.Rearranging-Fruits/2561.Rearranging-Fruits.cpp diff --git a/Greedy/2561.Rearranging-Fruits/2561.Rearranging-Fruits.cpp b/Greedy/2561.Rearranging-Fruits/2561.Rearranging-Fruits.cpp new file mode 100644 index 000000000..0fadebbb7 --- /dev/null +++ b/Greedy/2561.Rearranging-Fruits/2561.Rearranging-Fruits.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + long long minCost(vector& basket1, vector& basket2) + { + mapMap; + for (int x: basket1) + Map[x]++; + for (int x: basket2) + Map[x]--; + + int t = Map.begin()->first; + + vectora; + for (auto [k,v]: Map) + { + if (v%2!=0) return -1; + if (v>0) + { + for (int i=0; i Date: Sat, 11 Feb 2023 00:02:45 -0800 Subject: [PATCH 1614/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d34f67f94..476135c09 100644 --- a/Readme.md +++ b/Readme.md @@ -1194,6 +1194,7 @@ [2457.Minimum-Addition-to-Make-Integer-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2457.Minimum-Addition-to-Make-Integer-Beautiful) (M) [2546.Apply-Bitwise-Operations-to-Make-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal) (M+) [2551.Put-Marbles-in-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2551.Put-Marbles-in-Bags) (M+) +[2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From ee4e6990f86231e5c260cf49fc57a4f5068027fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 00:41:29 -0800 Subject: [PATCH 1615/2729] Create Readme.md --- Greedy/2561.Rearranging-Fruits/Readme.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Greedy/2561.Rearranging-Fruits/Readme.md diff --git a/Greedy/2561.Rearranging-Fruits/Readme.md b/Greedy/2561.Rearranging-Fruits/Readme.md new file mode 100644 index 000000000..c41fa5fb7 --- /dev/null +++ b/Greedy/2561.Rearranging-Fruits/Readme.md @@ -0,0 +1,16 @@ +### 2561.Rearranging-Fruits + +如果有些元素在两个数组里都成对出现过,显然我们不会去移动他们。所以我们会用一个hash表,记录每种元素在两个数组里的频次差值。比如`Map[3]=2`,表示数字3在篮子一里比在篮子二里多出现了2次。反之,`Map[4]=-3`,表示数字4在篮子一里比在篮子二里少出现了3次。 + +为了让最后每个元素能在调整之后,出现在两个数组里的频次一样多,那么hash表的value,无论正负,必须都是偶数。否则就无解。 + +接下来,我们通过这个hash表,根据value/2写出两个数组A与B,可以知道数组A有哪些元素需要换到B里,以及数组B有些元素需要换到A里。显然,这些元素必须的数目都必然相等。我们将它们各自排序后,记做 +``` +A: X X X X X X +B: Y Y Y Y Y Y +``` +根据规则,每次操作是AB里的元素的对换,代价是`min{x,y}`。所以会充分利用较小的元素使其成为“代价”来同时换掉较大的数。根据这个规则,假设在上面AB里全局最小的元素是A1,那么它必然会与B的最大元素进行对调。再接下来,假设全局第二小的元素是B1,那么它必然会与A的最大元素进行对调。再记下来,假设全局第三小的元素是B2,那么它必然与A的第二大元素进行对调.... 假设A和B里各自都有n个元素,那么我们进行n次对换的代价,其实就是AB数组里较小的一半(n个)元素。所以我们只需要将AB混合起来,取较小的一半元素之和即可。 + +但是本题还有另外一种策略。假设在初始状态下,可能全局有一个最小的元素t,但它在两个篮子里出现的频次相等,因此虽然理论上并不需要将t参与交换(即不出现在AB里)。但是我们发现,如果之前方案中交换一次的“代价”大于2t的话,我们不妨就将t作为媒介引入交换。比如,我们想将x与y直接交换,代价是x。但我们可以将步骤改为:将x与t交换,代价是t;再将t与y交换,代价是t。这样总代价就是2t,可能比x还小。 + +所以最终的答案是,将AB数组混合取最小的n个元素,每个同时再与`2t`取小,最终累加起来。 From 56d445fb6518a069a2b9d47adac96cc6d7cf8aef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 12:41:49 -0800 Subject: [PATCH 1616/2729] Create Readme.md --- SQL/Date/Readme.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 SQL/Date/Readme.md diff --git a/SQL/Date/Readme.md b/SQL/Date/Readme.md new file mode 100644 index 000000000..ada5871e8 --- /dev/null +++ b/SQL/Date/Readme.md @@ -0,0 +1,21 @@ +### 日期类型的操作 + +#### year() +取一个date数据类型的年份 + +#### between +```sql +purchase_date between Prices.start_date and Prices.end_date +``` + +#### left/right +选择一个date数据“2020-19-12”的左七位数字作为month的标记。 +```sql +left(trans_date, 7) as month +``` + +#### datediff +计算两个时间之差(前者减后者) +```sql +join XXX on datediff(a.visited_on, b.visited_on) between 0 and 6 +``` From 9a579ae5466490c5cb6c027d099c996f8c8fd769 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 12:41:54 -0800 Subject: [PATCH 1617/2729] Update README.md --- SQL/README.md | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/SQL/README.md b/SQL/README.md index 85b52364c..a722aed47 100644 --- a/SQL/README.md +++ b/SQL/README.md @@ -1,3 +1,7 @@ +#### the Nth element +order by XXX +limit 1 offset 10 + #### greatest, least 在同一行的多个列中选择最大/最小的一个 ```sql @@ -24,22 +28,6 @@ with temp as ) ``` -#### 日期类型的操作 -##### between -```sql -purchase_date between Prices.start_date and Prices.end_date -``` -##### left/right -选择一个date数据“2020-19-12”的左七位数字作为month的标记。 -```sql -left(trans_date, 7) as month -``` -##### datediff -计算两个时间之差(前者减后者) -```sql -join XXX on datediff(a.visited_on, b.visited_on) between 0 and 6 -``` - #### Join ##### Join Condition 可以有复杂的表达式 ```sql From 4a468e1facea9a9390f0dd08381b9cef78e54cc4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 12:42:55 -0800 Subject: [PATCH 1618/2729] Update Readme.md --- SQL/Date/Readme.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/SQL/Date/Readme.md b/SQL/Date/Readme.md index ada5871e8..43ecfd1aa 100644 --- a/SQL/Date/Readme.md +++ b/SQL/Date/Readme.md @@ -2,6 +2,9 @@ #### year() 取一个date数据类型的年份 +```sql +where year(date)=1997 +``` #### between ```sql From 909b531c003e026cc68776785d82e5a6423cfe97 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 13:17:57 -0800 Subject: [PATCH 1619/2729] Update Readme.md --- SQL/Date/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SQL/Date/Readme.md b/SQL/Date/Readme.md index 43ecfd1aa..db3aa37f7 100644 --- a/SQL/Date/Readme.md +++ b/SQL/Date/Readme.md @@ -3,7 +3,7 @@ #### year() 取一个date数据类型的年份 ```sql -where year(date)=1997 +where year(date) = 1997 ``` #### between From 36a817443ce802fc480daa1fa031768ff2f5985e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 13:25:31 -0800 Subject: [PATCH 1620/2729] Create README.md --- SQL/Window_Function/README.md | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 SQL/Window_Function/README.md diff --git a/SQL/Window_Function/README.md b/SQL/Window_Function/README.md new file mode 100644 index 000000000..2c7e7e26c --- /dev/null +++ b/SQL/Window_Function/README.md @@ -0,0 +1,43 @@ +### 窗口函数 + +#### 利用rank()求分区间的最大值 +在原表里插入rank存为新表。再在新表里选择rank=1的行。 +```sql +with temp as +( + select *, rank() over (partition by student_id order by grade desc, course_id) as rnk + from Enrollments +) +select student_id, course_id, grade +from temp +where rnk = 1 +``` + +#### 利用sum()求分区间的累积前缀 +按天数累积 +```sql +SELECT gender, day, SUM(score_points) OVER(PARTITION BY gender ORDER BY day) AS total +FROM Scores +``` + +#### 各种rank函数 +rank():正常排名,允许并列。两个第一名的话,则没有第二名。 +dense_rank():正常排名,允许并列。两个第一名的话,依然有第二名。 +row_number(); 排名不允许有并列。 + +#### 优先操作累积函数,再操作窗口函数 +在下面的代码里,优先考虑group by Orders.product_id, customer_id,group之后每一行就可以定义count(Orders.product_id),再按照该列对所有行进行rank +```sql +select Orders.product_id, product_name, customer_id, + rank() over (partition by customer_id order by count(Orders.product_id) desc) as rnk +from Orders +left join Products on Orders.product_id = Products.product_id +group by Orders.product_id, customer_id +``` + +#### 窗口函数内排序后用lead求某列的下一行 +对于每个user_id,按时间先后排序visit_data。用`lead(visit_date, 1, '2021-01-01')`可以求出此时表里visit_date的下一行,其中第三个参数表示没有下一行时的默认值。 +```sql +select lead(visit_date, 1, '2021-01-01') over (partition by user_id order by visit_date) as next +from UserVisits +``` From 04efd2f7c69f9e4e25a23bdc673e41a121831307 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 13:26:29 -0800 Subject: [PATCH 1621/2729] Update README.md --- SQL/Window_Function/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SQL/Window_Function/README.md b/SQL/Window_Function/README.md index 2c7e7e26c..7c0025f15 100644 --- a/SQL/Window_Function/README.md +++ b/SQL/Window_Function/README.md @@ -21,9 +21,9 @@ FROM Scores ``` #### 各种rank函数 -rank():正常排名,允许并列。两个第一名的话,则没有第二名。 -dense_rank():正常排名,允许并列。两个第一名的话,依然有第二名。 -row_number(); 排名不允许有并列。 +rank():正常排名,允许并列。两个第一名的话,则没有第二名。 +dense_rank():正常排名,允许并列。两个第一名的话,依然有第二名。 +row_number(); 排名不允许有并列。 #### 优先操作累积函数,再操作窗口函数 在下面的代码里,优先考虑group by Orders.product_id, customer_id,group之后每一行就可以定义count(Orders.product_id),再按照该列对所有行进行rank From e8e74159ab4f9127fbbc2f3eb6225e1c4e92829b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 13:29:59 -0800 Subject: [PATCH 1622/2729] Update README.md --- SQL/Window_Function/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SQL/Window_Function/README.md b/SQL/Window_Function/README.md index 7c0025f15..6e7f94c65 100644 --- a/SQL/Window_Function/README.md +++ b/SQL/Window_Function/README.md @@ -26,7 +26,7 @@ dense_rank():正常排名,允许并列。两个第一名的话,依然有 row_number(); 排名不允许有并列。 #### 优先操作累积函数,再操作窗口函数 -在下面的代码里,优先考虑group by Orders.product_id, customer_id,group之后每一行就可以定义count(Orders.product_id),再按照该列对所有行进行rank +在下面的代码里,优先考虑`group by Orders.product_id, customer_id`,group之后每一行就可以定义count(Orders.product_id),再依据customer_id的分区分别进行rank ```sql select Orders.product_id, product_name, customer_id, rank() over (partition by customer_id order by count(Orders.product_id) desc) as rnk From e7a4f0c85449ca748a9eacab0ef23fefeebc54fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 13:31:03 -0800 Subject: [PATCH 1623/2729] Update README.md --- SQL/README.md | 44 -------------------------------------------- 1 file changed, 44 deletions(-) diff --git a/SQL/README.md b/SQL/README.md index a722aed47..869acc44c 100644 --- a/SQL/README.md +++ b/SQL/README.md @@ -70,50 +70,6 @@ temp2 as select * from temp2 ``` -### 窗口函数 -#### 利用rank()求分区间的最大值 -在原表里插入rank存为新表。再在新表里选择rank=1的行。 -```sql -with temp as -( - select *, rank() over (partition by student_id order by grade desc, course_id) as rnk - from Enrollments -) -select student_id, course_id, grade -from temp -where rnk = 1 -``` - -#### 利用sum()求分区间的累积前缀 -按天数累积 -```sql -SELECT gender, day, SUM(score_points) OVER(PARTITION BY gender ORDER BY day) AS total -FROM Scores -``` - -#### 各种rank函数 -rank():正常排名,允许并列。两个第一名的话,则没有第二名。 -dense_rank():正常排名,允许并列。两个第一名的话,依然有第二名。 -row_number(); 排名不允许有并列。 - - -#### 优先操作累积函数,再操作窗口函数 -在下面的代码里,优先考虑group by Orders.product_id, customer_id,group之后每一行就可以定义count(Orders.product_id),再按照该列对所有行进行rank -```sql -select Orders.product_id, product_name, customer_id, - rank() over (partition by customer_id order by count(Orders.product_id) desc) as rnk -from Orders -left join Products on Orders.product_id = Products.product_id -group by Orders.product_id, customer_id -``` - -#### 窗口函数内排序后用lead求某列的下一行 -对于每个user_id,按时间先后排序visit_data。用`lead(visit_date, 1, '2021-01-01')`可以求出此时表里visit_date的下一行,其中第三个参数表示没有下一行时的默认值。 -```sql -select lead(visit_date, 1, '2021-01-01') over (partition by user_id order by visit_date) as next -from UserVisits -``` - ### Join #### out join From 79488909bfcd0fcd36dbcc6bf01bccdd4f3c37a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 15:28:29 -0800 Subject: [PATCH 1624/2729] Update README.md --- SQL/Window_Function/README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/SQL/Window_Function/README.md b/SQL/Window_Function/README.md index 6e7f94c65..8d9e93b0e 100644 --- a/SQL/Window_Function/README.md +++ b/SQL/Window_Function/README.md @@ -1,6 +1,6 @@ ### 窗口函数 -#### 利用rank()求分区间的最大值 +#### 利用rank()求分区里的最大值 在原表里插入rank存为新表。再在新表里选择rank=1的行。 ```sql with temp as @@ -13,6 +13,11 @@ from temp where rnk = 1 ``` +#### 利用count()求分区里的行数 +```sql +select *, count(activity) over (partition by username) as cnt +``` + #### 利用sum()求分区间的累积前缀 按天数累积 ```sql From fcbfe16870c6f6094cdce607692e98c1b3bf0a40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 23:00:24 -0800 Subject: [PATCH 1625/2729] Create 2563.Count-the-Number-of-Fair-Pairs.cpp --- .../2563.Count-the-Number-of-Fair-Pairs.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Binary_Search/2563.Count-the-Number-of-Fair-Pairs/2563.Count-the-Number-of-Fair-Pairs.cpp diff --git a/Binary_Search/2563.Count-the-Number-of-Fair-Pairs/2563.Count-the-Number-of-Fair-Pairs.cpp b/Binary_Search/2563.Count-the-Number-of-Fair-Pairs/2563.Count-the-Number-of-Fair-Pairs.cpp new file mode 100644 index 000000000..7abfb660a --- /dev/null +++ b/Binary_Search/2563.Count-the-Number-of-Fair-Pairs/2563.Count-the-Number-of-Fair-Pairs.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + long long countFairPairs(vector& nums, int lower, int upper) + { + sort(nums.begin(), nums.end()); + + long long ret = 0; + for (int x: nums) + { + int k = upper_bound(nums.begin(), nums.end(), upper-x) - nums.begin(); + int t = lower_bound(nums.begin(), nums.end(), lower-x) - nums.begin(); + int count = k-t; + + if (x+x<=upper && x+x>=lower) + count--; + + ret += count; + } + + return ret/2; + + } +}; From 5ff1572267bc40f8abdaa909daf0ff63f1bd8a22 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 23:00:54 -0800 Subject: [PATCH 1626/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 476135c09..f366b3cb2 100644 --- a/Readme.md +++ b/Readme.md @@ -87,6 +87,7 @@ [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) +[2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) * ``Binary Processing`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) From 9e6af361082d40ab8e63135b0d6fe2ed3b8b382f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 23:14:08 -0800 Subject: [PATCH 1627/2729] Create Readme.md --- .../2563.Count-the-Number-of-Fair-Pairs/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/2563.Count-the-Number-of-Fair-Pairs/Readme.md diff --git a/Binary_Search/2563.Count-the-Number-of-Fair-Pairs/Readme.md b/Binary_Search/2563.Count-the-Number-of-Fair-Pairs/Readme.md new file mode 100644 index 000000000..c6c676cf2 --- /dev/null +++ b/Binary_Search/2563.Count-the-Number-of-Fair-Pairs/Readme.md @@ -0,0 +1,7 @@ +### 2563.Count-the-Number-of-Fair-Pairs + +初看这道题的时候,一个比较自然的想法是,遍历每个j,查看j之前的有多少个符合条件的元素满足`lower-nums[j] <= nums[i] <= upper-nums[j]`。这就要求j之前的元素必须是有序的。但是每考察完一个j,就需要将nums[0:j]重新排序,这样的复杂度太高。 + +这时候我们再换一个角度。这里i与j其实是对称的。我们没有必要纠结于`ij`,只要除以二就可以。所以我们只需要将nums排一次序。对于其中任意的元素x,用二分法求出有多少个符合条件的元素满足在`[lower-x, pper-x]`的区间范围内即可。 + +但是这里有个关键点,就是上述方法中,x本身可能就恰好在`[lower-x, pper-x]`的范围内。这样我们会误加上(x,x)这样的组合。所以我们要验证一下,如果(x,x)满足条件,就额外从计数器里减一。最终总的计数除以二,就是合法的`i Date: Sat, 11 Feb 2023 23:51:49 -0800 Subject: [PATCH 1628/2729] Create 2564.Substring-XOR-Queries.cpp --- .../2564.Substring-XOR-Queries.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Binary_Search/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp diff --git a/Binary_Search/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp b/Binary_Search/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp new file mode 100644 index 000000000..0d2fcea3c --- /dev/null +++ b/Binary_Search/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { +public: + vector> substringXorQueries(string s, vector>& queries) + { + unordered_map>Map; + for (int i=0; i>rets(m); + for (int i=0; i=len) + sum -= (1LL< Date: Sat, 11 Feb 2023 23:52:37 -0800 Subject: [PATCH 1629/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f366b3cb2..aca13f968 100644 --- a/Readme.md +++ b/Readme.md @@ -88,6 +88,7 @@ [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) +[2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2564.Substring-XOR-Queries) (H-) * ``Binary Processing`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) From 8d61d4cd8e0605ba0e4ea1d3bde7811cb52b3ec1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 11 Feb 2023 23:52:58 -0800 Subject: [PATCH 1630/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index aca13f968..42cc794da 100644 --- a/Readme.md +++ b/Readme.md @@ -88,7 +88,6 @@ [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) -[2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2564.Substring-XOR-Queries) (H-) * ``Binary Processing`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) @@ -123,6 +122,7 @@ [2513.Minimize-the-Maximum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays) (H) [2528.Maximize-the-Minimum-Powered-City](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2528.Maximize-the-Minimum-Powered-City) (H-) [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) +[2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2564.Substring-XOR-Queries) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From a0faa5fe0a9918bcb59ec64fdc40f27d71a7d7c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 00:23:57 -0800 Subject: [PATCH 1631/2729] Create 2564.Substring-XOR-Queries.cpp --- .../2564.Substring-XOR-Queries.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp diff --git a/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp b/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp new file mode 100644 index 000000000..4c352d6a2 --- /dev/null +++ b/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { +public: + vector> substringXorQueries(string s, vector>& queries) + { + unordered_map>Map; + for (int i=0; i>rets(m); + for (int i=0; i=len) + sum -= (1LL< Date: Sun, 12 Feb 2023 00:24:20 -0800 Subject: [PATCH 1632/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 42cc794da..f3298c4b0 100644 --- a/Readme.md +++ b/Readme.md @@ -48,6 +48,7 @@ [2401.Longest-Nice-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2401.Longest-Nice-Subarray) (H-) [2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) [2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (M+) +[2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2564.Substring-XOR-Queries) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 3215f7bf28e93e2221eb86f6f89353cd56df447e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 00:25:12 -0800 Subject: [PATCH 1633/2729] Delete 2564.Substring-XOR-Queries.cpp --- .../2564.Substring-XOR-Queries.cpp | 40 ------------------- 1 file changed, 40 deletions(-) delete mode 100644 Binary_Search/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp diff --git a/Binary_Search/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp b/Binary_Search/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp deleted file mode 100644 index 0d2fcea3c..000000000 --- a/Binary_Search/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp +++ /dev/null @@ -1,40 +0,0 @@ -using LL = long long; -class Solution { -public: - vector> substringXorQueries(string s, vector>& queries) - { - unordered_map>Map; - for (int i=0; i>rets(m); - for (int i=0; i=len) - sum -= (1LL< Date: Sun, 12 Feb 2023 00:25:28 -0800 Subject: [PATCH 1634/2729] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index f3298c4b0..176c15e07 100644 --- a/Readme.md +++ b/Readme.md @@ -123,7 +123,6 @@ [2513.Minimize-the-Maximum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays) (H) [2528.Maximize-the-Minimum-Powered-City](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2528.Maximize-the-Minimum-Powered-City) (H-) [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) -[2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2564.Substring-XOR-Queries) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From d07a8c09898bfaa460178eac9a7998b8cb695bfa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 00:29:30 -0800 Subject: [PATCH 1635/2729] Create Readme.md --- Two_Pointers/2564.Substring-XOR-Queries/Readme.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 Two_Pointers/2564.Substring-XOR-Queries/Readme.md diff --git a/Two_Pointers/2564.Substring-XOR-Queries/Readme.md b/Two_Pointers/2564.Substring-XOR-Queries/Readme.md new file mode 100644 index 000000000..0c58ddd46 --- /dev/null +++ b/Two_Pointers/2564.Substring-XOR-Queries/Readme.md @@ -0,0 +1,4 @@ +### 2564.Substring-XOR-Queries + +首先我们知道`x^a=b`可以推出`x=a^b`。于是本题本质就是给出了一系列的val,问在二进制串里最早出现val的子串。暴力枚举子串的时间复杂度是o(N^2),本题能够优化的地方在于,val的长度是有上限的,最多31位(因为整型不超过2^32)。所以我们只要遍历长度分别为1,2,...,31的子串,跑31次双指针即可:查看固定长度的滑窗里的数值是否出现在query里即可。时间复杂度就是o(31N). + From 964f962ab62c819d3a6993dfe9288e50896aad94 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 00:41:48 -0800 Subject: [PATCH 1636/2729] Update 2564.Substring-XOR-Queries.cpp --- .../2564.Substring-XOR-Queries.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp b/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp index 4c352d6a2..c7510ecdb 100644 --- a/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp +++ b/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp @@ -1,22 +1,19 @@ -using LL = long long; class Solution { public: vector> substringXorQueries(string s, vector>& queries) { - unordered_map>Map; + unordered_map>Map; for (int i=0; i>rets(m); - for (int i=0; i>rets(queries.size()); + for (int i=0; i Date: Sun, 12 Feb 2023 01:02:36 -0800 Subject: [PATCH 1637/2729] Update 2564.Substring-XOR-Queries.cpp --- .../2564.Substring-XOR-Queries.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp b/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp index c7510ecdb..366d3d737 100644 --- a/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp +++ b/Two_Pointers/2564.Substring-XOR-Queries/2564.Substring-XOR-Queries.cpp @@ -1,3 +1,4 @@ +using LL = long long; class Solution { public: vector> substringXorQueries(string s, vector>& queries) @@ -6,14 +7,16 @@ class Solution { for (int i=0; i>rets(queries.size()); - for (int i=0; i>rets(m); + for (int i=0; i Date: Sun, 12 Feb 2023 01:03:54 -0800 Subject: [PATCH 1638/2729] Create 2565.Subsequence-With-the-Minimum-Score.cpp --- ...565.Subsequence-With-the-Minimum-Score.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Greedy/2565.Subsequence-With-the-Minimum-Score/2565.Subsequence-With-the-Minimum-Score.cpp diff --git a/Greedy/2565.Subsequence-With-the-Minimum-Score/2565.Subsequence-With-the-Minimum-Score.cpp b/Greedy/2565.Subsequence-With-the-Minimum-Score/2565.Subsequence-With-the-Minimum-Score.cpp new file mode 100644 index 000000000..e036d6d31 --- /dev/null +++ b/Greedy/2565.Subsequence-With-the-Minimum-Score/2565.Subsequence-With-the-Minimum-Score.cpp @@ -0,0 +1,66 @@ +class Solution { +public: + int minimumScore(string s, string t) + { + int m = s.size(); + int n = t.size(); + + vectorleft(n, m); + int j = 0; + for (int i=0; iright(n, -1); + j = m-1; + for (int i=n-1; i>=0; i--) + { + while (j>=0 && s[j]!=t[i]) + j--; + if (j>=0) + { + right[i] = j; + j--; + } + } + + int low = 0, high = n; + while (low < high) + { + int mid = low+(high-low)/2; + if (isOK(mid, s, t, left, right)) + high = mid; + else + low = mid+1; + } + + return low; + } + + bool isOK(int len, string& s, string& t, vector&left, vector&right) + { + int m = s.size(); + int n = t.size(); + + if (len==n) return true; + if (len==0) return (left[n-1] < m) && (right[0]>=0); + + if (right[len]>=0) return true; + if (left[n-len-1] < m) return true; + + for (int i=1; i+len Date: Sun, 12 Feb 2023 01:04:20 -0800 Subject: [PATCH 1639/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 176c15e07..31e20d2e0 100644 --- a/Readme.md +++ b/Readme.md @@ -1230,6 +1230,7 @@ [2163.Minimum-Difference-in-Sums-After-Removal-of-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2163.Minimum-Difference-in-Sums-After-Removal-of-Elements) (M+) [2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods) (H-) [2555.Maximize-Win-From-Two-Segments](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2555.Maximize-Win-From-Two-Segments) (M+) +[2565.Subsequence-With-the-Minimum-Score](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2565.Subsequence-With-the-Minimum-Score) (H-) * ``State Machine`` [524.Longest-Word-in-Dictionary-through-Deleting](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/524.Longest-Word-in-Dictionary-through-Deleting) (M+) [727.Minimum-Window-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/727.Minimum-Window-Subsequence) (H-) From f1030fd5e8d439aa48834b08cb340c64a363938e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 11:35:35 -0800 Subject: [PATCH 1640/2729] Create Readme.md --- .../2565.Subsequence-With-the-Minimum-Score/Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Greedy/2565.Subsequence-With-the-Minimum-Score/Readme.md diff --git a/Greedy/2565.Subsequence-With-the-Minimum-Score/Readme.md b/Greedy/2565.Subsequence-With-the-Minimum-Score/Readme.md new file mode 100644 index 000000000..df7e47293 --- /dev/null +++ b/Greedy/2565.Subsequence-With-the-Minimum-Score/Readme.md @@ -0,0 +1,10 @@ +### 2565.Subsequence-With-the-Minimum-Score + +本题的题意有点文字游戏。本质上,left到right之间的字符不删白不删,删的越多t就越容易成为s的subsequence。所以本题就是在t字符串里找一段可删除的最短substring,使得t成为s的subsequence。 + +于是,t其实就分成了三部分:`xxx yyy zzz`,第二部分是需要删除的,第一部分和第三部分拼接起来是s的一个subsequence。这等价于xxx必须是s的一个前缀的subsequence,而zzz必须是s的一个后缀的subsequence,且s的前缀和后缀不能重合。我们发现这部分信息其实是可以提前处理的,我们可以从前往后扫一遍,计算left[i]表示s的最短前缀长度是多少,使得其能包含t[0:i],即t[0:i]是该前缀的subsequence。同理,从后往前扫一遍,可以计算right[i]表示s的最短后缀长度是多少,使得其能包含t[i:n-1],即t[0:n-1]是该后缀的subsequence。 + +根据套路,考虑到t分成了三部分,我们不妨遍历中间的部分,然后利用第一部分和第三部分的已知信息。假设中间yyy的部分是[i:j],那么我们如果left[i-1] < right[j+1]的话,我们就可以知道`t[0:i-1]+t[j+1:n-1]`拼接起来就是s的subsequence了。 + +那么如何遍历中间部分呢?如果知道了`yyy`的长度,那么搞一个固定长度滑窗在t上走一遍即可。那么`yyy`的长度有哪些可能呢?其实只要二分搜索一下即可。因为有单调性的存在:`yyy`越长,必然就容易实现删除后的t是s的子序列;极端情况就是`yyy`部分占据了整个t,那么答案就是n,不过这不一定是最优解。所以我们试探减小`yyy`的长度,就可以逐步逼近最优解。 + From 22db704143a66dd34484671f46c934bcaa6a814a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 11:48:46 -0800 Subject: [PATCH 1641/2729] Update 2565.Subsequence-With-the-Minimum-Score.cpp --- .../2565.Subsequence-With-the-Minimum-Score.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Greedy/2565.Subsequence-With-the-Minimum-Score/2565.Subsequence-With-the-Minimum-Score.cpp b/Greedy/2565.Subsequence-With-the-Minimum-Score/2565.Subsequence-With-the-Minimum-Score.cpp index e036d6d31..399fc8405 100644 --- a/Greedy/2565.Subsequence-With-the-Minimum-Score/2565.Subsequence-With-the-Minimum-Score.cpp +++ b/Greedy/2565.Subsequence-With-the-Minimum-Score/2565.Subsequence-With-the-Minimum-Score.cpp @@ -49,9 +49,6 @@ class Solution { int m = s.size(); int n = t.size(); - if (len==n) return true; - if (len==0) return (left[n-1] < m) && (right[0]>=0); - if (right[len]>=0) return true; if (left[n-len-1] < m) return true; From 618c68f33f1c24b938c21984bb281cd0e09e3373 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 12:45:42 -0800 Subject: [PATCH 1642/2729] Update README.md --- SQL/Window_Function/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/SQL/Window_Function/README.md b/SQL/Window_Function/README.md index 8d9e93b0e..5657b11a6 100644 --- a/SQL/Window_Function/README.md +++ b/SQL/Window_Function/README.md @@ -18,6 +18,17 @@ where rnk = 1 select *, count(activity) over (partition by username) as cnt ``` +#### first_value() / last_value() 取最小值/最大值 +```sql +select first_value(device_id) over (partition by player_id order by event_date) as device_id +``` + +#### 配合distinct实现group by的效果 +```sql +select distinct player_id, first_value(device_id) over (partition by player_id order by event_date) as device_id +``` +这样本质上等同于`group by player_id` + #### 利用sum()求分区间的累积前缀 按天数累积 ```sql From 77d2b9c283366f962e234302c83cca3d8aa69875 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 14:12:37 -0800 Subject: [PATCH 1643/2729] Update README.md --- SQL/Window_Function/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/SQL/Window_Function/README.md b/SQL/Window_Function/README.md index 5657b11a6..d2accc989 100644 --- a/SQL/Window_Function/README.md +++ b/SQL/Window_Function/README.md @@ -35,6 +35,7 @@ select distinct player_id, first_value(device_id) over (partition by player_id o SELECT gender, day, SUM(score_points) OVER(PARTITION BY gender ORDER BY day) AS total FROM Scores ``` +LC 534, #### 各种rank函数 rank():正常排名,允许并列。两个第一名的话,则没有第二名。 From 0a73f4c1f52e9f0dcdb84d2668e90a2b496d5ad0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 12 Feb 2023 14:21:00 -0800 Subject: [PATCH 1644/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 31e20d2e0..a2ae119e9 100644 --- a/Readme.md +++ b/Readme.md @@ -122,6 +122,7 @@ [2517.Maximum-Tastiness-of-Candy-Basket](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2517.Maximum-Tastiness-of-Candy-Basket) (M+) [2513.Minimize-the-Maximum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2513.Minimize-the-Maximum-of-Two-Arrays) (H) [2528.Maximize-the-Minimum-Powered-City](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2528.Maximize-the-Minimum-Powered-City) (H-) +[2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II) (H-) [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) From 79c3d6773eac36f414511388279bda83a70ef350 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 10:42:53 -0800 Subject: [PATCH 1645/2729] Create 2567.Minimum-Score-by-Changing-Two-Elements.cpp --- .../2567.Minimum-Score-by-Changing-Two-Elements.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2567.Minimum-Score-by-Changing-Two-Elements/2567.Minimum-Score-by-Changing-Two-Elements.cpp diff --git a/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/2567.Minimum-Score-by-Changing-Two-Elements.cpp b/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/2567.Minimum-Score-by-Changing-Two-Elements.cpp new file mode 100644 index 000000000..80540a7c8 --- /dev/null +++ b/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/2567.Minimum-Score-by-Changing-Two-Elements.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int minimizeSum(vector& nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + return min({nums[n-2]-nums[1], nums[n-1]-nums[2], nums[n-3]-nums[0]}); + } +}; From 89ea8a58d0ca10c8767aeb9368f0f207acf69683 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 10:47:04 -0800 Subject: [PATCH 1646/2729] Create Readme.md --- .../2567.Minimum-Score-by-Changing-Two-Elements/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2567.Minimum-Score-by-Changing-Two-Elements/Readme.md diff --git a/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/Readme.md b/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/Readme.md new file mode 100644 index 000000000..f09858e8f --- /dev/null +++ b/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/Readme.md @@ -0,0 +1,7 @@ +### 2567.Minimum-Score-by-Changing-Two-Elements + +设想,如果贪心地将两个修改的名额都用来降低 high score,我们可以有三种方法:(1) 将最大值改为次大值,最小值改为次小值,这样high score就是`nums[n-2]-nums[1]`. (2) 将最小的两个值都改为第三小的值,这样high score就是`nums[n-1]-nums[2]`. (2) 将最大的两个值都改为第三大的值,这样high score就是`nums[n-3]-nums[0]`. + +此时我们发现,我们选取上述的哪个方案,因为出现了重复元素,所以low score都是零。 + +所以答案就是在三个high score里面挑最小值即可。 From f8616ee3d85a15a8b7fdb11bbc5f855a6a541e28 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 10:56:34 -0800 Subject: [PATCH 1647/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a2ae119e9..b515df320 100644 --- a/Readme.md +++ b/Readme.md @@ -1298,6 +1298,7 @@ [2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) [2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) +[2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From fa3004e72626363d018e081e8be0e1205d47d622 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 10:59:21 -0800 Subject: [PATCH 1648/2729] Create 2568.Minimum-Impossible-OR_v2.cpp --- .../2568.Minimum-Impossible-OR_v2.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v2.cpp diff --git a/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v2.cpp b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v2.cpp new file mode 100644 index 000000000..e7c6c54c3 --- /dev/null +++ b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int minImpossibleOR(vector& nums) + { + unordered_setSet(nums.begin(), nums.end()); + for (int i=0; i<31; i++) + { + if (Set.find(1< Date: Sun, 19 Feb 2023 11:01:21 -0800 Subject: [PATCH 1649/2729] Create 2568.Minimum-Impossible-OR_v1.cpp --- .../2568.Minimum-Impossible-OR_v1.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp diff --git a/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp new file mode 100644 index 000000000..aeafd9b78 --- /dev/null +++ b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minImpossibleOR(vector& nums) + { + sort(nums.begin(), nums.end()); + int mx = 0; + for (int i = 0; i < nums.size(); i++) + { + if (nums[i] > mx+1) + return mx+1; + else + mx = (mx | nums[i]); + } + + return -1; + } +}; From dcf77314c5816ed2177e4c1f4700ef4cf9d28dbf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 11:11:33 -0800 Subject: [PATCH 1650/2729] Create Readme.md --- Greedy/2568.Minimum-Impossible-OR/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/2568.Minimum-Impossible-OR/Readme.md diff --git a/Greedy/2568.Minimum-Impossible-OR/Readme.md b/Greedy/2568.Minimum-Impossible-OR/Readme.md new file mode 100644 index 000000000..4ce6fbe40 --- /dev/null +++ b/Greedy/2568.Minimum-Impossible-OR/Readme.md @@ -0,0 +1,11 @@ +### 2568.Minimum-Impossible-OR + +#### 解法1 +有一道类似的经典题。给一个数组,求最小的自然数,使得它不是数组的任何subset的元素和。 + +我们将数组从小到大排列。假设前i-1个元素里,我们能构造连续的自然数[1,mx],那么如果`nums[i]<=mx+1`,那么意味着前i个元素里,我们可以任意构造[1,mx+num[i]]里的元素。反之,如果`nums[i]>mx+1`,那么我们如论如何都无法构造出mx+1来。 + +同理,本题里的或运算和加法运算有着相同的性质:越搞数越大。假设前i-1个元素里,我们能构造连续的自然数[1,mx],那么如果`nums[i]<=mx+1`,那么意味着前i个元素里,我们可以任意构造[1,mx|num[i]]里的元素。反之,如果`nums[i]>mx+1`,那么将nums[i]与任何[1,mx]里面的元素进行操作,得到的都会比nums[i]还大,我们如论也无法构造出mx+1来。 + +#### 解法2 +假设我们能够构造出2^0,2^1,..,2^k,那么意味着[1,2^(k+1)-1]里面的任何元素都能构造出来。但是我们肯定无法构造出2^(k+1),所以我们只需要查看2^(k+1)是否在数组里即可。如果在的话,那么递归处理,我们只需要查看`2^(k+2)`是否在数组里即可。即本题求的就是最小的、不在数组里的2的幂。 From a96ed06f441400060a530e3f20cabfc92f9f76e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:11:48 -0800 Subject: [PATCH 1651/2729] Update range_sum_increase_by.cpp --- .../SegmentTree/range_sum_increase_by.cpp | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_sum_increase_by.cpp b/Template/SegmentTree/range_sum_increase_by.cpp index 578a1f61f..4baf84fdc 100644 --- a/Template/SegmentTree/range_sum_increase_by.cpp +++ b/Template/SegmentTree/range_sum_increase_by.cpp @@ -26,7 +26,26 @@ class SegTreeNode right = new SegTreeNode(mid+1, b, val); info = left->info + right->info; // check with your own logic } - } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } void pushDown() { @@ -83,3 +102,20 @@ class SegTreeNode return info; // should not reach here } }; + +int main() +{ + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. + + for (auto& update: updates) + { + int start = update[0], end = update[1], val = update[2]; + root->updateRange(start, end ,val); // increase the range [start, end] by val + } + + for (auto& query: queries) + { + int start = query[0], end = query[1]; + ret[i] = root->queryRange(start, end); // get the range sum over [start, end] + } +} From 4c80e3fdaf3877de8ecd508d0c488583084ac9da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:12:32 -0800 Subject: [PATCH 1652/2729] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 67c9b9ef7..653f7717e 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -25,6 +25,25 @@ class SegTreeNode } } + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + void pushDown() { if (tag==1 && left) @@ -83,7 +102,7 @@ class SegTreeNode int main() { - SegTreeNode* root = new SegTreeNode(0, length-1, 0); + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. for (auto& update: updates) { From cb22d795ad2f33f81a351fee15f8b56f4a6fd0ad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:12:43 -0800 Subject: [PATCH 1653/2729] Update range_sum.cpp --- Template/SegmentTree/range_sum.cpp | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_sum.cpp b/Template/SegmentTree/range_sum.cpp index c52051e69..4ebcb2d98 100644 --- a/Template/SegmentTree/range_sum.cpp +++ b/Template/SegmentTree/range_sum.cpp @@ -28,6 +28,25 @@ class SegTreeNode } } + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + void pushDown() { if (lazy_tag==1 && left) @@ -86,7 +105,7 @@ class SegTreeNode int main() { - SegTreeNode* root = new SegTreeNode(0, length-1, 0); + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. for (auto& update: updates) { From 6d0886a96d02b86837cb4f44fd088ba9cccbf803 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:16:42 -0800 Subject: [PATCH 1654/2729] Create 2569.Handling-Sum-Queries-After-Update.cpp --- ...2569.Handling-Sum-Queries-After-Update.cpp | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 Segment_Tree/2569.Handling-Sum-Queries-After-Update/2569.Handling-Sum-Queries-After-Update.cpp diff --git a/Segment_Tree/2569.Handling-Sum-Queries-After-Update/2569.Handling-Sum-Queries-After-Update.cpp b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/2569.Handling-Sum-Queries-After-Update.cpp new file mode 100644 index 000000000..c0823686b --- /dev/null +++ b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/2569.Handling-Sum-Queries-After-Update.cpp @@ -0,0 +1,130 @@ +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + bool lazy_tag; // if the child ranges are pending propagation + LL lazy_val; // how many flips needed to be propagated to child ranges. + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (lazy_tag==1 && left) + { + if (lazy_val % 2 == 1) + { + left->info = (left->end - left->start + 1) - left->info; + right->info = (right->end - right->start + 1) - right->info; + left->lazy_tag = 1; left->lazy_val += lazy_val; + right->lazy_tag = 1; right->lazy_val += lazy_val; + } + + lazy_tag = 0; lazy_val = 0; + } + } + + void updateRange(int a, int b) // set range [a,b] with flips + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = (end-start+1) - info; + lazy_tag = 1; + lazy_val += 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b); + right->updateRange(a, b); + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum over range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +class Solution { +public: + vector handleQuery(vector& nums1, vector& nums2, vector>& queries) + { + int n = nums1.size(); + SegTreeNode* root = new SegTreeNode(0, n-1, nums1); + LL sum = accumulate(nums2.begin(), nums2.end(), 0LL); + vectorrets; + for (auto & query: queries) + { + if (query[0]==1) + root->updateRange(query[1], query[2]); + else if (query[0]==2) + sum += root->queryRange(0, n-1) * query[1]; + else + rets.push_back(sum); + } + + return rets; + } +}; From 74580bf4695441772ae27fa8759a8055b01675fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:17:09 -0800 Subject: [PATCH 1655/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b515df320..883e11149 100644 --- a/Readme.md +++ b/Readme.md @@ -307,6 +307,7 @@ [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2286.Booking-Concert-Tickets-in-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups) (H-) [2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) +[2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From f71d2641c06216dae88fb918a927dbbc50887d73 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:29:17 -0800 Subject: [PATCH 1656/2729] Create Readme.md --- .../2569.Handling-Sum-Queries-After-Update/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md diff --git a/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md new file mode 100644 index 000000000..594c3e737 --- /dev/null +++ b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md @@ -0,0 +1,9 @@ +### 2569.Handling-Sum-Queries-After-Update + +本题的本质就是需要高效的区间更新函数来维护nums1,来实现第一类query。对于第二类query,只需要操作`sum += total(nums1)*p`即可,其中total就是对nums1全部元素取和。对于第三类query,就是输出当前的sum。 + +显然我们会用线段树来实现这样的数据结构。 + +在现有的模板中,我们肯定会选择带有“区间求和”功能的模板,即`queryRange(a,b)`可以求得nums1里指定区间元素的和。但是“区间更新”的功能需要重写。这里的区间更新是将元素做0/1翻转,这对区间和会产生什么影响呢?假设原本一段区间[a,b]内记录的元素和是info,那么`updateRange(a,b)`造成的影响其实就是`info = (b-a+1)-info`,改动非常简单。 + +另外,我们还需要对懒标记进行重新的定义。在模板里,`lazy_tag=1`表示该区间的子区间有待更新(即01翻转)。那么`lazy_val`我们需要重新定义为“它的子区间我们还需要翻转多少次”。当我们需要`push_down`的时候,就需要对左右子区间分别进行`lazy_val`次的翻转。 From bb1d2bb6661b4cbfa17b674de5c17f52f1056c66 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:30:23 -0800 Subject: [PATCH 1657/2729] Update Readme.md --- Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md index 594c3e737..9d5c69bb6 100644 --- a/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md +++ b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md @@ -4,6 +4,6 @@ 显然我们会用线段树来实现这样的数据结构。 -在现有的模板中,我们肯定会选择带有“区间求和”功能的模板,即`queryRange(a,b)`可以求得nums1里指定区间元素的和。但是“区间更新”的功能需要重写。这里的区间更新是将元素做0/1翻转,这对区间和会产生什么影响呢?假设原本一段区间[a,b]内记录的元素和是info,那么`updateRange(a,b)`造成的影响其实就是`info = (b-a+1)-info`,改动非常简单。 +在现有的模板中,我们肯定会选择带有“区间求和”功能的模板,即`queryRange(a,b)`可以求得nums1里指定区间[a,b]元素的和。但是“区间更新”的功能需要重写:原本的功能是将区间的数值替换为val,这里的区间更新是将里面的元素全部做0/1翻转,这对区间和会产生什么影响呢?假设原本一段区间[a,b]内记录的元素和是info,那么`updateRange(a,b)`造成的影响其实就是`info = (b-a+1)-info`,改动非常简单。 另外,我们还需要对懒标记进行重新的定义。在模板里,`lazy_tag=1`表示该区间的子区间有待更新(即01翻转)。那么`lazy_val`我们需要重新定义为“它的子区间我们还需要翻转多少次”。当我们需要`push_down`的时候,就需要对左右子区间分别进行`lazy_val`次的翻转。 From 77e19f22c640e1a69db5918d148391dab27f12fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 17:29:08 -0800 Subject: [PATCH 1658/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 883e11149..9da0a464f 100644 --- a/Readme.md +++ b/Readme.md @@ -1300,6 +1300,7 @@ [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) [2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) [2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) +[2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 5acc9e045635f297eed83a9377a54c382b97bd6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 17:58:40 -0800 Subject: [PATCH 1659/2729] Update 2568.Minimum-Impossible-OR_v1.cpp --- .../2568.Minimum-Impossible-OR_v1.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp index aeafd9b78..6776497aa 100644 --- a/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp +++ b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp @@ -3,15 +3,15 @@ class Solution { int minImpossibleOR(vector& nums) { sort(nums.begin(), nums.end()); - int mx = 0; - for (int i = 0; i < nums.size(); i++) + int mx = 0; + for (int i=0; i mx+1) return mx+1; else mx = (mx | nums[i]); } - - return -1; + + return mx+1; } }; From 0f89cbb78e0ee7c8df7c6ddf897c38edc04c9ee3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 19:44:24 -0800 Subject: [PATCH 1660/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 9da0a464f..d9438c3b0 100644 --- a/Readme.md +++ b/Readme.md @@ -1172,7 +1172,6 @@ [1727.Largest-Submatrix-With-Rearrangements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1727.Largest-Submatrix-With-Rearrangements) (M) [1744.Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1744.Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day) (M) [1788.Maximize-the-Beauty-of-the-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1788.Maximize-the-Beauty-of-the-Garden) (M+) -[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [1818.Minimum-Absolute-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1818.Minimum-Absolute-Sum-Difference) (M+) [1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number) (M+) [1911.Maximum-Alternating-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1911.Maximum-Alternating-Subsequence-Sum) (M+) @@ -1299,7 +1298,8 @@ [2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) [2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) -[2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) +[2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) +[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) From 484c0ff28c3f16c34a5ba0ad2e2671b10bdbea81 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 22:54:03 -0800 Subject: [PATCH 1661/2729] Create 2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp --- ...m-Operations-to-Reduce-an-Integer-to-0.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp diff --git a/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp b/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp new file mode 100644 index 000000000..c57e673de --- /dev/null +++ b/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minOperations(int n) + { + int ret =0 ; + for (int i=0; i<31; i++) + { + if (count(n+(1< Date: Sun, 19 Feb 2023 22:54:33 -0800 Subject: [PATCH 1662/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d9438c3b0..147a84bc6 100644 --- a/Readme.md +++ b/Readme.md @@ -1301,6 +1301,7 @@ [2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) +[2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 0db20c1d37226669be8aca3cb22ddbff34afc3fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 23:05:00 -0800 Subject: [PATCH 1663/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/Readme.md diff --git a/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/Readme.md b/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/Readme.md new file mode 100644 index 000000000..aae823807 --- /dev/null +++ b/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/Readme.md @@ -0,0 +1,5 @@ +### 2571.Minimum-Operations-to-Reduce-an-Integer-to-0 + +最简单的操作就是将n的每个bit上的1依次删去。我们容易发现有一种其他的策略,就是先加上某个2的幂,这样可以消灭更多的1. 比如当`n=1001110`的时候,如果我们先加上一个`10`,就可以将n变成`1010000`,此时只要减去一个`10000`,即可用两次操作消去原先的三个1. + +总结起来的规律就是,我们从小到大遍历i,依次尝试在n上加`1< Date: Mon, 20 Feb 2023 00:06:53 -0800 Subject: [PATCH 1664/2729] Create 2572.Count-the-Number-of-Square-Free-Subsets.cpp --- ...ount-the-Number-of-Square-Free-Subsets.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp new file mode 100644 index 000000000..b2350ec0b --- /dev/null +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp @@ -0,0 +1,52 @@ +using LL = long long; +class Solution { + LL dp[1005][1025]; + vectorprimes = {2,3,5,7,11,13,17,19,23,29}; + LL M = 1e9+7; +public: + int squareFreeSubsets(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + LL ret = 0; + dp[0][0] = 1; + for (int i=1; i<=n; i++) + for (int state = 0; state < (1<<10); state++) + { + if (nums[i]==1) + { + dp[i][state] = dp[i-1][state] * 2 % M; + } + else + { + dp[i][state] = dp[i-1][state]; + int s = helper(nums[i]); + if (s!=-1 && (state&s)==s) + dp[i][state] = (dp[i][state] + dp[i-1][state-s]) % M; + } + if (i==n) + ret = (ret + dp[i][state]) % M; + } + return ret-1; + } + + int helper(int x) + { + int s = 0; + for (int i=0; i 1) + return -1; + else if (count==1) + s += (1< Date: Mon, 20 Feb 2023 00:08:36 -0800 Subject: [PATCH 1665/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 147a84bc6..305099b80 100644 --- a/Readme.md +++ b/Readme.md @@ -821,6 +821,7 @@ [1994.The-Number-of-Good-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1994.The-Number-of-Good-Subsets) (H) [2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall) (H-) [2403.Minimum-Time-to-Kill-All-Monsters](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters) (M+) +[2572.Count-the-Number-of-Square-Free-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets) (H-) * ``枚举集合的子集`` [1494.Parallel-Courses-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1494.Parallel-Courses-II) (H) [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) From 55e06add79875fcc0e3065dacf9ae7d680b24e1f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 00:34:12 -0800 Subject: [PATCH 1666/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md new file mode 100644 index 000000000..12a4dda48 --- /dev/null +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md @@ -0,0 +1,9 @@ +### 2572.Count-the-Number-of-Square-Free-Subsets + +数组的元素有n个,每个元素都有选或不选两种策略,故subset的种类就是`2^n`。本题的要求是寻找某些subset,使得他们的乘积里每个质因数最多只能出现一次。根据数值的范围(小于30),我们发现质因数的种类只有10种,即`2,3,5,7,11,13,17,19,23,29`. 所以我们可以用一个10 bit的二进制数state来表示哪些质因数已经被选了,那么对于任意nums[i]是否能选,其实就是取决于state。 + +所以我们可以知道本题是一个动态规划,状态变量是dp[i][state]。我们试图从dp[i-1]来推出dp[i]。 + +如果我们不想选nums[i],那么有`dp[i][state] += dp[i-1][state]`。如果我们想选nums[i],那么有个前提条件,即state里必须包含nums[i]的所有质因数(且每个质因数必须只出现一次)。我们也可以用一个二进制数s来表示nums[i]所包含的质因数状态,那么有`dp[i][state] += dp[i-1][state-s]`. 特别注意,如果`nums[i]=1`,那么是否选取都没有影响,故`dp[i][state]=dp[i-1][state]*2`. + +最终`sum(dp[n][state])`就是满足所有质因数最多只出现一次的subset的数目。注意要减一排除空集。 From 929eca42c97c4b44f27b4061a370a42640f0870b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 00:34:45 -0800 Subject: [PATCH 1667/2729] Update Readme.md --- .../2572.Count-the-Number-of-Square-Free-Subsets/Readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md index 12a4dda48..24a4f434f 100644 --- a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md @@ -1,8 +1,6 @@ ### 2572.Count-the-Number-of-Square-Free-Subsets -数组的元素有n个,每个元素都有选或不选两种策略,故subset的种类就是`2^n`。本题的要求是寻找某些subset,使得他们的乘积里每个质因数最多只能出现一次。根据数值的范围(小于30),我们发现质因数的种类只有10种,即`2,3,5,7,11,13,17,19,23,29`. 所以我们可以用一个10 bit的二进制数state来表示哪些质因数已经被选了,那么对于任意nums[i]是否能选,其实就是取决于state。 - -所以我们可以知道本题是一个动态规划,状态变量是dp[i][state]。我们试图从dp[i-1]来推出dp[i]。 +数组的元素有n个,每个元素都有选或不选两种策略,故subset的种类就是`2^n`。本题的要求是寻找某些subset,使得他们的乘积里每个质因数最多只能出现一次。根据数值的范围(小于30),我们发现质因数的种类只有10种,即`2,3,5,7,11,13,17,19,23,29`. 所以我们可以用一个10 bit的二进制数state来表示哪些质因数已经被选了,那么对于任意nums[i]是否能选,其实就是取决于state。所以我们可以知道本题是一个动态规划,状态变量是dp[i][state]。我们试图从dp[i-1]来推出dp[i]。 如果我们不想选nums[i],那么有`dp[i][state] += dp[i-1][state]`。如果我们想选nums[i],那么有个前提条件,即state里必须包含nums[i]的所有质因数(且每个质因数必须只出现一次)。我们也可以用一个二进制数s来表示nums[i]所包含的质因数状态,那么有`dp[i][state] += dp[i-1][state-s]`. 特别注意,如果`nums[i]=1`,那么是否选取都没有影响,故`dp[i][state]=dp[i-1][state]*2`. From 3631745135e10733de049bc5b5647d97219592c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 00:35:15 -0800 Subject: [PATCH 1668/2729] Update Readme.md --- .../2572.Count-the-Number-of-Square-Free-Subsets/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md index 24a4f434f..afb7e284a 100644 --- a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md @@ -2,6 +2,6 @@ 数组的元素有n个,每个元素都有选或不选两种策略,故subset的种类就是`2^n`。本题的要求是寻找某些subset,使得他们的乘积里每个质因数最多只能出现一次。根据数值的范围(小于30),我们发现质因数的种类只有10种,即`2,3,5,7,11,13,17,19,23,29`. 所以我们可以用一个10 bit的二进制数state来表示哪些质因数已经被选了,那么对于任意nums[i]是否能选,其实就是取决于state。所以我们可以知道本题是一个动态规划,状态变量是dp[i][state]。我们试图从dp[i-1]来推出dp[i]。 -如果我们不想选nums[i],那么有`dp[i][state] += dp[i-1][state]`。如果我们想选nums[i],那么有个前提条件,即state里必须包含nums[i]的所有质因数(且每个质因数必须只出现一次)。我们也可以用一个二进制数s来表示nums[i]所包含的质因数状态,那么有`dp[i][state] += dp[i-1][state-s]`. 特别注意,如果`nums[i]=1`,那么是否选取都没有影响,故`dp[i][state]=dp[i-1][state]*2`. +如果我们不想选nums[i],那么有`dp[i][state] += dp[i-1][state]`。如果我们想选nums[i],那么有个前提条件,即state里必须包含nums[i]的所有质因数(且每个质因数必须只出现一次)。我们也可以用一个二进制数s来表示nums[i]所包含的质因数状态,那么有`dp[i][state] += dp[i-1][state-s]`. 特别注意,如果`nums[i]=1`,那么是否选取对state都没有影响,故`dp[i][state]=dp[i-1][state]*2`. 最终`sum(dp[n][state])`就是满足所有质因数最多只出现一次的subset的数目。注意要减一排除空集。 From db881e1b386010d32265d9ce9fd2882729fad067 Mon Sep 17 00:00:00 2001 From: LeaFZ Date: Mon, 20 Feb 2023 17:27:00 -0500 Subject: [PATCH 1669/2729] Update Readme.md --- Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md index 6050ccedc..d9d0e136c 100644 --- a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md +++ b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md @@ -2,6 +2,6 @@ 这道题可以用动态规划很方便地求解最大值,但是如果要记录最大值所对应的区间的位置,则会略显麻烦。 -考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是`[i:i+k-1]`,那么我们只需要求在`[0:i-1]`内最大的长度为k的区间,以及在`[i+1:n-1]`内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1] + sum[i:i+k-1] + rightMax[i+k]`即可。 +考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是`[i:i+k-1]`,那么我们只需要求在`[0:i-1]`内最大的长度为k的区间,以及在`[i+k:n-1]`内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1] + sum[i:i+k-1] + rightMax[i+k]`即可。 除此之外,我们还需要记录下leftMax[i]所对应的最大滑窗的位置,即为leftIdx[i]。这里要注意一个细节,因为题意要求,如果有多个总和相同的解,取index位置最小的解。所以我们从左往右遍历的时候,只有在leftMax大于历史最大值的时候才更新leftIdx,这样在相同的leftMax的时候我们保留的是较小的index。同理,我们在从右往左遍历的时候,当rightMax大于等于历史最大值,就可以更新rightIdx,这样在相同的rightMax的时候我们保留的是较小的index。 From 4880277cb065f7095cf10b3b651a2c6b5a26e66d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 18:08:53 -0800 Subject: [PATCH 1670/2729] Update 2572.Count-the-Number-of-Square-Free-Subsets.cpp --- .../2572.Count-the-Number-of-Square-Free-Subsets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp index b2350ec0b..648ae675d 100644 --- a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp @@ -28,7 +28,7 @@ class Solution { if (i==n) ret = (ret + dp[i][state]) % M; } - return ret-1; + return (ret+M-1)%M; } int helper(int x) From 9da6f8aedab90b522aa26625993c3675f4395d0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 22:31:00 -0800 Subject: [PATCH 1671/2729] Create 2573.Find-the-String-with-LCP.cpp --- .../2573.Find-the-String-with-LCP.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Greedy/2573.Find-the-String-with-LCP/2573.Find-the-String-with-LCP.cpp diff --git a/Greedy/2573.Find-the-String-with-LCP/2573.Find-the-String-with-LCP.cpp b/Greedy/2573.Find-the-String-with-LCP/2573.Find-the-String-with-LCP.cpp new file mode 100644 index 000000000..145edc209 --- /dev/null +++ b/Greedy/2573.Find-the-String-with-LCP/2573.Find-the-String-with-LCP.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + string findTheString(vector>& lcp) + { + int n = lcp.size(); + string s(n, '0'); + + int i = 0; + for (char ch = 'a'; ch<='z'; ch++) + { + while (i>dp(n, vector(n,0)); + for (int i=n-1; i>=0; i--) + for (int j=n-1; j>=0; j--) + { + if (s[i]==s[j]) + dp[i][j] = (i==n-1 || j==n-1)? 1: (dp[i+1][j+1] + 1); + if (dp[i][j] != lcp[i][j]) + return ""; + } + + return s; + } +}; From 2df4522ca2b796a0d4a4d3ca00db1533713a0bad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 22:31:21 -0800 Subject: [PATCH 1672/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 305099b80..3c4e699c1 100644 --- a/Readme.md +++ b/Readme.md @@ -1303,6 +1303,7 @@ [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) [2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) +[2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From ebc214b06ab18311029001ceed770235974d6553 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 22:56:54 -0800 Subject: [PATCH 1673/2729] Create Readme.md --- Greedy/2573.Find-the-String-with-LCP/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/2573.Find-the-String-with-LCP/Readme.md diff --git a/Greedy/2573.Find-the-String-with-LCP/Readme.md b/Greedy/2573.Find-the-String-with-LCP/Readme.md new file mode 100644 index 000000000..81a5db7cd --- /dev/null +++ b/Greedy/2573.Find-the-String-with-LCP/Readme.md @@ -0,0 +1,11 @@ +### 2573.Find-the-String-with-LCP + +首先,我们知道,如果lcp[i][j]>=0,那么一定意味着s[i]==s[j],这意味着我们知道任意两个字符是否相等的信息。假设LCP的信息是准确的,那么仅凭这些信息我们就可以充分地构造出字符串来。 + +我们先考察s中第一个未填写的位置i,此时必然是s[0]。由于我们只有字符相等的约束,而没有字符大小的约束,所以为了构造字典序最小的字符串,我们必然将s[0]填写为'a'。此时我们只需要考察所有`lcp[0][j]>0`的位置j,那么必然有s[j]=s[0]='a'。当然如果我们发现s[j]已经被填写过了且不是'a',那么说明引出了矛盾,可以直接返回无解。 + +接下来我们考察s中第二个未填写的字符i。注意这个位置可能不一定是s[1],因为s[1]可能已经由于一些相等关系的约束而已经填写了。同样,为了使得字典序最小,我们必然将s[i]置为'b'。此时我们只需要考察所有`lcp[i][j]>0`的位置j,那么必然有s[j]=s[i]='b'。当然如果我们发现s[j]已经被填写过了且不是'b',那么说明引出了矛盾,可以直接返回无解。 + +依次类推,我们可以将26个字母顺次填入s未填充的位置上。如果最后还有一些位置没有填充完,说明无法用26个英文字符完成任务。 + +以上得到的s是基于LCP可信赖的前提。但是LCP本身可能是有问题的,比如`lcp[0][2]=3`但是`lcp[1][3]=4`,这样的信息是矛盾的。所以我们还需要检验基于s的LCP矩阵的准确性。求任意两个位置的LCP,这本质就是求一个双序列的DP,用两层循环即可实现。 From b7054ae05d138a42f73e62fe4dfa4ce2b148736f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 23:33:37 -0800 Subject: [PATCH 1674/2729] Create 1987.Number-of-Unique-Good-Subsequences_v2.cpp --- ...87.Number-of-Unique-Good-Subsequences_v2.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/1987.Number-of-Unique-Good-Subsequences_v2.cpp diff --git a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/1987.Number-of-Unique-Good-Subsequences_v2.cpp b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/1987.Number-of-Unique-Good-Subsequences_v2.cpp new file mode 100644 index 000000000..76976d7a8 --- /dev/null +++ b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/1987.Number-of-Unique-Good-Subsequences_v2.cpp @@ -0,0 +1,17 @@ +using LL = long long; +class Solution { + LL M = 1e9+7; +public: + int numberOfUniqueGoodSubsequences(string binary) + { + int one = 0, zero = 0; + for (auto ch: binary) + { + if (ch=='0') + zero = (one + zero) % M; + else + one = (one + zero + 1) % M; + } + return (one + zero + (binary.find("0")==-1? 0:1)) % M; + } +}; From 58c30447bbce90fd3812bcf1764cc16313d4a335 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 23:44:19 -0800 Subject: [PATCH 1675/2729] Update Readme.md --- .../Readme.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md index a2bb93aed..7e494c40e 100644 --- a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md +++ b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md @@ -1,5 +1,6 @@ ### 1987.Number-of-Unique-Good-Subsequences +#### 解法1: 此题和```LC940.Distinct-Subsequences-II```的联系非常紧密。我们可以先用LC940的方法计算所有distinct subsequence的总数。令dp[i]表示前i个字符的前缀里有多少个不同的子序列(包括有先导零的子序列以及空子序列)。核心代码如下: ```cpp for (int i=1; i<=n; i++) @@ -12,11 +13,16 @@ for (int i=1; i<=n; i++) 这里给个直观的解释。首先,从i=m+1开始```+ dp[i-1]*2```这部分,意思是在前面已有的合法子序列的基础上,append s[i] or not,因此所对应的一定都是已经以1开头的子序列。其次```-dp[j-1]```这部分,去重的是形如```x x x s[i]```这样的字符串,其中```x x x```是前j-1个字符所能构建的distinct subsequence. 如果j-1<=m,那么这些dp[j-1]都预置为0,所以去重的部分也不会包括以0开头的子序列。综上所述,每一步所计算的dp[i]都表达的是以1开头的子序列。 -此外需要说明的是,很多题解的代码写成了如下的形式: +#### 解法2: +此题有非常简洁的DP解法。令zero表示截止目前以0结尾的unique子序列的数目,令one表示截止目前以1结尾的unique子序列的数目。那么 ```cpp if (s[i]=='0') - dp[i][0] = dp[i-1][0]+dp[i-1][1]; + zero = one + zero; else - dp[i][1] = dp[i-1][0]+dp[i-1][1]+1; + one = one + zero + 1; ``` -这样的结果是对的,但简洁的代码背后,理解上其实有很大的思维的跳跃,我觉得不够清晰。上面的表达式dp[i][0],看上去是说前i个字符构成的、以0结尾的合法子序列,必须是在前i-1个字符构成的合法子序列的基础上append当前s[i]所对应的这个0。dp[i][1]的解释同理类似,但多了一个单独以s[i]构造“1”的情况。但这个其实是没有道理的,我们完全有权利不使用s[i]这个字符呀。所以还有更深的微妙的分析隐藏在里面,对于这个代码的解释并不像表面上那么容易。国服的官方解答就是用了很大的篇幅才对上面的代码做了比较全面的解释。 +这段代码需要特别的解读。从字面上看,第一个分支里`zero = one + zero`语句更新后的zero,应该指以s[i]为结尾的、unqiue的子序列。但是注意到我们定义的zero,只是“以0结尾的、unique子序列的数目”,并没有要求一定要以s[i]结尾呀。这有问题吗?其实这就是精华所在。在前缀s[0:i]里,“以0结尾的、unique子序列的数目”必然等于“以s[i]结尾的、unique子序列的数目”。因为前者的任何一个序列,我们都可以把最后一个0的位置认为是放在s[i]。反之,后者的任何一个序列,也必然是以0结尾的。 + +同理,我们可以解释第二个分支。其中“+1”是因为s[i]可以自己单独作为序列,但是0不行(它会给后面子序列的生成产生先导零)。 + +最终的答案是`one+zero`。如果s里存在任何一个0的话,那么再加1. From a4cd181c21f0e19f347a240f255c56c07bc9fc6f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 23:44:34 -0800 Subject: [PATCH 1676/2729] Update Readme.md --- .../1987.Number-of-Unique-Good-Subsequences/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md index 7e494c40e..08f852f63 100644 --- a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md +++ b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md @@ -1,6 +1,6 @@ ### 1987.Number-of-Unique-Good-Subsequences -#### 解法1: +#### 解法1(deprecated) 此题和```LC940.Distinct-Subsequences-II```的联系非常紧密。我们可以先用LC940的方法计算所有distinct subsequence的总数。令dp[i]表示前i个字符的前缀里有多少个不同的子序列(包括有先导零的子序列以及空子序列)。核心代码如下: ```cpp for (int i=1; i<=n; i++) From d352c9f0da190b2e601b66b4986f4d657d50cb60 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Feb 2023 00:14:09 -0800 Subject: [PATCH 1677/2729] Create 940.Distinct-Subsequences-II_v2.cpp --- .../940.Distinct-Subsequences-II_v2.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v2.cpp diff --git a/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v2.cpp b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v2.cpp new file mode 100644 index 000000000..6e4252b56 --- /dev/null +++ b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v2.cpp @@ -0,0 +1,22 @@ +using LL = long long; +class Solution { + LL dp[26]; + LL M = 1e9+7; +public: + int distinctSubseqII(string s) + { + for (char ch: s) + { + LL sum = 0; + for (int i=0; i<26; i++) + sum = (sum + dp[i]) % M; + + dp[ch-'a'] = sum + 1; + } + + LL ret = 0; + for (int i=0; i<26; i++) + ret = (ret + dp[i]) % M; + return ret; + } +}; From 2bacd54cfad7707cd15fdbc6d08ffb6b942f4048 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Feb 2023 00:14:21 -0800 Subject: [PATCH 1678/2729] Rename 940.Distinct-Subsequences-II.cpp to 940.Distinct-Subsequences-II_v1.cpp --- ...ct-Subsequences-II.cpp => 940.Distinct-Subsequences-II_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/940.Distinct-Subsequences-II/{940.Distinct-Subsequences-II.cpp => 940.Distinct-Subsequences-II_v1.cpp} (100%) diff --git a/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v1.cpp similarity index 100% rename from Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp rename to Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v1.cpp From 2ccfd3bc26298db6eb7d5455e6c7f15b1b25992a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Feb 2023 00:15:21 -0800 Subject: [PATCH 1679/2729] Update Readme.md --- .../1987.Number-of-Unique-Good-Subsequences/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md index 08f852f63..715e8c50c 100644 --- a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md +++ b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md @@ -1,6 +1,6 @@ ### 1987.Number-of-Unique-Good-Subsequences -#### 解法1(deprecated) +#### 解法1 (deprecated) 此题和```LC940.Distinct-Subsequences-II```的联系非常紧密。我们可以先用LC940的方法计算所有distinct subsequence的总数。令dp[i]表示前i个字符的前缀里有多少个不同的子序列(包括有先导零的子序列以及空子序列)。核心代码如下: ```cpp for (int i=1; i<=n; i++) @@ -13,7 +13,7 @@ for (int i=1; i<=n; i++) 这里给个直观的解释。首先,从i=m+1开始```+ dp[i-1]*2```这部分,意思是在前面已有的合法子序列的基础上,append s[i] or not,因此所对应的一定都是已经以1开头的子序列。其次```-dp[j-1]```这部分,去重的是形如```x x x s[i]```这样的字符串,其中```x x x```是前j-1个字符所能构建的distinct subsequence. 如果j-1<=m,那么这些dp[j-1]都预置为0,所以去重的部分也不会包括以0开头的子序列。综上所述,每一步所计算的dp[i]都表达的是以1开头的子序列。 -#### 解法2: +#### 解法2 (preferred) 此题有非常简洁的DP解法。令zero表示截止目前以0结尾的unique子序列的数目,令one表示截止目前以1结尾的unique子序列的数目。那么 ```cpp if (s[i]=='0') From 7664a222d11cc94167409dc9ff4beb45335d7426 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Feb 2023 00:24:54 -0800 Subject: [PATCH 1680/2729] Update Readme.md --- .../940.Distinct-Subsequences-II/Readme.md | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/940.Distinct-Subsequences-II/Readme.md b/Dynamic_Programming/940.Distinct-Subsequences-II/Readme.md index 71a15ab6f..d9e0d5f8a 100644 --- a/Dynamic_Programming/940.Distinct-Subsequences-II/Readme.md +++ b/Dynamic_Programming/940.Distinct-Subsequences-II/Readme.md @@ -1,5 +1,7 @@ ### 940.Distinct-Subsequences-II +#### 解法1:(deprecated) + 此题是字符串序列的一道经典题。如果第一次做的话,可能会觉得有难度。 尝试构造状态dp[i],表示截止第i个字符为止,我们能够创建的distinct子序列有多少.对于这个dp[i]的定义,我们并不要求s[i]必须是子序列的一部分。 @@ -34,7 +36,7 @@ XXa (8) 最终的输出是dp[n]。但是这个数字包含了“空字串”,所以答案需要再减去1. -#### 补充 +##### 补充 有一个听众问我,为什么去重的操作里,只需要减去dp[j-1](j是上一个满足S[j]==S[i]的字符的index),而不减去其他的dp[k-1](k是在j更早之前的某些字符,也满足S[k]==S[i])。这个问题很深刻。 我举个例子:...XXX... (a1) ...YYY... (a2) ...ZZZ... (a3), 其中a1,a2,a3都代表相同的字符a,他们对应的index分别是k,j,i. XXX/YYY/ZZZ表示在各自区间内取的某个subsequence. @@ -51,5 +53,22 @@ XXX(a3) ``` 这是因为```XXX(a1)```本质是和```XXXYYY(a2)```重合的!就最终的subsequence的样子而言,前者就是后者的一部分。我们计算dp[i]时,减去的dp[j-1],去掉了形如```XXXYYY(a2)```的重复,其实也就已经去掉了形如```XXX(a1)```的重复。所以我们不需要考虑其他在j之前的任何S[k]==S[i]的case。 +#### 解法2:(preferred) +此题和`1987.Number-of-Unique-Good-Subsequences`几乎一样。 + +我们令dp[c]表示截止到目前,以字母c结尾的unique subsequence的数目。 + +核心的代码是: +```cpp + for (int i=0; i Date: Sat, 25 Feb 2023 11:54:25 -0800 Subject: [PATCH 1681/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md b/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md index ba980904b..9a0b090a0 100644 --- a/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md +++ b/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md @@ -20,7 +20,7 @@ return ret + bonus; } ``` -上面的```dfs(count, presum, i)```表示我们已经选择了i-1个groups(它们的前缀和是presum、已有的得分是prescore),我们从剩下的groups挑选一个安排在第i个。选哪个好呢?我们不知道,必须每种可能都尝试一次,结合相应的```dfs(..., i+1)```来判断。这里需要注意的是,如果此时的presum恰好被batch整除,那么说明无论第i个元素取谁,我们都可以得到1分,所以下次递归的时候perscore可以增加1。 +上面的```dfs(count, presum, i)```表示我们已经选择了i-1个groups(它们的前缀和是presum、已有的得分记做prescore),我们从剩下的groups挑选一个安排在第i个。选哪个好呢?我们不知道,必须每种可能都尝试一次,结合相应的```dfs(..., i+1)```来判断。这里需要注意的是,如果此时的presum恰好被batch整除,那么说明无论第i个元素取谁,我们都可以得到1分,所以下次递归的时候prescore可以增加1。 以上的解法自然会TLE,原因是什么呢?显然是没有记忆化。我们可以发现,dfs函数中,其实只要确定了当前的count(即未被安排的groups),其他的参数presum本质上就是确定了的。所以记忆化的key其实就是count。但是count是一个数组,如何将转化为一个方便的key呢?和状态压缩相同的原因。因为count[i]最多30个,用五个bit就能表示(0~32)。batch最多是9,所以总共45位的二进制数就可以表述count数组。这就要求这个key是long long类型。 From 1a0f5ef39bc5078a3839e8aa012bba96a93868b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Feb 2023 11:57:10 -0800 Subject: [PATCH 1682/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md b/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md index 9a0b090a0..47e84d952 100644 --- a/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md +++ b/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md @@ -20,7 +20,7 @@ return ret + bonus; } ``` -上面的```dfs(count, presum, i)```表示我们已经选择了i-1个groups(它们的前缀和是presum、已有的得分记做prescore),我们从剩下的groups挑选一个安排在第i个。选哪个好呢?我们不知道,必须每种可能都尝试一次,结合相应的```dfs(..., i+1)```来判断。这里需要注意的是,如果此时的presum恰好被batch整除,那么说明无论第i个元素取谁,我们都可以得到1分,所以下次递归的时候prescore可以增加1。 +上面的```dfs(count, presum, i)```表示我们已经选择了i-1个groups(它们的前缀和是presum,哪些被选择了记录在count里),我们从剩下的groups挑选一个安排在第i个。选哪个好呢?我们不知道,必须每种可能都尝试一次,结合相应的```dfs(..., i+1)```来判断。这里需要注意的是,如果此时的presum恰好被batch整除,那么说明无论第i个元素取谁,我们都可以得到1分。所以返回的答案就是下轮递归 里的最大值,再加本轮的1。 以上的解法自然会TLE,原因是什么呢?显然是没有记忆化。我们可以发现,dfs函数中,其实只要确定了当前的count(即未被安排的groups),其他的参数presum本质上就是确定了的。所以记忆化的key其实就是count。但是count是一个数组,如何将转化为一个方便的key呢?和状态压缩相同的原因。因为count[i]最多30个,用五个bit就能表示(0~32)。batch最多是9,所以总共45位的二进制数就可以表述count数组。这就要求这个key是long long类型。 From b8d22dd86cb5e35eaa7d2cdf6aaa0d6feb921290 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Feb 2023 23:46:36 -0800 Subject: [PATCH 1683/2729] Create 2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp --- ...Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp diff --git a/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp b/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp new file mode 100644 index 000000000..d39f07620 --- /dev/null +++ b/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp @@ -0,0 +1,44 @@ +using AI3 = array; +class Solution { + vector>dir= {{0,1},{0,-1},{1,0},{-1,0}}; +public: + int minimumTime(vector>& grid) + { + if (grid[0][1]>1 && grid[1][0]>1) return -1; + + int m = grid.size(), n = grid[0].size(); + vector>arrival(m, vector(n,-1)); + + priority_queue, greater<>>pq; + if (grid[0][1]<=1) pq.push({1,0,1}); + if (grid[1][0]<=1) pq.push({1,1,0}); + + while (!pq.empty()) + { + auto [t,x,y] = pq.top(); + pq.pop(); + if (arrival[x][y]!=-1) + continue; + arrival[x][y] = t; + if (x==m-1 && y==n-1) + break; + + for (int k=0; k<4; k++) + { + int i = x+dir[k].first; + int j = y+dir[k].second; + if (i<0||i>=m||j<0||j>=n) continue; + if (arrival[i][j] != -1) continue; + + if (grid[i][j]<=t+1) + pq.push({t+1, i, j}); + else if ((grid[i][j]-t)%2==0) + pq.push({grid[i][j]+1, i, j}); + else + pq.push({grid[i][j], i, j}); + } + } + + return arrival[m-1][n-1]; + } +}; From 8ef1fdc79fdc717fb7ae3edad45aa9901a0ab8e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Feb 2023 23:48:03 -0800 Subject: [PATCH 1684/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3c4e699c1..1ab932ffe 100644 --- a/Readme.md +++ b/Readme.md @@ -579,6 +579,7 @@ [2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) +[2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From 9c77de305900fa764e077e411d8144f2daef990e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Feb 2023 00:02:59 -0800 Subject: [PATCH 1685/2729] Create Readme.md --- BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md diff --git a/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md b/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md new file mode 100644 index 000000000..a2ce41a08 --- /dev/null +++ b/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md @@ -0,0 +1,7 @@ +### 2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid + +如果本题没有“you must move to any adjacent cell”这个要求,那么套用Dijkstra算法的模板即可求得到达右下角的最短路径。其中任意两条相邻的格子a->b之间的边权就是`max(1, grid[b]-arrival[a]`,表示到达a之后,可以立即走一步到达b,或者原地等待到b的准入时刻再进入b。 + +以上算法的问题在于,我们不能在原地等待。假设我们到达a的时刻是3,但是其相邻的b点的准入时刻是5。显然,我们不能在时刻4的时候进入b,但我们可以再时刻5的时候进入b吗?其实也不能。我们唯一能拖延时间的方法就是从a走到一个相邻的格子再走回a,这样可以拖延两秒的时间,再进入b的时刻就是6. 同理我们可以发现,从a到任何与其相邻的格子b,考虑到“往复拖延”的策略,所需要的时间增量必然是+1,+3,+5,... 直至大于等于b的准入时刻。 + +所以我们只需要更新Dijkstra的部分代码。假设到达a的时刻是t,其相邻格子的准入时间是grid[b],那么如果`grid[b]<=t+1`,说明最早可以在t+1的时刻进入b;如果`(grid[b]-t)%2==1`,那么我们可以反复横跳之后恰好在grid[b]时刻进入b;否则我们需要在`grid[b]+1`时刻进入b。 From 67592c6b3aaf133f1a3d62268b943851e130bd40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Feb 2023 09:26:06 -0800 Subject: [PATCH 1686/2729] Create 2576.Find-the-Maximum-Number-of-Marked-Indices.cpp --- ...d-the-Maximum-Number-of-Marked-Indices.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/2576.Find-the-Maximum-Number-of-Marked-Indices.cpp diff --git a/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/2576.Find-the-Maximum-Number-of-Marked-Indices.cpp b/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/2576.Find-the-Maximum-Number-of-Marked-Indices.cpp new file mode 100644 index 000000000..f18f83e3d --- /dev/null +++ b/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/2576.Find-the-Maximum-Number-of-Marked-Indices.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxNumOfMarkedIndices(vector& nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + + int i = 0, j = n/2; + int count = 0; + for (int i=0; inums[j]) + j++; + if (j Date: Sun, 26 Feb 2023 09:26:27 -0800 Subject: [PATCH 1687/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1ab932ffe..a2fa00ebe 100644 --- a/Readme.md +++ b/Readme.md @@ -1305,6 +1305,7 @@ [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) [2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) +[2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 51d97be6bc20dd5f6de4cf6abca9fc63cdf77ea9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Feb 2023 10:47:39 -0800 Subject: [PATCH 1688/2729] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/Readme.md diff --git a/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/Readme.md b/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/Readme.md new file mode 100644 index 000000000..41674d4bf --- /dev/null +++ b/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/Readme.md @@ -0,0 +1,12 @@ +### 2576.Find-the-Maximum-Number-of-Marked-Indices + +一个比较容易想到的贪心策略就是,对于最小的元素a,我们找到对应的恰好满足`b>=2a`的元素b与之配对。目的是尽量保留更大的元素可以用来匹配次小的元素。然后重复这样的过程。 + +但是这种策略会遇到这样的一个例子:`[2,4,5,9]`。当2与4匹配之后,此时未被匹配的次小元素是5,反而变得更大了。 + +正确的思考方式是:如果总元素是n,那么最多能匹配n/2对。为了更多地凑出这些pairs,每个pair的较小值必然在排序后的nums的前半部分,而较大值在nums的后半部分。假设有一对[a,b]都在前半部分,另一对[c,d]都在后半部分,那么必然可以重构出两对[a,c],[b,d]同样更容易条件。同理,可以证明出其他情况下,任何处于同一个半区的配对都不会是最优解。 + +所以本题只需要使用双指针,第一个指针i在前半区遍历,第二个指针j在后半区遍历,对于每个i单调移动j看看是否能有配对即可。 + +本题在codeforces上的原题是:https://codeforces.com/contest/372/problem/A + From b04aa37a2f77b471c9f745a49ac26eb1c016956f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 13:01:24 -0800 Subject: [PATCH 1689/2729] Create 2370.Longest-Ideal-Subsequence_v2.cpp --- .../2370.Longest-Ideal-Subsequence_v2.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v2.cpp diff --git a/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v2.cpp b/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v2.cpp new file mode 100644 index 000000000..91fb684f6 --- /dev/null +++ b/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int longestIdealString(string s, int k) + { + int n = s.size(); + vectordp(26, 0); + + int ret = 0; + for (int i=0; i Date: Sat, 4 Mar 2023 13:01:34 -0800 Subject: [PATCH 1690/2729] Rename 2370.Longest-Ideal-Subsequence.cpp to 2370.Longest-Ideal-Subsequence_v1.cpp --- ...deal-Subsequence.cpp => 2370.Longest-Ideal-Subsequence_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/2370.Longest-Ideal-Subsequence/{2370.Longest-Ideal-Subsequence.cpp => 2370.Longest-Ideal-Subsequence_v1.cpp} (100%) diff --git a/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence.cpp b/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v1.cpp similarity index 100% rename from Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence.cpp rename to Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v1.cpp From ff04d1a686caf333991fa3f731997fd64ddf1f04 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 13:07:15 -0800 Subject: [PATCH 1691/2729] Update Readme.md --- Greedy/2370.Longest-Ideal-Subsequence/Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Greedy/2370.Longest-Ideal-Subsequence/Readme.md b/Greedy/2370.Longest-Ideal-Subsequence/Readme.md index bd5594ce6..73b704c45 100644 --- a/Greedy/2370.Longest-Ideal-Subsequence/Readme.md +++ b/Greedy/2370.Longest-Ideal-Subsequence/Readme.md @@ -1,7 +1,11 @@ ### 2370.Longest-Ideal-Subsequence -本题是常规的动态规划。令dp[i]表示以i为结尾的最长subsequence的长度。我们需要寻找这个subsequence的上一个位置j,这样就有`dp[i]=dp[j]+1`。那么j可以是在哪里呢?根据题意,j所在的字母必须是与s[i]的ASCII差距在k以内的字母。在知道是哪些字母后,于是我们需要维护一个长度为26的数组`prev[ch]`,表示当前位置i之前最近的字母ch出现在哪个位置。 +#### 解法1 +令dp[i]表示以i为结尾的最长subsequence的长度。我们需要寻找这个subsequence的上一个位置j,这样就有`dp[i]=dp[j]+1`。那么j可以是在哪里呢?根据题意,j所在的字母必须是与s[i]的ASCII差距在k以内的字母。在知道是哪些字母后,于是我们需要维护一个长度为26的数组`prev[ch]`,表示当前位置i之前最近的字母ch出现在哪个位置。 举个例子,如果当前s[i]='b',且k=1。那么我们就需要查看这两处位置`j1 = prev['a']`和`j2 = prev['c]`,这样就可以有`dp[i] = max(dp[j1], dp[j2]) + 1`. 特别注意,对于任意的dp[i]都有一个基本解是`dp[i] = 1`. 最终的答案是返回在全局`dp[i]`中最大的一个。 + +#### 解法2 +令dp[ch]表示以字母ch为结尾的最长子序列的长度。那么对于s[i]而言,假设其字母是c,我们可以知道如果以s[i]为结尾的子序列,其倒数第二个字母的取值范围[x:y],于是dp[c]就可以更新为dp[x]到dp[y]中的最大值加一。 From 6e9accc7bf202ac37d09e22b8cf9c42af77ea437 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 22:29:11 -0800 Subject: [PATCH 1692/2729] Create 2580.Count-Ways-to-Group-Overlapping-Ranges.cpp --- ...Count-Ways-to-Group-Overlapping-Ranges.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/2580.Count-Ways-to-Group-Overlapping-Ranges.cpp diff --git a/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/2580.Count-Ways-to-Group-Overlapping-Ranges.cpp b/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/2580.Count-Ways-to-Group-Overlapping-Ranges.cpp new file mode 100644 index 000000000..f37b46d2b --- /dev/null +++ b/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/2580.Count-Ways-to-Group-Overlapping-Ranges.cpp @@ -0,0 +1,26 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int countWays(vector>& ranges) + { + sort(ranges.begin(), ranges.end()); + int n = ranges.size(); + LL ret = 1; + + for (int i=0; i Date: Sat, 4 Mar 2023 22:29:56 -0800 Subject: [PATCH 1693/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a2fa00ebe..c845d7e6c 100644 --- a/Readme.md +++ b/Readme.md @@ -1289,6 +1289,7 @@ [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) +[2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From b9ae0bb695df157006035dbc598c3a1722e69b03 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 22:39:02 -0800 Subject: [PATCH 1694/2729] Create Readme.md --- .../2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md diff --git a/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md b/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md new file mode 100644 index 000000000..7cc1a18c6 --- /dev/null +++ b/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md @@ -0,0 +1,7 @@ +### 2580.Count-Ways-to-Group-Overlapping-Ranges + +对于区间类型的题目,最常见的处理手段就是将其排序。多数情况下,按照左端点排序就能解决很多问题。 + +我们考虑排序后的第一个区间范围是[l,r],我们只需要顺次往后遍历,就可以找到所有左端点小于等于r的区间。这些区间必然与第一个区间重合,它们必须归为一组。此时已经遍历过的这些区间,它们会有一个最远的右边界far,之后凡是左边界小于等于far的区间必然又会与这个组群有重叠。所以我们可以一路遍历下去:不断加入左边界小于等于far的区间,同时又更新far值变得更大。直至下一个区间的左边界大于far,说明之前的这些区间,必然有传递的交叠的关系,必须都归为一大组。 + +假设存在K个这样的大组,每个大组需要二选一站队,那么最终的答案就是2^N。 From a865ddd2c6b2dcc0a3fe5e2a57283386c5ffa2a8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 23:43:32 -0800 Subject: [PATCH 1695/2729] Create 2581.Count-Number-of-Possible-Root-Nodes.cpp --- ...81.Count-Number-of-Possible-Root-Nodes.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp new file mode 100644 index 000000000..aec7c67b0 --- /dev/null +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp @@ -0,0 +1,62 @@ +class Solution { + vectornext[100005]; + unordered_setguess[100005]; + int ret = 0; + int k; + int good[100005]; + int bad[100005]; +public: + int rootCount(vector>& edges, vector>& guesses, int k) + { + int n = edges.size()+1; + this-> k = k; + for (auto e: edges) + { + next[e[0]].push_back(e[1]); + next[e[1]].push_back(e[0]); + } + + for (auto g: guesses) + guess[g[0]].insert(g[1]); + + dfs(0, -1); + + dfs2(0, -1, good[0]); + + return ret; + } + + void dfs(int cur, int parent) + { + int count = 0; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + + if (guess[cur].find(nxt)!=guess[cur].end()) + good[cur] += 1; + if (guess[nxt].find(cur)!=guess[nxt].end()) + bad[cur] += 1; + + dfs(nxt, cur); + good[cur] += good[nxt]; + bad[cur] += bad[nxt]; + } + } + + void dfs2(int cur, int parent, int count) + { + if (count >= k) ret++; + + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + int temp = count; + if (guess[cur].find(nxt)!=guess[cur].end()) + temp -= 1; + if (guess[nxt].find(cur)!=guess[nxt].end()) + temp += 1; + dfs2(nxt, cur, temp); + } + } +}; From ef3b630846d819f723aa06a87b187750877f921a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 23:44:03 -0800 Subject: [PATCH 1696/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c845d7e6c..6e58c2efb 100644 --- a/Readme.md +++ b/Readme.md @@ -292,6 +292,7 @@ [1516.Move-Sub-Tree-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1516.Move-Sub-Tree-of-N-Ary-Tree) (H-) * ``Re-Root`` [834.Sum-of-Distances-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/834.Sum-of-Distances-in-Tree) (H) +[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) * ``似树非树`` [823](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/823.Binary-Trees-With-Factors), [1902](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order), From 959271ea704ddfb7f7e2ef00483767e50c1e33d9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 08:29:21 -0800 Subject: [PATCH 1697/2729] Update 2581.Count-Number-of-Possible-Root-Nodes.cpp --- .../2581.Count-Number-of-Possible-Root-Nodes.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp index aec7c67b0..dce0ec153 100644 --- a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp @@ -3,8 +3,8 @@ class Solution { unordered_setguess[100005]; int ret = 0; int k; - int good[100005]; - int bad[100005]; + int along[100005]; + int against[100005]; public: int rootCount(vector>& edges, vector>& guesses, int k) { @@ -21,7 +21,7 @@ class Solution { dfs(0, -1); - dfs2(0, -1, good[0]); + dfs2(0, -1, along[0]); return ret; } @@ -34,13 +34,13 @@ class Solution { if (nxt==parent) continue; if (guess[cur].find(nxt)!=guess[cur].end()) - good[cur] += 1; + along[cur] += 1; if (guess[nxt].find(cur)!=guess[nxt].end()) - bad[cur] += 1; + against[cur] += 1; dfs(nxt, cur); - good[cur] += good[nxt]; - bad[cur] += bad[nxt]; + along[cur] += along[nxt]; + against[cur] += against[nxt]; } } From 2b01c65ac2737856cd47a52804859413a035645f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 08:46:16 -0800 Subject: [PATCH 1698/2729] Create Readme.md --- Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md b/Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md new file mode 100644 index 000000000..b6495713f --- /dev/null +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md @@ -0,0 +1,9 @@ +### 2581.Count-Number-of-Possible-Root-Nodes + +既然题目问的是“有多少节点作为根符合要求”,那么我们自然就会思考遍历每个节点作为根的情况。因为节点总数是1e5,所以我们只能用线性的时间遍历完整棵树,并且对于每个根的情况下,用o(1)的时候做出判断。 + +对于这种题目,有一种常见的套路就是“移根”。假设当前节点A作为根时,答案为a,那么以A的某个邻接节点B未做根时,答案能否快速从a转化而来呢? + +假设当前节点A作为根时,它对应的guesses里面有x个顺序的猜想(猜对了),y个逆序的猜想(猜错了)。那么我们转而考虑以B为根时,顺逆序唯一改变的边其实就只有AB之间的路径。所以如果AB边原本是一个顺序的猜想,那么此刻就会变成逆序;如果AB边原本是一个逆序的猜想,那么此刻就会变成顺序。 + +所以本题的做法就是,先以任意节点(比如说0)为根,一遍dfs计算有多少正确的guess,假设叫做count。然后递归处理它相邻的节点作为根的情况,只需要考察这条相邻边的正逆序变化改变了多少猜想,更新count即可。 From 40176bcfa6181a43c71a93727c3187a440b7168c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 08:46:48 -0800 Subject: [PATCH 1699/2729] Update 2581.Count-Number-of-Possible-Root-Nodes.cpp --- .../2581.Count-Number-of-Possible-Root-Nodes.cpp | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp index dce0ec153..806fae8ef 100644 --- a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp @@ -3,8 +3,7 @@ class Solution { unordered_setguess[100005]; int ret = 0; int k; - int along[100005]; - int against[100005]; + int count[100005]; public: int rootCount(vector>& edges, vector>& guesses, int k) { @@ -21,26 +20,22 @@ class Solution { dfs(0, -1); - dfs2(0, -1, along[0]); + dfs2(0, -1, count[0]); return ret; } void dfs(int cur, int parent) { - int count = 0; for (int nxt: next[cur]) { if (nxt==parent) continue; if (guess[cur].find(nxt)!=guess[cur].end()) - along[cur] += 1; - if (guess[nxt].find(cur)!=guess[nxt].end()) - against[cur] += 1; + count[cur] += 1; dfs(nxt, cur); - along[cur] += along[nxt]; - against[cur] += against[nxt]; + count[cur] += count[nxt]; } } From 86c5d98876671ac3919954eb4b25e0fd0308f17a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 09:18:18 -0800 Subject: [PATCH 1700/2729] Update 2581.Count-Number-of-Possible-Root-Nodes.cpp --- ...81.Count-Number-of-Possible-Root-Nodes.cpp | 47 +++++++++---------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp index 806fae8ef..a35eb63e7 100644 --- a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp @@ -1,51 +1,46 @@ class Solution { - vectornext[100005]; - unordered_setguess[100005]; - int ret = 0; + vector next[100005]; + unordered_set guess[100005]; int k; - int count[100005]; + int ret = 0; public: - int rootCount(vector>& edges, vector>& guesses, int k) - { + int rootCount(vector>& edges, vector>& guesses, int k) { + this->k = k; int n = edges.size()+1; - this-> k = k; - for (auto e: edges) + for (auto& e: edges) { next[e[0]].push_back(e[1]); next[e[1]].push_back(e[0]); } - - for (auto g: guesses) - guess[g[0]].insert(g[1]); - - dfs(0, -1); - - dfs2(0, -1, count[0]); - + for (auto& g: guesses) + guess[g[0]].insert(g[1]); + + int count = dfs(0, -1); + + dfs2(0, -1, count); + return ret; } - - void dfs(int cur, int parent) + + int dfs(int cur, int parent) { + int count = 0; for (int nxt: next[cur]) { if (nxt==parent) continue; - + count += dfs(nxt, cur); if (guess[cur].find(nxt)!=guess[cur].end()) - count[cur] += 1; - - dfs(nxt, cur); - count[cur] += count[nxt]; + count +=1; } + return count; } - + void dfs2(int cur, int parent, int count) { if (count >= k) ret++; - for (int nxt: next[cur]) { - if (nxt==parent) continue; + if (nxt==parent) continue; int temp = count; if (guess[cur].find(nxt)!=guess[cur].end()) temp -= 1; From 0b015dd479edb6f113f056341d7c0c3ef38d17ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 17:01:46 -0800 Subject: [PATCH 1701/2729] Create 2585.Number-of-Ways-to-Earn-Points.cpp --- .../2585.Number-of-Ways-to-Earn-Points.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/2585.Number-of-Ways-to-Earn-Points.cpp diff --git a/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/2585.Number-of-Ways-to-Earn-Points.cpp b/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/2585.Number-of-Ways-to-Earn-Points.cpp new file mode 100644 index 000000000..4c704718d --- /dev/null +++ b/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/2585.Number-of-Ways-to-Earn-Points.cpp @@ -0,0 +1,23 @@ +using LL = long long; +class Solution { + LL dp[51][1005]; + LL M = 1e9+7; +public: + int waysToReachTarget(int target, vector>& types) + { + int n = types.size(); + types.insert(types.begin(), {0,0}); + dp[0][0] = 1; + for (int i=1; i<=n; i++) + for (int j=0; j<=target; j++) + { + for (int k=0; k<=types[i][0]; k++) + { + if (k*types[i][1]>j) break; + dp[i][j] += dp[i-1][j- k*types[i][1]]; + dp[i][j] %= M; + } + } + return dp[n][target]; + } +}; From a92a03c4ab02f67ee2d110bbfb7baa531a61851c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 17:02:08 -0800 Subject: [PATCH 1702/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6e58c2efb..67b71d05f 100644 --- a/Readme.md +++ b/Readme.md @@ -751,6 +751,7 @@ [1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements) (M+) [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) +[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From fb17511b3e29176c3792e0248c15b75755fee0fc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 17:05:19 -0800 Subject: [PATCH 1703/2729] Create Readme.md --- .../2585.Number-of-Ways-to-Earn-Points/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/Readme.md diff --git a/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/Readme.md b/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/Readme.md new file mode 100644 index 000000000..1b6298c6a --- /dev/null +++ b/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/Readme.md @@ -0,0 +1,15 @@ +### 2585.Number-of-Ways-to-Earn-Points + +非常常规的背包DP。将第二个下标设计为已经取得的分数。令dp[i][j]表示前i种题目里恰好取得j分的方案数。对于每种题目类型,我们尝试取不同的数目k。所以总共三层循环。比如,当第i种题目取k道题时,那么方案就取决于前i-1中题目里取`j- k*types[i][1]`分的方案数。 +```cpp +for (int i=1; i<=n; i++) + for (int j=0; j<=target; j++) + { + for (int k=0; k<=types[i][0]; k++) + { + if (k*types[i][1]>j) break; + dp[i][j] += dp[i-1][j- k*types[i][1]]; + dp[i][j] %= M; + } + } +``` From 33e706b2edae8cbae37948835a997fda9080f58a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 19:38:04 -0800 Subject: [PATCH 1704/2729] Create 2584.Split-the-Array-to-Make-Coprime-Products.cpp --- ...lit-the-Array-to-Make-Coprime-Products.cpp | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp diff --git a/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp b/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp new file mode 100644 index 000000000..5180f3b5d --- /dev/null +++ b/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp @@ -0,0 +1,76 @@ +class Solution { +public: + vectorEratosthenes(int n) + { + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); + } + return primes; + } + + int findValidSplit(vector& nums) + { + int K = *max_element(nums.begin(), nums.end()); + vectorprimes = Eratosthenes(K); + + unordered_map>Map; + for (int i=0; ix) + { + if (Map.find(x)==Map.end()) + Map[x].first = i; + Map[x].second = i; + break; + } + + if (x%p==0) + { + if (Map.find(p)==Map.end()) + Map[p].first = i; + Map[p].second = i; + } + while (x%p==0) + { + x/=p; + } + } + } + + int n = nums.size(); + vectordiff(n+1); + for (auto& [k, v]: Map) + { + if (v.first == v.second) continue; + diff[v.first]+=1; + diff[v.second]-=1; + } + + int sum = 0; + for (int i=0; i Date: Sun, 5 Mar 2023 19:38:30 -0800 Subject: [PATCH 1705/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 67b71d05f..a8e48513a 100644 --- a/Readme.md +++ b/Readme.md @@ -1393,6 +1393,7 @@ [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) [2327.Number-of-People-Aware-of-a-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Others/2327.Number-of-People-Aware-of-a-Secret) (H-) [2381.Shifting-Letters-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/2381.Shifting-Letters-II) (M) +[2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From ee8749246117ccdad9fe86fb6b89c6797aa18537 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 20:05:49 -0800 Subject: [PATCH 1706/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/2584.Split-the-Array-to-Make-Coprime-Products/Readme.md diff --git a/Others/2584.Split-the-Array-to-Make-Coprime-Products/Readme.md b/Others/2584.Split-the-Array-to-Make-Coprime-Products/Readme.md new file mode 100644 index 000000000..b358fa28a --- /dev/null +++ b/Others/2584.Split-the-Array-to-Make-Coprime-Products/Readme.md @@ -0,0 +1,9 @@ +### 2584.Split-the-Array-to-Make-Coprime-Products + +因为本题里nums的数值都很大,连乘几个数就会溢出,所以我们无法通过直接计算乘积来解题。 + +既然是互质,一个很自然的想法就是从质因数入手。如果某个质因数p在nums里存在的范围是从[a:b],那么显然,我们所寻找的前缀切割位置不能在[a:b]的中间,否则切割前后的两部分就会有公约数p。 + +所以基本的算法思想就是。考察每个元素,记录它的所有质因数。然后对每种质因数,我们记录它在nums里出现的范围,只要记录第一次出现和最后一次出现的位置即可,记做一个区间。这样,我们可以收集到很多的区间。之后我们要寻找某个前缀的位置,使其不能切割任何一个区间。怎么实现呢?很明显我们可以用扫描线(差分数组)来做。对于一个区间[a,b],我们就记录差分`diff[a]+=1, diff[b]-=1`,这样当我们从前往后的积分值第一次出现零的时候,就表示该处没有落在任何区间里面,即是符合条件的前缀截止位置。 + +时间复杂度分析:遍历所有元素是o(N),每个元素的分解质因数的复杂度是sqrt(M),M是数值的大小,故大概是`1e4*sqrt(1e6) = 1e7`,勉强可以接受。事实上,如果先把所有的质因数提前计算出来,能够帮助更快地分解质因数。 From e3f639064702a8fef1ad9ddffc2bb985f0f0df51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 7 Mar 2023 17:48:48 -0800 Subject: [PATCH 1707/2729] Update 2584.Split-the-Array-to-Make-Coprime-Products.cpp --- ...lit-the-Array-to-Make-Coprime-Products.cpp | 70 ++++++++++--------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp b/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp index 5180f3b5d..b26f692ff 100644 --- a/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp +++ b/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp @@ -1,68 +1,70 @@ -class Solution { -public: - vectorEratosthenes(int n) +vectorEratosthenes(int n) // NlogNlogN +{ + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) { - vectorq(n+1,0); - vectorprimes; - for (int i=2; i<=sqrt(n); i++) - { - if (q[i]==1) continue; - int j=i*2; - while (j<=n) - { - q[j]=1; - j+=i; - } - } - for (int i=2; i<=n; i++) + if (q[i]==1) continue; + int j=i*2; + while (j<=n) { - if (q[i]==0) - primes.push_back(i); + q[j]=1; + j+=i; } - return primes; + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); } - + return primes; +} + +class Solution { +public: int findValidSplit(vector& nums) { int K = *max_element(nums.begin(), nums.end()); vectorprimes = Eratosthenes(K); - - unordered_map>Map; + unordered_setSet(primes.begin(), primes.end()); + + unordered_map>Map; + for (int i=0; ix) + if (x==1) break; + if (p * p > x) { if (Map.find(x)==Map.end()) Map[x].first = i; Map[x].second = i; break; } - + if (x%p==0) { if (Map.find(p)==Map.end()) Map[p].first = i; Map[p].second = i; } - while (x%p==0) - { - x/=p; - } + while (x%p==0) x/=p; } } - + int n = nums.size(); - vectordiff(n+1); + vectordiff(n+1); for (auto& [k, v]: Map) { + // cout< Date: Tue, 7 Mar 2023 23:25:08 -0800 Subject: [PATCH 1708/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a8e48513a..3d787e1fb 100644 --- a/Readme.md +++ b/Readme.md @@ -57,7 +57,7 @@ [992.Subarrays-with-K-Different-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/992.Subarrays-with-K-Different-Integers) (H-) [2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K) (M) [2537.Count-the-Number-of-Good-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays) (M+) -* ``Two pointers for two seuqences`` +* ``Two pointers for two sequences`` [986.Interval-List-Intersections](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/986.Interval-List-Intersections) (M) [1229.Meeting-Scheduler](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1229.Meeting-Scheduler) (M+) [1537.Get-the-Maximum-Score](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1537.Get-the-Maximum-Score) (H-) From 5f268ca46a3a8326ed53ffcbbc5022037295d6e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:02:09 -0700 Subject: [PATCH 1709/2729] Create 2588.Count-the-Number-of-Beautiful-Subarrays.cpp --- ...ount-the-Number-of-Beautiful-Subarrays.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays.cpp diff --git a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays.cpp b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays.cpp new file mode 100644 index 000000000..2794ed76c --- /dev/null +++ b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + long long beautifulSubarrays(vector& nums) + { + unordered_mapMap; + Map[0] = 1; + int state = 0; + long long ret = 0; + for (int i=0; i>k)&1) + ((state>>k)&1); + t = t%2; + state = state - (((state>>k)&1)< Date: Sat, 18 Mar 2023 19:02:47 -0700 Subject: [PATCH 1710/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3d787e1fb..4b3742cf6 100644 --- a/Readme.md +++ b/Readme.md @@ -180,6 +180,7 @@ [2025.Maximum-Number-of-Ways-to-Partition-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array) (H) [2488.Count-Subarrays-With-Median-K](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2488.Count-Subarrays-With-Median-K) (H-) [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) +[2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From 5569cf0d132ce23ab98119e6f43314e4a2950cc8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:14:10 -0700 Subject: [PATCH 1711/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md diff --git a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md new file mode 100644 index 000000000..f8a640463 --- /dev/null +++ b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md @@ -0,0 +1,9 @@ +### 2588.Count-the-Number-of-Beautiful-Subarrays + +本题翻译一下,其实就是找符合条件的subarray的数目,使得subarray里面的元素,在每个二进制bit上出现1的次数都是偶数。这样我们每次操作可以消灭一对在某个bit上的1,操作若干次之后会把所有bit上的1都消灭。 + +对于subarray的题目,考虑前缀是一个比较自然的想法。假设某个subarray [a:b]是符合要求的,那么意味着前缀[0:b]在每个bit上出现1的次数的奇偶性,必然与前缀[0:a-1]的奇偶性相同。这样两者一减,必然就有[a:b]的元素在每个二进制bit上出现1的次数是偶数。 + +所以我们遍历b的位置,将[0:b]里每个bit上出现1的次数的奇偶性编码为一个32位的二进制整数state,我们则只需要检查在之前出现的前缀里,这样的编码state出现了几次,就意味着有多少前缀位置可以和b匹配构成一个subarray。 + +特别注意,初始情况下对应编码0,要有初始值`Map[0] = 1`,否则会遗漏以下标0为左端点的subarray。 From 2db38f5c79fda602503be7f054c3d20fb1f8eae1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:16:31 -0700 Subject: [PATCH 1712/2729] Create 2594.Minimum-Time-to-Repair-Cars.cpp --- .../2594.Minimum-Time-to-Repair-Cars.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Binary_Search/2594.Minimum-Time-to-Repair-Cars/2594.Minimum-Time-to-Repair-Cars.cpp diff --git a/Binary_Search/2594.Minimum-Time-to-Repair-Cars/2594.Minimum-Time-to-Repair-Cars.cpp b/Binary_Search/2594.Minimum-Time-to-Repair-Cars/2594.Minimum-Time-to-Repair-Cars.cpp new file mode 100644 index 000000000..cf3e7b734 --- /dev/null +++ b/Binary_Search/2594.Minimum-Time-to-Repair-Cars/2594.Minimum-Time-to-Repair-Cars.cpp @@ -0,0 +1,30 @@ +using LL = long long; +class Solution { +public: + long long repairCars(vector& ranks, int cars) + { + LL left = 0, right = LLONG_MAX; + while (left < right) + { + LL mid = left + (right-left)/2; + if (isOK(mid, ranks, cars)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(LL t, vector& ranks, int cars) + { + LL count = 0; + for (int r : ranks) + { + count += sqrt(t/r); + if (count >= cars) + return true; + } + return false; + + } +}; From 317e38435dd4589f7de07a0c98c6711c46cc2449 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:17:52 -0700 Subject: [PATCH 1713/2729] Create Readme.md --- Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md diff --git a/Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md b/Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md new file mode 100644 index 000000000..72ae59ab1 --- /dev/null +++ b/Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md @@ -0,0 +1,5 @@ +### 2594.Minimum-Time-to-Repair-Cars + +最基本的二分搜值。猜测一个时间t,看看在这个时间内所有人修车数目的总和是否大于等于cars。是的话试图减小t,否则的话试图增加t,直至收敛。 + +对于给定的t,每个人的修车数量就是`sqrt(t/r)`. From 66f39810b28ae2badd98e14582eec837f162647b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:18:19 -0700 Subject: [PATCH 1714/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4b3742cf6..5e1ebf5f8 100644 --- a/Readme.md +++ b/Readme.md @@ -124,6 +124,7 @@ [2528.Maximize-the-Minimum-Powered-City](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2528.Maximize-the-Minimum-Powered-City) (H-) [2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II) (H-) [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) +[2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 1ae5297221d1810a5533cb0f69dadafbd8cbb50a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:23:10 -0700 Subject: [PATCH 1715/2729] Create 2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v1.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp new file mode 100644 index 000000000..93545ec23 --- /dev/null +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int findMinimumTime(vector>& tasks) + { + sort(tasks.begin(), tasks.end(), [](vector&a, vector&b){ + return a[1]time(4005); + for (int i=0; i= d) continue; + int diff = d - count; + for (int j=b; j>=a; j--) + { + if (time[j]==0) + { + time[j] = 1; + diff--; + } + if (diff == 0) break; + } + } + + int ret = 0; + for (int t=0; t<=2000; t++) + ret += (time[t]==1); + return ret; + } +}; From f8f237bd9180b9770434962fd0d6fdc411cee695 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:23:36 -0700 Subject: [PATCH 1716/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5e1ebf5f8..be719dd63 100644 --- a/Readme.md +++ b/Readme.md @@ -1294,6 +1294,7 @@ [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) +[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 330e5c65b91b9e990e6fbd6b0b6219a8c961e0aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:24:22 -0700 Subject: [PATCH 1717/2729] Create 2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v2.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp new file mode 100644 index 000000000..4a42a97af --- /dev/null +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp @@ -0,0 +1,46 @@ +using AI3 = array; +class Solution { +public: + int findMinimumTime(vector>& tasks) + { + sort(tasks.begin(), tasks.end(), + [](vector&a, vector&b){return a[1]arr; + arr.push_back({-2,-1,0}); + + for (int i=0; i 0) + { + if (abs(arr.back()[1] - cur) < diff) + { + diff -= abs(arr.back()[1] - cur); + cur = arr.back()[0] - 1; + arr.pop_back(); + } + else + { + arr.push_back({cur-diff+1, b, arr.back()[2]+b-(cur-diff)}); + diff = 0; + } + } + } + + return arr.back()[2]; + } +}; From 46f4ebe56b12f4401fa6757991189bb904329e55 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 23:01:28 -0700 Subject: [PATCH 1718/2729] Create Readme.md --- .../Readme.md" | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 "LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/Readme.md" diff --git "a/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/Readme.md" "b/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/Readme.md" new file mode 100644 index 000000000..96779102e --- /dev/null +++ "b/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/Readme.md" @@ -0,0 +1,12 @@ +### LCP32.批量处理任务 + +每个任务都有一个最早开始时间。我们将所有tasks按照最早开工时间依次处理并放入任务池中。任务池中的tasks意味着你可以选择开工减少它们的工作量,当然也可以不开工。如果不在池中的tasks则无法做任何操作。 + +对于任务池中的tasks,我们将其按照最晚开工时间保持有序。最晚开工时间的意思是,你必须在这个时刻开工并且直到全部完成其工作量,否则就来不及了。 + +我们令runtime表示当前(已经将部分tasks放入任务池)我们已经(不得不)开工的时长。我们现在需要考虑一个新任务A,准备加入任务池。而此刻任务池中某任务B对应着最早的“最晚开工时间”。此时,如果B的最晚开工时间晚于A的最早开工时间,那么意味着当前没有任何due time,我们不着急开工,可以再拖一拖,可以将A先放入任务池再说。而如果B的最晚开工时间早于A的最早开工时间,意味着B等不及了,我们在将A放入任务池之前必须开工了,那么至少开工多长时间呢?三种情况: +1. 如果当前的runtime已经比B需要的工作时长多。那么说明任务B已经完成了,那么将B从任务池中拿走。 +2. 如果在A的最早开工时间之前就可以把B做完,那么需要再跑:B需要的工作时长减去已经开工的runtime。 +3. 如果在A的最早开工时间之前并不能把B做完,那么需要再跑:A的最早开工时间减去B的最晚开工时间,也就是将时间线拉到A的最早开工时间。 + +然后我们需要将A放入任务池。但是任务池里面的tasks都已经跑过runtime了,A与它们并没有直接的可比性呀。我们做一个处理:假设A的最晚开工时间为t,需要工作时长为d,那么A就等效于任务A',其最晚开工时间为t-runtime,需要工作时长为d+runtime。这样将A'放入任务池后,任务池中的所有任务都可以认为已经跑过了runtime的时间,彼此之间可以放心地按照“最晚开工时间”排序。 From cea58a7bb8f70f85392efef8ccf229f2d546fc14 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 23:01:52 -0700 Subject: [PATCH 1719/2729] Create code.cpp --- .../code.cpp" | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 "LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/code.cpp" diff --git "a/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/code.cpp" "b/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/code.cpp" new file mode 100644 index 000000000..ba2e4c5e4 --- /dev/null +++ "b/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/code.cpp" @@ -0,0 +1,24 @@ +typedef pair PII; +class Solution { +public: + int processTasks(vector>& tasks) + { + int runtime = 0; // the minimum time to run jobs + priority_queue, greater<>>pq; // {latestTimeToStart, duration} + sort(tasks.begin(), tasks.end()); + tasks.push_back({1000000005, 1000000005, 1}); + + for (auto task: tasks) + { + while (!pq.empty() && pq.top().first + runtime < task[0]) + { + if (runtime >= pq.top().second) + pq.pop(); + else + runtime += min(pq.top().second, task[0]-pq.top().first) - runtime; + } + pq.push({task[1]-task[2]+1-runtime, task[2]+runtime}); + } + return runtime; + } +}; From eeea44ce45c8af1464b4864da45d8f612788478d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 23:02:02 -0700 Subject: [PATCH 1720/2729] Delete Readme.md --- LCCUP/2021Spring/Readme.md | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 LCCUP/2021Spring/Readme.md diff --git a/LCCUP/2021Spring/Readme.md b/LCCUP/2021Spring/Readme.md deleted file mode 100644 index 96779102e..000000000 --- a/LCCUP/2021Spring/Readme.md +++ /dev/null @@ -1,12 +0,0 @@ -### LCP32.批量处理任务 - -每个任务都有一个最早开始时间。我们将所有tasks按照最早开工时间依次处理并放入任务池中。任务池中的tasks意味着你可以选择开工减少它们的工作量,当然也可以不开工。如果不在池中的tasks则无法做任何操作。 - -对于任务池中的tasks,我们将其按照最晚开工时间保持有序。最晚开工时间的意思是,你必须在这个时刻开工并且直到全部完成其工作量,否则就来不及了。 - -我们令runtime表示当前(已经将部分tasks放入任务池)我们已经(不得不)开工的时长。我们现在需要考虑一个新任务A,准备加入任务池。而此刻任务池中某任务B对应着最早的“最晚开工时间”。此时,如果B的最晚开工时间晚于A的最早开工时间,那么意味着当前没有任何due time,我们不着急开工,可以再拖一拖,可以将A先放入任务池再说。而如果B的最晚开工时间早于A的最早开工时间,意味着B等不及了,我们在将A放入任务池之前必须开工了,那么至少开工多长时间呢?三种情况: -1. 如果当前的runtime已经比B需要的工作时长多。那么说明任务B已经完成了,那么将B从任务池中拿走。 -2. 如果在A的最早开工时间之前就可以把B做完,那么需要再跑:B需要的工作时长减去已经开工的runtime。 -3. 如果在A的最早开工时间之前并不能把B做完,那么需要再跑:A的最早开工时间减去B的最晚开工时间,也就是将时间线拉到A的最早开工时间。 - -然后我们需要将A放入任务池。但是任务池里面的tasks都已经跑过runtime了,A与它们并没有直接的可比性呀。我们做一个处理:假设A的最晚开工时间为t,需要工作时长为d,那么A就等效于任务A',其最晚开工时间为t-runtime,需要工作时长为d+runtime。这样将A'放入任务池后,任务池中的所有任务都可以认为已经跑过了runtime的时间,彼此之间可以放心地按照“最晚开工时间”排序。 From fd5ab7fc4a6032fc9e2d760ed1821ebb33a5e9ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 23:02:09 -0700 Subject: [PATCH 1721/2729] Delete code.cpp --- LCCUP/2021Spring/code.cpp | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 LCCUP/2021Spring/code.cpp diff --git a/LCCUP/2021Spring/code.cpp b/LCCUP/2021Spring/code.cpp deleted file mode 100644 index ba2e4c5e4..000000000 --- a/LCCUP/2021Spring/code.cpp +++ /dev/null @@ -1,24 +0,0 @@ -typedef pair PII; -class Solution { -public: - int processTasks(vector>& tasks) - { - int runtime = 0; // the minimum time to run jobs - priority_queue, greater<>>pq; // {latestTimeToStart, duration} - sort(tasks.begin(), tasks.end()); - tasks.push_back({1000000005, 1000000005, 1}); - - for (auto task: tasks) - { - while (!pq.empty() && pq.top().first + runtime < task[0]) - { - if (runtime >= pq.top().second) - pq.pop(); - else - runtime += min(pq.top().second, task[0]-pq.top().first) - runtime; - } - pq.push({task[1]-task[2]+1-runtime, task[2]+runtime}); - } - return runtime; - } -}; From 6c9dbfca172072fb0e91f7a548e7912ab61ab331 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 00:41:32 -0700 Subject: [PATCH 1722/2729] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md new file mode 100644 index 000000000..8ea8af45f --- /dev/null +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md @@ -0,0 +1,22 @@ +### 2589.Minimum-Time-to-Complete-All-Tasks + +#### 解法1: +我们将所有任务按照end排序。这是因为end早的任务我们必然先考虑,其它没有到deadline的任务都可以放一放。对于第一个任务,我们必然会尽量拖延它的启动时间,即实际的运作时段是`[end-duration+1, end]`,这样就可以与后面的任务有更多的重合时间。对于第二个任务,必然会充分利用它与第一个任务实际工作的重合部分,假设已经重合的时间不够完成第二个任务,那么我们会在什么时段继续工作呢?其实也是同理,就是卡在第二个任务的deadline之前完成,目的也是为了尽量拖延,增加与后面的任务重合的概率。依此贪心的策略,就可以处理所有的任务。 + +因为本题的数据量不多,任务的个数`n <= 2000`,另外整体的时间跨度也不大`1 <= starti, endi <= 2000`,所以本题可以通过在时间轴上的遍历来暴力解决。比如对于某个任务[start,end,duration],我们先看时间轴上哪些时刻是标记为开工的,与它的重合部分有多长,再与duration比较还得需要多长时间diff才能完成。如果T大于零,那么我们就从end开始往前遍历,将没有在工作的时刻标记为开工,直至把diff都消耗完。 + +这样的时间复杂度是`O(N*T)`。 + +#### 解法2: +上述算法的时间复杂度其实可以不依赖于总时间跨度T。可以想象,如果每个任务的时间跨度都很大,那么遍历时间轴的效率是很低的。上述的算法可以用o(nlogn)来实现。 + +在上述算法里,我们依次处理每个任务的时候,其实都会在时间轴上确定下一段段的实际开工时间,它们是一系列互不重叠的区间。所以我们用arr来盛装这些区间,对于每个区间我们用[a,b,totalTime]表示,a表示起点、b表示终点(都是双闭区间),totalTime表示该区间结束时整个时间轴上已经开工时间的总和,相当于arr里开工区间的长度的前缀和。 + +对于一个新任务[start,end,duration],我们先要计算新区间与已经开工的这些区间有多少重合度`already`。因为有了前缀和的信息,所以这个计算是可行的。我们只需要用二分法,定位start在arr里的位置,找到最后一个早于start的区间interval。如果此interval与新任务完全不重合,那么新任务与已开工的重合度`already`就是interval右边的所有开工区间的长度,这可以用两个前缀和之差得到。如果此interval与新任务有重合部分,那么`already`就是前一种情况的计算结果,再加上此区间与[start,end]的重合部分。 + +我们知道了`duration`和`already`,就可以知道我们还需要从end开始往前填充若干个开工区间之间的间隔,以满足额外的开工长度`diff`,显然这会导致arr最后的几个开工区间合并起来。所以我们就暴力从后往前枚举每个区间[a,b],思路如下: +1. 如果融合了该区间,那么我们新增了多长的开工时间(新增的开工时间其实是该区间与下一个区间之间的间隔长度) +2. 如果新增的开工时间大于diff,那么说明该区间不用被重合,我们只需要计算该区间右端点后的某个位置x,将[x,end]加入arr即可。 +3. 如果新增的开工时间小于diff,那么说明该区间需要被融合,我们将arr的最后一个区间重置为[a,end]. 更新diff后开启下一个循环。 + +最终的总开工时间就是arr里最后一个区间对应的前缀和。 From c8f581ece2d1b1e086b490d1328ea3a5d5959b13 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 10:21:50 -0700 Subject: [PATCH 1723/2729] Update 2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v2.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp index 4a42a97af..8ff969bb3 100644 --- a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp @@ -12,19 +12,18 @@ class Solution { for (int i=0; i 0) { if (abs(arr.back()[1] - cur) < diff) @@ -35,7 +34,7 @@ class Solution { } else { - arr.push_back({cur-diff+1, b, arr.back()[2]+b-(cur-diff)}); + arr.push_back({cur-diff+1, end, arr.back()[2]+end-(cur-diff)}); diff = 0; } } From 7d17ae1d4495d20a6a5f724d99b3a46adfc9349f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 10:22:25 -0700 Subject: [PATCH 1724/2729] Update Readme.md --- Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md index 8ea8af45f..6674d3426 100644 --- a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md @@ -12,9 +12,9 @@ 在上述算法里,我们依次处理每个任务的时候,其实都会在时间轴上确定下一段段的实际开工时间,它们是一系列互不重叠的区间。所以我们用arr来盛装这些区间,对于每个区间我们用[a,b,totalTime]表示,a表示起点、b表示终点(都是双闭区间),totalTime表示该区间结束时整个时间轴上已经开工时间的总和,相当于arr里开工区间的长度的前缀和。 -对于一个新任务[start,end,duration],我们先要计算新区间与已经开工的这些区间有多少重合度`already`。因为有了前缀和的信息,所以这个计算是可行的。我们只需要用二分法,定位start在arr里的位置,找到最后一个早于start的区间interval。如果此interval与新任务完全不重合,那么新任务与已开工的重合度`already`就是interval右边的所有开工区间的长度,这可以用两个前缀和之差得到。如果此interval与新任务有重合部分,那么`already`就是前一种情况的计算结果,再加上此区间与[start,end]的重合部分。 +对于一个新任务[start,end,duration],我们先要计算新区间与已经开工的这些区间有多少重合度`overlap`。因为有了前缀和的信息,所以这个计算是可行的。我们只需要用二分法,定位start在arr里的位置,找到最后一个早于start的区间interval。如果此interval与新任务完全不重合,那么新任务与已开工的重合度`overlap`就是interval右边的所有开工区间的长度,这可以用两个前缀和之差得到。如果此interval与新任务有重合部分,那么`overlap`就是前一种情况的计算结果,再加上此区间与[start,end]的重合部分。 -我们知道了`duration`和`already`,就可以知道我们还需要从end开始往前填充若干个开工区间之间的间隔,以满足额外的开工长度`diff`,显然这会导致arr最后的几个开工区间合并起来。所以我们就暴力从后往前枚举每个区间[a,b],思路如下: +我们知道了`duration`和`overlap`,就可以知道我们还需要从end开始往前填充若干个开工区间之间的间隔,以满足额外的开工长度`diff`,显然这会导致arr最后的几个开工区间合并起来。所以我们就暴力从后往前枚举每个区间[a,b],思路如下: 1. 如果融合了该区间,那么我们新增了多长的开工时间(新增的开工时间其实是该区间与下一个区间之间的间隔长度) 2. 如果新增的开工时间大于diff,那么说明该区间不用被重合,我们只需要计算该区间右端点后的某个位置x,将[x,end]加入arr即可。 3. 如果新增的开工时间小于diff,那么说明该区间需要被融合,我们将arr的最后一个区间重置为[a,end]. 更新diff后开启下一个循环。 From 111a9109c46ce1eed6e73258a1e621b0d82e147b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 10:34:26 -0700 Subject: [PATCH 1725/2729] Create 2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp --- ...t-the-Number-of-Beautiful-Subarrays_v2.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp diff --git a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp new file mode 100644 index 000000000..cf829564e --- /dev/null +++ b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp @@ -0,0 +1,21 @@ +using LL = long long; +class Solution { +public: + long long beautifulSubarrays(vector& nums) + { + unordered_mapMap; + // Map[state] : how many times of state there have been + Map[0] = 1; + + int state = 0; + LL ret = 0; + for (int i=0; i Date: Sun, 19 Mar 2023 10:36:20 -0700 Subject: [PATCH 1726/2729] Update Readme.md --- Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md index f8a640463..4f38290c6 100644 --- a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md +++ b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md @@ -1,5 +1,6 @@ ### 2588.Count-the-Number-of-Beautiful-Subarrays +#### 解法1: 本题翻译一下,其实就是找符合条件的subarray的数目,使得subarray里面的元素,在每个二进制bit上出现1的次数都是偶数。这样我们每次操作可以消灭一对在某个bit上的1,操作若干次之后会把所有bit上的1都消灭。 对于subarray的题目,考虑前缀是一个比较自然的想法。假设某个subarray [a:b]是符合要求的,那么意味着前缀[0:b]在每个bit上出现1的次数的奇偶性,必然与前缀[0:a-1]的奇偶性相同。这样两者一减,必然就有[a:b]的元素在每个二进制bit上出现1的次数是偶数。 @@ -7,3 +8,6 @@ 所以我们遍历b的位置,将[0:b]里每个bit上出现1的次数的奇偶性编码为一个32位的二进制整数state,我们则只需要检查在之前出现的前缀里,这样的编码state出现了几次,就意味着有多少前缀位置可以和b匹配构成一个subarray。 特别注意,初始情况下对应编码0,要有初始值`Map[0] = 1`,否则会遗漏以下标0为左端点的subarray。 + +#### 解法2: +其实我们可以用subarray里面元素的异或和,来表示每个bit上出现1的的次数的奇偶性。与解法1相比可以省略对每个bit的循环操作。 From c84f8343a67f61e09234bc7bafc23c8f1655e696 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 12:52:20 -0700 Subject: [PATCH 1727/2729] Update 2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v2.cpp | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp index 8ff969bb3..58e273662 100644 --- a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp @@ -3,29 +3,30 @@ class Solution { public: int findMinimumTime(vector>& tasks) { - sort(tasks.begin(), tasks.end(), - [](vector&a, vector&b){return a[1]arr; + sort(tasks.begin(), tasks.end(), [](vector&a, vector&b){ + return a[1] < b[1]; + }); + + vectorarr; arr.push_back({-2,-1,0}); - + for (int i=0; i 0) - { + { if (abs(arr.back()[1] - cur) < diff) { diff -= abs(arr.back()[1] - cur); @@ -34,12 +35,12 @@ class Solution { } else { - arr.push_back({cur-diff+1, end, arr.back()[2]+end-(cur-diff)}); + arr.push_back({cur-diff+1, end, arr.back()[2] + end-(cur-diff)}); diff = 0; - } - } + } + } } - + return arr.back()[2]; } }; From 399d233afbc56b1d094b523769ec16f8b979bbb3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 12:52:41 -0700 Subject: [PATCH 1728/2729] Update 2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v1.cpp | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp index 93545ec23..00c0228a7 100644 --- a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp @@ -3,29 +3,31 @@ class Solution { int findMinimumTime(vector>& tasks) { sort(tasks.begin(), tasks.end(), [](vector&a, vector&b){ - return a[1]time(4005); + return a[1] < b[1]; + }); + + vectortime(2005); for (int i=0; i= d) continue; - int diff = d - count; - for (int j=b; j>=a; j--) + int start = tasks[i][0], end = tasks[i][1], duration = tasks[i][2]; + int overlap = 0; + for (int t=start; t<=end; t++) + overlap += (time[t]==1); + + if (overlap >= duration) continue; + int diff = duration - overlap; + for (int t=end; t>=start; t--) { - if (time[j]==0) + if (time[t]==0) { - time[j] = 1; + time[t] = 1; diff--; } - if (diff == 0) break; - } + if (diff == 0) + break; + } } - + int ret = 0; for (int t=0; t<=2000; t++) ret += (time[t]==1); From 256a8b166c2ecfbefdd0209e1a0c89338a230fe6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Mar 2023 00:19:47 -0700 Subject: [PATCH 1729/2729] Create 2591.Distribute-Money-to-Maximum-Children.cpp --- ...1.Distribute-Money-to-Maximum-Children.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Others/2591.Distribute-Money-to-Maximum-Children/2591.Distribute-Money-to-Maximum-Children.cpp diff --git a/Others/2591.Distribute-Money-to-Maximum-Children/2591.Distribute-Money-to-Maximum-Children.cpp b/Others/2591.Distribute-Money-to-Maximum-Children/2591.Distribute-Money-to-Maximum-Children.cpp new file mode 100644 index 000000000..9c76f21bc --- /dev/null +++ b/Others/2591.Distribute-Money-to-Maximum-Children/2591.Distribute-Money-to-Maximum-Children.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int distMoney(int money, int children) + { + if (money < children) return -1; + if (money==4 && children==1) return -1; + if (money > children * 8) return children-1; + + int d = money - children; + int k = d / 7; + int r = d % 7; + + if (r==3 && (children-k)==1) + return k-1; + else + return k; + + } +}; From 0cc1500f214e9a450d64338d7d6e62c6003c01fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Mar 2023 00:27:57 -0700 Subject: [PATCH 1730/2729] Create Readme.md --- Others/2591.Distribute-Money-to-Maximum-Children/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2591.Distribute-Money-to-Maximum-Children/Readme.md diff --git a/Others/2591.Distribute-Money-to-Maximum-Children/Readme.md b/Others/2591.Distribute-Money-to-Maximum-Children/Readme.md new file mode 100644 index 000000000..3e0bb1fee --- /dev/null +++ b/Others/2591.Distribute-Money-to-Maximum-Children/Readme.md @@ -0,0 +1,7 @@ +### 2591.Distribute-Money-to-Maximum-Children + +首先考虑无解的情况。当money Date: Mon, 20 Mar 2023 00:28:32 -0700 Subject: [PATCH 1731/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index be719dd63..20cff8170 100644 --- a/Readme.md +++ b/Readme.md @@ -1359,6 +1359,7 @@ [2359.Find-Closest-Node-to-Given-Two-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2359.Find-Closest-Node-to-Given-Two-Nodes) (M) [2380.Time-Needed-to-Rearrange-a-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2380.Time-Needed-to-Rearrange-a-Binary-String) (H) [2453.Destroy-Sequential-Targets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2453.Destroy-Sequential-Targets) (M) +[2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From f69a25831b41683944f7750414f84bb6ee87d8c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Mar 2023 00:44:45 -0700 Subject: [PATCH 1732/2729] Create 2597.The-Number-of-Beautiful-Subsets.cpp --- .../2597.The-Number-of-Beautiful-Subsets.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp diff --git a/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp new file mode 100644 index 000000000..958416214 --- /dev/null +++ b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int beautifulSubsets(vector& nums, int k) + { + sort(nums.begin(), nums.end()); + return dfs(0, 0, nums, k) - 1; + } + + int dfs(int cur, int state, vector& nums, int k) + { + if (cur==nums.size()) return 1; + + int flag = 1; + for (int i=0; i>i)&1 && nums[i]+k==nums[cur]) + { + flag = 0; + break; + } + } + + int choose = dfs(cur+1, state+(1< Date: Mon, 20 Mar 2023 00:45:24 -0700 Subject: [PATCH 1733/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 20cff8170..db1e11a8f 100644 --- a/Readme.md +++ b/Readme.md @@ -494,6 +494,7 @@ [1681.Minimum-Incompatibility](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1681.Minimum-Incompatibility) (H) [1723.Find-Minimum-Time-to-Finish-All-Jobs](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1723.Find-Minimum-Time-to-Finish-All-Jobs) (H-) [2305.Fair-Distribution-of-Cookies](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2305.Fair-Distribution-of-Cookies) (H-) +[2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (M+) * ``memorization`` [329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix) (M) [2328.Number-of-Increasing-Paths-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2328.Number-of-Increasing-Paths-in-a-Grid) (M) From 96ebf9b13a9654f938bbb4b7cdc049bf2f01b453 Mon Sep 17 00:00:00 2001 From: Yi Yao Date: Fri, 24 Mar 2023 14:14:43 -0500 Subject: [PATCH 1734/2729] Update range_sum_increase_by.cpp Fix the variable names in the constructor for a vector. --- Template/SegmentTree/range_sum_increase_by.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/SegmentTree/range_sum_increase_by.cpp b/Template/SegmentTree/range_sum_increase_by.cpp index 4baf84fdc..86febd552 100644 --- a/Template/SegmentTree/range_sum_increase_by.cpp +++ b/Template/SegmentTree/range_sum_increase_by.cpp @@ -30,8 +30,8 @@ class SegTreeNode SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val { - lazy_tag = 0; - lazy_val = 0; + tag = 0; + delta = 0; start = a, end = b; if (a==b) { From 2b9831904dfb2644c837d2db920da7fb016f4d55 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Mar 2023 14:50:00 -0700 Subject: [PATCH 1735/2729] Create 2597.The-Number-of-Beautiful-Subsets_v2.cpp --- ...597.The-Number-of-Beautiful-Subsets_v2.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets_v2.cpp diff --git a/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets_v2.cpp b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets_v2.cpp new file mode 100644 index 000000000..8f15655eb --- /dev/null +++ b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets_v2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int beautifulSubsets(vector& nums, int k) + { + unordered_mapcount; + for (int x:nums) + count[x]+=1; + + unordered_map>>Map; + for (auto [val,count]:count) + Map[val%k].push_back({val, count}); + + int ret = 1; + for (auto& [r,arr]: Map) + { + sort(arr.begin(), arr.end()); + + int take = 0, notake = 1; + for (int i=0; i Date: Sat, 25 Mar 2023 14:51:03 -0700 Subject: [PATCH 1736/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index db1e11a8f..fff6e9f31 100644 --- a/Readme.md +++ b/Readme.md @@ -682,6 +682,7 @@ * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) +[2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (H) [2320.Count-Number-of-Ways-to-Place-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses) (M+) [1388.Pizza-With-3n-Slices](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1388.Pizza-With-3n-Slices) (H-) [276.Paint-Fence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/276.Paint-Fence) (H-) From 7cb7df1f036d8c5c46eb0b1b7d1ae5bdc02769c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Mar 2023 17:58:38 -0700 Subject: [PATCH 1737/2729] Update 2597.The-Number-of-Beautiful-Subsets.cpp --- .../2597.The-Number-of-Beautiful-Subsets.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp index 958416214..a1fe1ffac 100644 --- a/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp +++ b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp @@ -2,7 +2,6 @@ class Solution { public: int beautifulSubsets(vector& nums, int k) { - sort(nums.begin(), nums.end()); return dfs(0, 0, nums, k) - 1; } @@ -13,7 +12,7 @@ class Solution { int flag = 1; for (int i=0; i>i)&1 && nums[i]+k==nums[cur]) + if ((state>>i)&1 && (nums[i]+k==nums[cur] || nums[i]-k==nums[cur])) { flag = 0; break; From 5042c73f1b123106af38f2c92be18548b74dad64 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Mar 2023 18:10:18 -0700 Subject: [PATCH 1738/2729] Create Readme.md --- .../Readme.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 DFS/2597.The-Number-of-Beautiful-Subsets/Readme.md diff --git a/DFS/2597.The-Number-of-Beautiful-Subsets/Readme.md b/DFS/2597.The-Number-of-Beautiful-Subsets/Readme.md new file mode 100644 index 000000000..090a4bed4 --- /dev/null +++ b/DFS/2597.The-Number-of-Beautiful-Subsets/Readme.md @@ -0,0 +1,24 @@ +### 2597.The-Number-of-Beautiful-Subsets + +#### 解法1: +看到数据规模`nums.size()<=20`,最多2^20种组合数目,意味着暴力枚举即可。一个DFS即可解决。 + +#### 解法2: +本题有o(N)的解法。我们将所有的数字按照对k取模分类。对于位于不同类的数字,彼此之间是否选取都是没有制约关系的。也就是说,假设第一类数字里我们有k1种选法,第一类数字里我们有k2种选法,...,那么最终的答案就是`k1*k2*...`. + +对于同一类的数字,我们将其去重并从小到大排序之后,相邻元素之间的差值必然是k的整数倍。此时的问题转化为:总共有多少种元素的取法,要求相邻元素如果恰好相差k的话不能同时取。这就是典型的house robber问题。我们维护两个变量:take表示假设当前元素被选取的话,有多少种组合方法;notake表示当前元素不被选取的话,有多少种方法。于是 +``` +if (当前元素与前一个元素恰好相差k) +{ + take = notake * 当前元素的个数; + nottake = (take+notake) * 1; +} +else +{ + take = (take+notake) * 当前元素的个数; + nottake = (take+notake) * 1; +} +``` +最终返回`take+notake`就是该类数字里总共合法的组合数目。 + +注意,最终相乘之后的答案要减去“空集”这种情况。 From c20b5438f0e8d12ed073a1e0b29db7b8beb9ad8d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Mar 2023 23:01:06 -0700 Subject: [PATCH 1739/2729] Create 2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp --- ...-Non-negative-Integer-After-Operations.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp diff --git a/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp b/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp new file mode 100644 index 000000000..18ee10bd5 --- /dev/null +++ b/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int findSmallestInteger(vector& nums, int value) + { + vectorcount(value); + + for (int& x: nums) + { + x = ((x%value)+value) % value; + count[x] += 1; + } + + int min_count = INT_MAX; + int k; + + for (int i=0; i Date: Sun, 26 Mar 2023 23:01:30 -0700 Subject: [PATCH 1740/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fff6e9f31..5f19c2f34 100644 --- a/Readme.md +++ b/Readme.md @@ -1206,6 +1206,7 @@ [2546.Apply-Bitwise-Operations-to-Make-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal) (M+) [2551.Put-Marbles-in-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2551.Put-Marbles-in-Bags) (M+) [2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) +[2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From 87d0899e2c4e21478fa084a272a9ab0db8a5d439 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Mar 2023 23:18:05 -0700 Subject: [PATCH 1741/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/Readme.md diff --git a/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/Readme.md b/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/Readme.md new file mode 100644 index 000000000..0d4a1def0 --- /dev/null +++ b/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/Readme.md @@ -0,0 +1,7 @@ +### 2598.Smallest-Missing-Non-negative-Integer-After-Operations + +显然,对一个元素无论做多少次的加减操作,不变的就是对value的余数。于是,我们知道,只要有元素对value的余数是0,我们就可以构造出0来。同理,只要有元素对value的余数是1,我们就可以构造出1来。以此类推,我们可以推出是否能构造出value-1. + +假设以上这些都可以构造出来,那么接下来就考虑能否构造出value来呢?其实只要再来一个能被value整除的元素,我们就可以构造出value来。同理,只要再有一个元素对value的余数是1,那么我们就可以调整它变成value+1,以此类推。 + +所以我们将所有元素以对value的模分类,找到其中的最小频次c以及对应的模r,就意味着我们能构造出c个`[0, value-1]`的完整周期来,也就是能构造出`[0, value*c-1]`的所有整数。接下来再算上零头,我们可以再构造出接下来r个元素。最终未能构造出的MEX就是`value*c+r`. From cb9a348e6e8e59d8189d0ea3264f12ba778ac03d Mon Sep 17 00:00:00 2001 From: zhi-zhi <1164020907@qq.com> Date: Fri, 31 Mar 2023 00:56:01 +0800 Subject: [PATCH 1742/2729] =?UTF-8?q?fix:=20=E6=9B=B4=E6=96=B0=20right+1?= =?UTF-8?q?=20=E8=BE=B9=E7=95=8C=E6=97=B6=EF=BC=8C=E6=9C=AA=E8=80=83?= =?UTF-8?q?=E8=99=91=E6=98=AF=E5=90=A6=E4=BC=9A=E7=A0=B4=E5=9D=8F=E5=8E=9F?= =?UTF-8?q?=20right=20+1=EF=BC=9B=EF=BC=88https://github.com/wisdompeak/Le?= =?UTF-8?q?etCode/issues/88=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../699.Falling-Squares_Heap_v1.cpp | 68 +++++++++---------- .../699.Falling-Squares_Heap_v2.cpp | 56 ++++++++------- 2 files changed, 60 insertions(+), 64 deletions(-) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp index 9522ee658..f1fe39f79 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp @@ -1,44 +1,42 @@ class Solution { public: - vector fallingSquares(vector>& positions) - { - mapMap; - - Map[0]=0; - Map[INT_MAX]=0; - - vectorresults; - int cur=0; - - for (auto p:positions) - { - int left=p.first; - int right=p.first+p.second-1; - int h=p.second; - int maxH=0; - + vector fallingSquares(vector > &positions) { + map Map; + + Map[0] = 0; + Map[INT_MAX] = 0; + + vector results; + int cur = 0; + + for (auto p: positions) { + int left = p[0]; + int right = p[0] + p[1] - 1; + int h = p[1]; + int maxH = 0; + auto ptri = Map.lower_bound(left); auto ptrj = Map.upper_bound(right); - - int temp = prev(ptrj,1)->second; - - auto ptr = ptri->first==left? ptri:prev(ptri,1); - while (ptr!=ptrj) - { - maxH=max(maxH, ptr->second); - ptr = next(ptr,1); + + int temp = prev(ptrj, 1)->second; + + auto ptr = ptri->first == left ? ptri : prev(ptri, 1); + while (ptr != ptrj) { + maxH = max(maxH, ptr->second); + ptr = next(ptr, 1); } - if (ptri!=ptrj) - Map.erase(ptri,ptrj); - - Map[left] = maxH+h; - Map[right+1] = temp; - cur = max(cur, maxH+h); - - results.push_back(cur); + if (ptri != ptrj) + Map.erase(ptri, ptrj); + + Map[left] = maxH + h; + if (right + 1 < ptrj->first) + Map[right + 1] = temp; + cur = max(cur, maxH + h); + + results.push_back(cur); } - + return results; - + } }; diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp index 373f43045..b63837efd 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp @@ -1,39 +1,37 @@ class Solution { public: - vector fallingSquares(vector>& positions) - { - mapMap; - Map[0]=0; - Map[INT_MAX]=0; - int cur=0; - vectorresults; - - for (int i=0; i fallingSquares(vector > &positions) { + map Map; + Map[0] = 0; + Map[INT_MAX] = 0; + int cur = 0; + vector results; + + for (int i = 0; i < positions.size(); i++) { + int left = positions[i][0]; + int len = positions[i][1]; + int right = left + len - 1; + auto pos1 = Map.lower_bound(left); - - int Hmax=0; - auto pos=pos1; - if (pos->first!=left) pos=prev(pos,1); - while (pos->first <= right) - { + + int Hmax = 0; + auto pos = pos1; + if (pos->first != left) pos = prev(pos, 1); + while (pos->first <= right) { Hmax = max(Hmax, pos->second); - pos = next(pos,1); + pos = next(pos, 1); } - int rightHeight = prev(pos,1)->second; - - Map.erase(pos1,pos); - Map[left]=Hmax+len; - Map[right+1]=rightHeight; - - cur = max(cur, Hmax+len); + int rightHeight = prev(pos, 1)->second; + + Map.erase(pos1, pos); + Map[left] = Hmax + len; + if (right + 1 < pos->first) + Map[right + 1] = rightHeight; + + cur = max(cur, Hmax + len); results.push_back(cur); } - + return results; } }; From f81dded46388c089c64130eb558c29e15e8db395 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 15:01:08 -0700 Subject: [PATCH 1743/2729] Create 2603.Collect-Coins-in-a-Tree.cpp --- .../2603.Collect-Coins-in-a-Tree.cpp | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp diff --git a/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp b/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp new file mode 100644 index 000000000..21f187326 --- /dev/null +++ b/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp @@ -0,0 +1,81 @@ +class Solution { + int ret = 0; +public: + int collectTheCoins(vector& coins, vector>& edges) + { + int n = coins.size(); + vector>next(n); + + vectordegree(n); + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].insert(b); + next[b].insert(a); + degree[a]++; + degree[b]++; + } + + vectordeleted(n); + queueq; + for (int i=0; idepth(n, -1); + for (int i=0; i=3); + + if (ret >= 1) + return (ret-1)*2; + else + return 0; + } +}; From 71bf38db58ed724990a7f706b3e1cb8ace13f690 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 15:01:53 -0700 Subject: [PATCH 1744/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5f19c2f34..fd554451d 100644 --- a/Readme.md +++ b/Readme.md @@ -1045,6 +1045,7 @@ [2360.Longest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2360.Longest-Cycle-in-a-Graph) (M+) [2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even) (H-) [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) +[2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 46d55e6fe60360a823a523661548fbefe5e9c795 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 15:22:32 -0700 Subject: [PATCH 1745/2729] Create Readme.md --- Graph/2603.Collect-Coins-in-a-Tree/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Graph/2603.Collect-Coins-in-a-Tree/Readme.md diff --git a/Graph/2603.Collect-Coins-in-a-Tree/Readme.md b/Graph/2603.Collect-Coins-in-a-Tree/Readme.md new file mode 100644 index 000000000..94a316e9a --- /dev/null +++ b/Graph/2603.Collect-Coins-in-a-Tree/Readme.md @@ -0,0 +1,9 @@ +### 2603.Collect-Coins-in-a-Tree + +首先,对于那些处于端点位置的非coin节点、及全部由非coin节点组成支链,我们注定是不会去理会的。所以我们可以第一步进行“剪枝”,用拓扑排序的方法,从度为1的非coin节点开始,一层一层往内圈剥洋葱,将这些多余的分支砍去。剩下的图形,叶子节点必然都是coin;当然也可能存在一些非coin的节点,但它们都位于去往其他coin节点的必经之路上,我们也必须去理会。 + +接下来考虑考虑题目中说,Collect all the coins that are at a distance of at most 2 from the current vertex. 这就意味着我们不必走到每个端点去收集coin,只要走到端点之前两步的位置就可以收集。所以我们可以进一步将这些不用到达的节点都砍去。这里我们同样可以用拓扑排序的方法,从度为1的节点开始,一层一层往内剥洋葱,从小到大来标记每个节点的深度。这里的深度的定义就是,从该点到它的所有的子孙节点里的最大距离。举个例子,假设A->B,A->C->D->E,其中B和E都是端点,那么A的深度就是4. + +通过拓扑排序标记了所有节点从外圈到内圈的深度之后,我们发现,深度大于等于3的节点是我们必须访问的。而深度小于3的节点我们不需要访问,只需要走到深度等于3的节点就能收集到端点处的coin(如果有的话)。假设深度大于等于3的节点的个数有m个,因为这m个点必然是联通的,所以对应有m-1条边。我们注意到,起点和终点必须在同一处,这就意味着无论如何每条边我们必须走两次(一来一回),所以最终的答案就是`2(m-1)`,起点选在这m个节点的任意一个都可。 + +特别注意,如果m等于0,直接返回0. From 967cc549e929013e02e74964d220cab77091ac20 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 15:23:12 -0700 Subject: [PATCH 1746/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fd554451d..941b27a9e 100644 --- a/Readme.md +++ b/Readme.md @@ -565,6 +565,7 @@ [2204.Distance-to-a-Cycle-in-Undirected-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph) (M) [2392.Build-a-Matrix-With-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2392.Build-a-Matrix-With-Conditions) (M+) [2440.Create-Components-With-Same-Value](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2440.Create-Components-With-Same-Value) (H-) +[2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H-) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From df79a5637cfc0b3f23a69f4cb8b4ecf4a018ae0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 18:08:15 -0700 Subject: [PATCH 1747/2729] Update 2603.Collect-Coins-in-a-Tree.cpp --- .../2603.Collect-Coins-in-a-Tree.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp b/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp index 21f187326..67bf720e9 100644 --- a/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp +++ b/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp @@ -29,8 +29,7 @@ class Solution { while (len--) { int cur = q.front(); - q.pop(); - if (deleted[cur]) continue; + q.pop(); deleted[cur] = 1; for (int nxt: next[cur]) { From 7caa207a67d2c528094a2847a89ecf348165a819 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 10:39:19 -0700 Subject: [PATCH 1748/2729] Update Readme.md --- Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md index 6688609f3..0af68beb7 100644 --- a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md +++ b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md @@ -1,6 +1,6 @@ ### 2172.Maximum-AND-Sum-of-Array -本题看上像二分图匹配问题。左边是一堆数字,右边是一对slots,要求匹配的边权之和最大。但是标准的二分图匹配要求每条边不能有公共边,本题则是允许最多两条边共享一个slot节点。 +本题看上像二分图匹配问题。左边是一堆数字,右边是一堆slots,要求匹配的边权之和最大。但是标准的二分图匹配要求每条边不能有公共边,本题则是允许最多两条边共享一个slot节点。 同以往一样,我们不用KM算法来解决带权最大二分图匹配,我们也不考虑最小费用最大流的做法,这里依然用状态压缩DP。 From cf0dd6b6f31c291990429f94bf6a3842372f4c5f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 20:39:37 -0700 Subject: [PATCH 1749/2729] Create 2599.Make-the-Prefix-Sum-Non-negative.cpp --- .../2599.Make-the-Prefix-Sum-Non-negative.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp diff --git a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp new file mode 100644 index 000000000..52d63e36c --- /dev/null +++ b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp @@ -0,0 +1,39 @@ +using LL = long long; +class Solution { +public: + int makePrefSumNonNegative(vector& nums) + { + int ret = 0; + LL sum = 0; + priority_queuepq; + for (int x: nums) + { + if (x>=0) + { + sum +=x; + continue; + } + + if (sum+x < 0) + { + if (!pq.empty() && pq.top() > abs(x)) + { + sum = sum + pq.top() + x; + pq.pop(); + pq.push(abs(x)); + ret++; + } + else + { + ret++; + } + } + else + { + sum +=x; + pq.push(abs(x)); + } + } + return ret; + } +}; From fb18f0daf9cd15819c209b54485b2286aaef0863 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 20:42:34 -0700 Subject: [PATCH 1750/2729] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 941b27a9e..037857b24 100644 --- a/Readme.md +++ b/Readme.md @@ -424,7 +424,6 @@ #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) [373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums) (H-) -[774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [871.Minimum-Number-of-Refueling-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/871.Minimum-Number-of-Refueling-Stops) (H-) [1057.Campus-Bikes](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1057.Campus-Bikes) (H-) [1167.Minimum-Cost-to-Connect-Sticks](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1167.Minimum-Cost-to-Connect-Sticks) (H-) @@ -434,6 +433,10 @@ [1792.Maximum-Average-Pass-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1792.Maximum-Average-Pass-Ratio) (M+) [2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) [2386.Find-the-K-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2386.Find-the-K-Sum-of-an-Array) (H+) +* ``反悔贪心`` +[630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) +[774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) +[2599.Make-the-Prefix-Sum-Non-negative](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative) (H-) * ``Dual PQ`` [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) @@ -443,7 +446,6 @@ * ``Sort+PQ`` [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) -[630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) [857.Minimum-Cost-to-Hire-K-Workers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers) (H) [1353.Maximum-Number-of-Events-That-Can-Be-Attended](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1353.Maximum-Number-of-Events-That-Can-Be-Attended) (H-) [1383.Maximum-Performance-of-a-Team](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1383.Maximum-Performance-of-a-Team) (M+) From 0f9c6c7f99234da497c248bee02860811d4fcefa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 21:08:40 -0700 Subject: [PATCH 1751/2729] Create Readme.md --- .../2599.Make-the-Prefix-Sum-Non-negative/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/Readme.md diff --git a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/Readme.md b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/Readme.md new file mode 100644 index 000000000..0299a2d5d --- /dev/null +++ b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/Readme.md @@ -0,0 +1,13 @@ +### 2599.Make-the-Prefix-Sum-Non-negative + +本题是典型的反悔贪心。 + +我们一路维护前缀和sum。假设遇到当前的元素x,那么分一下几种情况。 + +场景1,如果x是正数,那么无脑收录。 + +场景2,如果x是负数,并且sum+x>=0,那么我们也会贪心地将其收入前缀,从而减少一次扔元素的操作。 + +场景3,就是如果x是负数,且sum+x<0,那么我们别我他法,必须将x扔走。但是将x扔走的同时,能捞一些什么好处呢?假设之前有某个负数y没有被扔走而是收录进了前缀,并且绝对值的y大于x,那么显然将y扔走比将x扔走更合算,并且将y扔走可以保证可以将x顺利保留在前缀里。 + +所以我们需要将场景2里所有收录过的负数,按照绝对值大小放入一个PQ。当遇到场景3的时候,我们将PQ里的最大值代替x去扔掉(如果大于x的话),这样同样用一次操作,可以获取最大的收益(尽可能地提升前缀和)。 From e52f4665221f458c80b0a393ea7f4bee38e8d7e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 21:34:57 -0700 Subject: [PATCH 1752/2729] Create 2604.Minimum-Time-to-Eat-All-Grains.cpp --- .../2604.Minimum-Time-to-Eat-All-Grains.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp diff --git a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp new file mode 100644 index 000000000..7dd72cd54 --- /dev/null +++ b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + int minimumTime(vector& hens, vector& grains) + { + sort(hens.begin(), hens.end()); + sort(grains.begin(), grains.end()); + + int left = 0, right = INT_MAX/2; + while (left < right) + { + int mid = left + (right-left)/2; + if (isOK(mid, hens, grains)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(int time, vector& hens, vector& grains) + { + int j = 0; + for (int i=0; i Date: Sun, 9 Apr 2023 21:35:29 -0700 Subject: [PATCH 1753/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 037857b24..7f5c165f4 100644 --- a/Readme.md +++ b/Readme.md @@ -125,6 +125,7 @@ [2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II) (H-) [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) [2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) +[2604.Minimum-Time-to-Eat-All-Grains](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 39edcabd3f8e9cf2f846e5956e9fbf84fe47142a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 21:51:33 -0700 Subject: [PATCH 1754/2729] Create Readme.md --- .../2604.Minimum-Time-to-Eat-All-Grains/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/Readme.md diff --git a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/Readme.md b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/Readme.md new file mode 100644 index 000000000..e4743371a --- /dev/null +++ b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/Readme.md @@ -0,0 +1,15 @@ +### 2604.Minimum-Time-to-Eat-All-Grains + +直观上我们就会把grains和hens都排序,那么最优解里,从左往右的hens的顺序,必然对应着从左往右grains互不相交的区间。也就是说对于母鸡ay,这不可能是最优解。 + +有了这个发现之后,接下来似乎还是无从下手,那就不妨二分搜值。显然我们会设定一个时间T,看看所有的母鸡能在此时间内把所有谷子都吃完。或者说,是否存在一种谷子区间的分配,能够在T里被各个母鸡吃到。如果可行,那么尝试降低T,否则我们就提高T,最终收敛到最优解。 + +现在考察这个判定函数。因为每个谷子都要被吃,显然我们就从第0号谷子开始考察:它必然是被第0号母鸡吃掉。假设0号谷子在0号母鸡左边,如果两者离得太远(超过了T),那么整体就返回无解。如果在范围内,那么意味着0号母鸡在移动到0号谷子的过程中遇到的所有谷子都能被吃掉。我们记0号母鸡移动到0号谷子的时间是t,那么母鸡在吃完0号谷子还需要返回再花时间t,此时如果还有剩余T-2t,那么就可以往右走,再多吃一点谷子,注意这一段是单程。由此我们可以确定0号母鸡吃的谷子的总数目,假设是j,那么下一个回合我们就考察第j个谷子和第1号母鸡之间的关系,再考察1号母鸡总共能吃几粒谷子,重复这个逻辑。 + +但是注意,在上面的0号母鸡策略中,其实还有另一种方案,就是先往右走,再折返,再往左边走t的时间保证吃掉0号谷子。这也是可行的。哪种方案更好呢?取决于0号母鸡往右边开拓的范围哪个更远。假设方案1比方案2更好,意味着 +``` +T - t*2 > (T-t) / 2 <=> T > 3*t +``` +也就是说,如果`T>3t`,我们就选取方案1,否则就选取方案2. + +由此我们顺次遍历谷子,将一个区间范围内的谷子归入下一个母鸡,在T的约束下确定这个区间范围。直至看能否把所有的谷子都分配完毕。 From cc9a1c29134f5e08147436da2091048d5f2bc44e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Apr 2023 10:33:22 -0700 Subject: [PATCH 1755/2729] Update Readme.md --- Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md b/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md index 7b60669cb..d93c9bf1d 100644 --- a/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md +++ b/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md @@ -9,8 +9,8 @@ 以上方法的两层循环的时间复杂度是o(NK),显然会超时。 #### 解法2:双指针 -对于任何求subarray的问题,我们通常的做法就是固定左边界,探索右边界。假设我们固定左边界是i,那么要使右边界j最远,需要满足[i,j]最多有K个0。 +对于任何求subarray的问题,我们通常的做法就是固定左边界,探索右边界。假设我们固定左边界是i,那么要使右边界j最远,需要满足[i,j]最多有K个0。我们只需要将j单调右移,同时记录中间遇到了几个0即可。 -此时我们考虑左边界是i+1的情况。如果A[i+1]==1,那么此时[i+1,j]内的需要翻转元素的个数count依然是K,然而右边界j依然不能往右突破。我们只有不停地移动i,直到A[i]==0的时候,意味着第i个元素的不被允许翻转,所以区间内的翻转次数count-=1,因此右边界就又可以移动,直到找到下一个A[j]==0为止(此时count再次变为K)。 +综上,我们用for循环遍历左边界i:对于每个i我们记录移动右指针j时经过了几个0,将j停在count为K的最远位置。然后左移一个i并更新count(如果A[i]原本是0的话,我们要吐出一个flip的名额),再接着移动j的位置。 所以两个指针都只会朝一个方向移动。这是快慢类型的双指针,时间复杂度就是o(N). From 51d690a1db7facb5df5f8e4dfbde02ece8723e3f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Apr 2023 10:34:37 -0700 Subject: [PATCH 1756/2729] Update Readme.md --- Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md b/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md index d93c9bf1d..bca68a0ce 100644 --- a/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md +++ b/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md @@ -9,8 +9,8 @@ 以上方法的两层循环的时间复杂度是o(NK),显然会超时。 #### 解法2:双指针 -对于任何求subarray的问题,我们通常的做法就是固定左边界,探索右边界。假设我们固定左边界是i,那么要使右边界j最远,需要满足[i,j]最多有K个0。我们只需要将j单调右移,同时记录中间遇到了几个0即可。 +对于任何求subarray的问题,我们通常的做法就是固定左边界,探索右边界。假设我们固定左边界是`i`,那么要使右边界`j`最远,需要满足[i,j]最多有K个0。我们只需要将`j`单调右移,同时记录中间遇到了几个0即可。 -综上,我们用for循环遍历左边界i:对于每个i我们记录移动右指针j时经过了几个0,将j停在count为K的最远位置。然后左移一个i并更新count(如果A[i]原本是0的话,我们要吐出一个flip的名额),再接着移动j的位置。 +综上,我们用for循环遍历左边界`i`:对于每个`i`我们记录移动右指针`j`,将`j`停在count为K的最远位置。然后左移一个`i`并更新count(如果A[i]原本是0的话,我们要吐出一个flip的名额),再接着移动`j`的位置。 所以两个指针都只会朝一个方向移动。这是快慢类型的双指针,时间复杂度就是o(N). From af912e13f1b041ebb4405986e448c9ad580fc34f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Apr 2023 20:26:45 -0700 Subject: [PATCH 1757/2729] Create 2607.Make-K-Subarray-Sums-Equal_v1.cpp --- .../2607.Make-K-Subarray-Sums-Equal_v1.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp diff --git a/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp new file mode 100644 index 000000000..7a3d9b908 --- /dev/null +++ b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) + { + int n = arr.size(); + LL ret = 0; + vectorvisited(n); + + for (int i=0; inums; + int j = i; + while (visited[j]==0) + { + visited[j] = 1; + nums.push_back(arr[j]); + j = (j+k)%n; + } + ret += helper(nums); + } + return ret; + } + + LL helper(vector&nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + LL ret = 0; + for (int i=0; i Date: Tue, 18 Apr 2023 20:28:27 -0700 Subject: [PATCH 1758/2729] Create 2607.Make-K-Subarray-Sums-Equal_v2.cpp --- .../2607.Make-K-Subarray-Sums-Equal_v2.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v2.cpp diff --git a/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v2.cpp b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v2.cpp new file mode 100644 index 000000000..6207020d0 --- /dev/null +++ b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v2.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) + { + int n = arr.size(); + LL ret = 0; + vectorvisited(n); + int T = gcd(k, n); + + for (int i=0; inums; + int j = i; + while (j&nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + LL ret = 0; + for (int i=0; i Date: Tue, 18 Apr 2023 20:29:04 -0700 Subject: [PATCH 1759/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7f5c165f4..bc353e277 100644 --- a/Readme.md +++ b/Readme.md @@ -1094,6 +1094,7 @@ [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) +[2607.Make-K-Subarray-Sums-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2607.Make-K-Subarray-Sums-Equal) (M+) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) From d50234e2b7df9cca7c9f4787cd4bae22d36b7381 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 10:11:07 -0700 Subject: [PATCH 1760/2729] Create Readme.md --- Math/2607.Make-K-Subarray-Sums-Equal/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Math/2607.Make-K-Subarray-Sums-Equal/Readme.md diff --git a/Math/2607.Make-K-Subarray-Sums-Equal/Readme.md b/Math/2607.Make-K-Subarray-Sums-Equal/Readme.md new file mode 100644 index 000000000..b5d837821 --- /dev/null +++ b/Math/2607.Make-K-Subarray-Sums-Equal/Readme.md @@ -0,0 +1,7 @@ +### 2607.Make-K-Subarray-Sums-Equal + +首先,要使得`the sum of each subarray of length k is equal`,说明`sum[0:k-1] = sum[1:k]`,马上可知`nums[0]=nums[k]`,同理推得间隔k的元素都相等`nums[i]=nums[i+k]`。根据这个规则,我们可以将必须相等的元素归为一组。具体的说,我们从0开始,那么`0,k,2k,3k,...`分在一组,`1,1+k,1+2k,1+3k,...`分在一组,以此类推。 + +注意到数组是循环的,所以我们可以需要将数组遍历若干圈之后才能将属于同一组的元素都穷举完。比如n=10, k=4的时候,`0,4,8,2,6`属于同一组。 + +将所有的元素都分组完毕之后,为了将组内元素都搞成同一个值,显然最优解就是统一成该组里的中位数m,可以保证`sum|xi-m|`最小。 From e3dca646118e06df759293b508b0fdc461550cbf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 19:25:22 -0700 Subject: [PATCH 1761/2729] Update 2607.Make-K-Subarray-Sums-Equal_v1.cpp --- .../2607.Make-K-Subarray-Sums-Equal_v1.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp index 7a3d9b908..749347c81 100644 --- a/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp +++ b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp @@ -9,7 +9,6 @@ class Solution { for (int i=0; inums; int j = i; while (visited[j]==0) From baeec35b33919762a6d1ad1bd1477eb4b749861d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 19:48:45 -0700 Subject: [PATCH 1762/2729] Create 2642.Design-Graph-With-Shortest-Path-Calculator.cpp --- ...gn-Graph-With-Shortest-Path-Calculator.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Graph/2642.Design-Graph-With-Shortest-Path-Calculator/2642.Design-Graph-With-Shortest-Path-Calculator.cpp diff --git a/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/2642.Design-Graph-With-Shortest-Path-Calculator.cpp b/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/2642.Design-Graph-With-Shortest-Path-Calculator.cpp new file mode 100644 index 000000000..04cfb1a13 --- /dev/null +++ b/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/2642.Design-Graph-With-Shortest-Path-Calculator.cpp @@ -0,0 +1,44 @@ +class Graph { + int n; + int dp[100][100]; +public: + Graph(int n, vector>& edges) { + this->n = n; + for (int i=0; i edge) + { + int a = edge[0], b = edge[1]; + for (int i=0; iaddEdge(edge); + * int param_2 = obj->shortestPath(node1,node2); + */ From 3f69c1ea780055ba4b2a21ee1904b547fc7c0c14 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 19:50:50 -0700 Subject: [PATCH 1763/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bc353e277..8233f945c 100644 --- a/Readme.md +++ b/Readme.md @@ -1050,6 +1050,7 @@ [2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even) (H-) [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) +[2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 8ab9c914c5cf48ed9c4ed61d6952470a70a95542 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 21:09:16 -0700 Subject: [PATCH 1764/2729] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Graph/2642.Design-Graph-With-Shortest-Path-Calculator/Readme.md diff --git a/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/Readme.md b/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/Readme.md new file mode 100644 index 000000000..a82e45572 --- /dev/null +++ b/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/Readme.md @@ -0,0 +1,17 @@ +### 2642.Design-Graph-With-Shortest-Path-Calculator + +根据题意,我们要时刻准备返回任意两点之间的最短路径,因此Dijkstra算法是不行的。除此之外,想求任意两点之间的最短路径,最经典的算法就是Floyd算法了,而o(N^3)的时间复杂度也是可以接受的。所以我们用Floyd预处理这个图,代码非常优雅 +```cpp + for (int k = 0; k < n; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][j]); + } + } + } +``` +特别注意k必须放在最外层。从形式上看,本质上这就是一个动态规划。 + +当我们新增一条从a->b的edge时,会对已有网络的最短路径产生什么影响呢?很显然,dp[i][j]无非就两种情况:经过edge,不经过edge。对于前者,我们只需要考察`dp[i][a]+edge+dp[b][j]`;对于后者,依然还是`dp[i][j]`。两者取小,就是更新后的dp[i][j].所以我们能用N^2的时间更新所有的`dp[i][j]`,这也是符合数据量的。 + +综上,我们可以实时输出`dp[i][j]`表示两点之间的最短距离。 From f3a4f3bbe3e9dc5a75e94ff9277663e54431e23c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 21:27:09 -0700 Subject: [PATCH 1765/2729] Create 2608.Shortest-Cycle-in-a-Graph.cpp --- .../2608.Shortest-Cycle-in-a-Graph.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Graph/2608.Shortest-Cycle-in-a-Graph/2608.Shortest-Cycle-in-a-Graph.cpp diff --git a/Graph/2608.Shortest-Cycle-in-a-Graph/2608.Shortest-Cycle-in-a-Graph.cpp b/Graph/2608.Shortest-Cycle-in-a-Graph/2608.Shortest-Cycle-in-a-Graph.cpp new file mode 100644 index 000000000..4bffafa3c --- /dev/null +++ b/Graph/2608.Shortest-Cycle-in-a-Graph/2608.Shortest-Cycle-in-a-Graph.cpp @@ -0,0 +1,57 @@ +class Solution { + unordered_setnext[1005]; + int n; +public: + int findShortestCycle(int n, vector>& edges) + { + this->n = n; + for (auto&edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].insert(b); + next[b].insert(a); + } + + int ret = INT_MAX; + for (auto&edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].erase(b); + next[b].erase(a); + ret = min(ret, BFS(a,b)); + next[a].insert(b); + next[b].insert(a); + } + + if (ret==INT_MAX) return -1; + return ret+1; + } + + int BFS(int start, int end) + { + vectorvisited(n); + queueq; + q.push(start); + visited[start] = 1; + + int step = 0; + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + int cur = q.front(); + q.pop(); + if (cur==end) return step; + for (int nxt: next[cur]) + { + if (visited[nxt]) continue; + q.push(nxt); + visited[nxt] = 1; + } + } + step++; + } + return INT_MAX; + } +}; From 4bb04518afae584c721a940801407cc17badba1d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 21:27:35 -0700 Subject: [PATCH 1766/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8233f945c..d97ced7ea 100644 --- a/Readme.md +++ b/Readme.md @@ -1050,6 +1050,7 @@ [2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even) (H-) [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) +[2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) From c499fd94f2994642d0771b9acdd6e016fe33a060 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 21:28:49 -0700 Subject: [PATCH 1767/2729] Create Readme.md --- Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md diff --git a/Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md b/Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md new file mode 100644 index 000000000..5ed018960 --- /dev/null +++ b/Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md @@ -0,0 +1,3 @@ +### 2608.Shortest-Cycle-in-a-Graph + +这是图论里的经典问题。解法非常简单,就是遍历所有的边`a-b`。查看如果将该边断开,从a到b的最短距离d,那么d+1就是就包含d的最短环。然后取全局的最小值即可。 From 9c7889cbb4bd136c9d21a3643ceb386d4d4a7dc7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Apr 2023 15:59:40 -0700 Subject: [PATCH 1768/2729] Create 2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp --- ...imum-Number-of-Visited-Cells-in-a-Grid.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp diff --git a/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp new file mode 100644 index 000000000..8ac4d976f --- /dev/null +++ b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp @@ -0,0 +1,52 @@ +using PII = pair; +class Solution { +public: + int minimumVisitedCells(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + + vector>dp(m, vector(n,INT_MAX/2)); + vector, greater<>>> row_diff(m); + vector, greater<>>> col_diff(n); + vector>row(m); + vector>col(n); + + for (int i=0; i0) row[i].insert(x); + else row[i].erase(row[i].find(-x)); + row_diff[i].pop(); + } + while (!col_diff[j].empty() && col_diff[j].top().first == i) + { + int x = col_diff[j].top().second; + if (x>0) col[j].insert(x); + else col[j].erase(col[j].find(-x)); + col_diff[j].pop(); + } + int min_val = INT_MAX/2; + if (!row[i].empty()) min_val = min(min_val, *row[i].begin()); + if (!col[j].empty()) min_val = min(min_val, *col[j].begin()); + dp[i][j] = min_val; + if (i==0 && j==0) dp[i][j] = 1; + // cout<<"dp "< Date: Sat, 22 Apr 2023 16:01:08 -0700 Subject: [PATCH 1769/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d97ced7ea..053545b77 100644 --- a/Readme.md +++ b/Readme.md @@ -1408,7 +1408,8 @@ [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) [2327.Number-of-People-Aware-of-a-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Others/2327.Number-of-People-Aware-of-a-Secret) (H-) [2381.Shifting-Letters-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/2381.Shifting-Letters-II) (M) -[2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) +[2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) +[2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From b47c4a09ec2dfad1e5540e24cf828d0d52e978ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Apr 2023 16:36:26 -0700 Subject: [PATCH 1770/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/Readme.md diff --git a/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/Readme.md b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/Readme.md new file mode 100644 index 000000000..11245bec5 --- /dev/null +++ b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/Readme.md @@ -0,0 +1,15 @@ +### 2617.Minimum-Number-of-Visited-Cells-in-a-Grid + +按照正常的DP思路,我们令dp[i][j]表示到达(i,j)的最短时间。当更新dp[i][j]的时候,我们发现它的前驱状态会有很多,包括同行里左边的若干格子(不一定相连),同列上面的若干格子(不一定相连)。我们发现遍历这些前驱状态最多需要花费o(m)和o(n)的时间,再配上遍历全体的o(mn),时间复杂度是超的。 + +我们换个DP的角度,如果已知dp[i][j],那么我们可以更新未来的一些状态,包括同行右边的若干格子(一定相连),以及同列下边的若干格子(一定相连)。但是同理,这也是`o(m)*o(mn)`的时间复杂度。但是我们发现从这个角度考虑的话,你可以更新的格子是一个连续的subarray。举个例子,如果dp[i][j]=4,grid[i][j]=3,那么意味着(i,j+1)到(i,j+3)这三个格子的dp都可以更新到5,此外(i+1,j)到(i+3,j)这三个格子的dp也都可以更新到5. 我们立马就想到了差分数组的性质,可以避免将整个区间的元素逐个更新,只需要对这个连续区间的首尾进行标记即可。 + +具体的步骤是:我们首先给每一行和每一列配一个“差分点”的优先队列。按照上面的例子,假设我们得到`dp[i][j]=4`,且`grid[i][j]=step`, 那么意味着优先队列row_diff[i]里需要添加两个差分点,分别是`{j+1, 5}`和`{j+step+1, -5}`,表示第i行从第j列开始的格子,dp值可以是5,但是从第i行第j+step+1列开始的格子,dp值不能再有5. 同理,我们对于另一个优先队列col_diff[j]也添加类似的差分点,分别是`{i+1, 5}`和`{i+step+1, -5}`. + +以上讲的是已知dp[i][j],如何更新row_diff[i]与col_diff[j]。那么我们如何计算dp[i][j]呢?我们同样需要给每一行和每一列配一个multiset,表示当前可以选取的dp值,但是显然我们只会挑最小的。举个例子,当我们遍历到(i,j)点时,有序集合row[i]会从row_diff[i]里看是否在(i,j)有差分点,有的话就从row[i]里加入或者减去相应的dp值。同理,另一个有序集合col[j]会从col_diff[j]里看是否在(i,j)有差分点,有的话就从col[j]里加入或者减去相应的dp值。最终dp[i][j]必然是在row[i]和col[j]里里面挑最小的元素(即在一堆可选的dp值里挑最小的)。 + +综上,我们对每个(i,j),先从从row_diff[i]和col_diff[j]读入差分点,更新row[i]和col[j],然后选最小值得到dp[i][j],然后往row_diff[i]和col_diff[j]再加入后续的差分点。 + +最终的答案就是dp[m-1][n-1]. + +类型的思路可以借鉴2158,2218,253。 From 0565c4f4abc721c588a811fd85fd161f3c25c816 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 10:24:26 -0700 Subject: [PATCH 1771/2729] Update 2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp --- ...imum-Number-of-Visited-Cells-in-a-Grid.cpp | 49 +++++++++---------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp index 8ac4d976f..9d642b538 100644 --- a/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp +++ b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp @@ -1,52 +1,51 @@ -using PII = pair; -class Solution { +using PII = pair; // {pos, val} +class Solution { public: int minimumVisitedCells(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - - vector>dp(m, vector(n,INT_MAX/2)); + int m = grid.size(), n = grid[0].size(); + + vector>dp(m, vector(n, INT_MAX/2)); vector, greater<>>> row_diff(m); vector, greater<>>> col_diff(n); - vector>row(m); - vector>col(n); - + vector>row_set(m); + vector>col_set(n); + for (int i=0; i0) row[i].insert(x); - else row[i].erase(row[i].find(-x)); - row_diff[i].pop(); + row_diff[i].pop(); + if (x>0) row_set[i].insert(x); + if (x<0) row_set[i].erase(row_set[i].find(-x)); } while (!col_diff[j].empty() && col_diff[j].top().first == i) { int x = col_diff[j].top().second; - if (x>0) col[j].insert(x); - else col[j].erase(col[j].find(-x)); - col_diff[j].pop(); + col_diff[j].pop(); + if (x>0) col_set[j].insert(x); + if (x<0) col_set[j].erase(col_set[j].find(-x)); } + int min_val = INT_MAX/2; - if (!row[i].empty()) min_val = min(min_val, *row[i].begin()); - if (!col[j].empty()) min_val = min(min_val, *col[j].begin()); + if (!row_set[i].empty()) min_val = min(min_val, *row_set[i].begin()); + if (!col_set[j].empty()) min_val = min(min_val, *col_set[j].begin()); dp[i][j] = min_val; - if (i==0 && j==0) dp[i][j] = 1; - // cout<<"dp "< Date: Sun, 23 Apr 2023 10:25:15 -0700 Subject: [PATCH 1772/2729] Create 2616.Minimize-the-Maximum-Difference-of-Pairs.cpp --- ...nimize-the-Maximum-Difference-of-Pairs.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp diff --git a/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp new file mode 100644 index 000000000..06a39fcea --- /dev/null +++ b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minimizeMax(vector& nums, int p) + { + sort(nums.begin(), nums.end()); + int left = 0, right = INT_MAX; + while (left < right) + { + int mid = left + (right-left)/2; + if (isOK(nums, p, mid)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(vector& nums, int p, int diff) + { + int n = nums.size(); + int count = 0; + for (int i=0; i= p); + } +}; From b25bb374d1915b82f0649c740639676030363f8f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 10:25:44 -0700 Subject: [PATCH 1773/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 053545b77..645c2f2d9 100644 --- a/Readme.md +++ b/Readme.md @@ -126,6 +126,7 @@ [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) [2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) [2604.Minimum-Time-to-Eat-All-Grains](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains) (H-) +[2616.Minimize-the-Maximum-Difference-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 77d2b8535f838172aba1266784ad6fe67b085198 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 14:39:01 -0700 Subject: [PATCH 1774/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/Readme.md diff --git a/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/Readme.md b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/Readme.md new file mode 100644 index 000000000..34fc49dd2 --- /dev/null +++ b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/Readme.md @@ -0,0 +1,7 @@ +### 2616.Minimize-the-Maximum-Difference-of-Pairs + +我们首先容易想到的是将数组排序,这样我们选择的pairs必然都是相邻的元素。任何跳跃选择的pair都必然不会是最优解。接下来我们该如何选择这些pairs呢?此时陷入了困难。我们并不能贪心地找相邻最短的pair,比如这个例子:`1 3 4 6`,我们优先取{3,4}之后,剩下的{1,6}的差距更大了。 + +在正面突破没有思路的时候,不妨试一试反向的“猜答案”。二分搜值在这里恰好是适用的。假设最大间距是x,那么当x越大时,我们就越容易找p对符合条件的pairs(比如当x是无穷大时,pairs可以随意挑);反之当x越小时,就越不容易找到p对符合条件的pairs。以此不断调整x的大小,直至收敛。 + +于是接下来我们就考虑,假设最大间距是x,那么我们如何判定能否找到p对符合条件的pairs呢?为了尽量找到多的pairs,我们必然从小到大把这些元素都看一遍,尽量不浪费。假设最小的四个元素分别是abcd,并且他们彼此之间的间距都小于x,那么我们是否应该取a和b呢?如果取的话,那么可能带来的顾虑就是b就失去了和c配对的机会。不过这个顾虑是不必要的:如果我们选择了b和c,那么同样构造了一对,但a就白白浪费了。即使你可以将a与d配对且间距也小于x,那么也违背了我们之前的直觉,“我们永远只会取相邻的元素配对”。事实上(a,b)(c,d)的方案肯定是优于(b,c)(a,d)的。所以我们的结论就是,如果最小元素和它相邻元素的间距小于x,那么就贪心地配对;否则最小元素只能放弃。依次类推从小到大处理每一个元素,就可以知道我们最多能搞出多少个配对。 From 430c24657b22b2643d19663c8e8aa3e063d0f881 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 14:47:44 -0700 Subject: [PATCH 1775/2729] Update 2616.Minimize-the-Maximum-Difference-of-Pairs.cpp --- ...Minimize-the-Maximum-Difference-of-Pairs.cpp | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp index 06a39fcea..17fb3e7ba 100644 --- a/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp +++ b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp @@ -20,17 +20,12 @@ class Solution { int n = nums.size(); int count = 0; for (int i=0; i= p); } From 922dd07c44fcf4d9c0735eaa9e8044d367cba8fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 15:17:51 -0700 Subject: [PATCH 1776/2729] Create 2615.Sum-of-Distances.cpp --- .../2615.Sum-of-Distances.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp diff --git a/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp b/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp new file mode 100644 index 000000000..ad7c6abdd --- /dev/null +++ b/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { +public: + vector distance(vector& nums) + { + int n = nums.size(); + unordered_map>Map; + for (int i=0; ians; + unordered_mapidx; + for (auto& [k,v]: Map) + { + idx[k] = 0; + LL sum = 0; + for (int p: v) + sum += abs(p - v[0]); + ans[k] = sum; + } + + + vectorrets; + for (int x: nums) + { + rets.push_back(ans[x]); + int i = idx[x]; + if (i==Map[x].size()-1) continue; + LL temp = ans[x]; + int m = Map[x].size(); + temp += (Map[x][i+1]-Map[x][i])*(i+1); + temp -= (Map[x][i+1]-Map[x][i])*(m-1-i); + ans[x] = temp; + idx[x] = i+1; + } + + return rets; + + } +}; From 0a5597b8a0dc97c194395b6b2ec2e8d1005f5c92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 15:18:24 -0700 Subject: [PATCH 1777/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 645c2f2d9..742d3b48e 100644 --- a/Readme.md +++ b/Readme.md @@ -1375,6 +1375,7 @@ * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) +[2615.Sum-of-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Others/2615.Sum-of-Distances) (M+) * ``Count Subarray by Element`` [828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) From 3e5fb9ff589f452fe7d8a4192f18954a11a69aaa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 15:22:46 -0700 Subject: [PATCH 1778/2729] Update 2604.Minimum-Time-to-Eat-All-Grains.cpp --- .../2604.Minimum-Time-to-Eat-All-Grains.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp index 7dd72cd54..d7dbce343 100644 --- a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp +++ b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp @@ -22,12 +22,16 @@ class Solution { int j = 0; for (int i=0; i Date: Sun, 23 Apr 2023 15:54:46 -0700 Subject: [PATCH 1779/2729] Create 2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp --- ...-to-Make-All-Array-Elements-Equal-to-1.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp diff --git a/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp b/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp new file mode 100644 index 000000000..84af054b8 --- /dev/null +++ b/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minOperations(vector& nums) + { + int n = nums.size(); + int g = nums[0]; + for (int i=0; i 0) + return (n - count); + + count = n; + for (int i=0; i Date: Sun, 23 Apr 2023 15:55:12 -0700 Subject: [PATCH 1780/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 742d3b48e..47bb683d6 100644 --- a/Readme.md +++ b/Readme.md @@ -1144,6 +1144,7 @@ [2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) [2344.Minimum-Deletions-to-Make-Array-Divisible](https://github.com/wisdompeak/LeetCode/tree/master/Math/2344.Minimum-Deletions-to-Make-Array-Divisible) (E) [2543.Check-if-Point-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Math/2543.Check-if-Point-Is-Reachable) (H) +[2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) From 9338482d6c8247357f5419530b0a9c2bad78dce3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 16:04:15 -0700 Subject: [PATCH 1781/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/Readme.md diff --git a/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/Readme.md b/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/Readme.md new file mode 100644 index 000000000..60ed4de75 --- /dev/null +++ b/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/Readme.md @@ -0,0 +1,9 @@ +### 2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1 + +我们发现,只有出现两个元素互质的时候,才能搞出一个1。只要搞出一个1,那么它与相邻元素结合,之后每一个回合就都能再搞出一个1,而且是最高效的变换。 + +所以,如果所有元素的最大公约数不是1,那么永远无法约出1来,那么就无解。 + +其次,如果已经有元素有1,那么如上所说,每个会和,都可以把一个非1元素变换成1. 所以答案就是`n - m`,其中m是原数组里1的个数。 + +最后,我们思考如何尽快地搞出1来。这就需要将一段相邻的元素取gcd,公约数越来越小,直至变成1. 于是本题就转化为,求最短的区间,区间元素的gcd是1. 考虑到整个元素的个数不超过50,那么暴力遍历所有subarray即可。找到了这样的最短区间len,说明经过`len-1`次变化就可以搞出第一个1,那么接下来经过`n-1`变化就可以把所有的非1元素搞定。 From 41dd845b1b06565916d74a806e45870fa902eb58 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 17:50:22 -0700 Subject: [PATCH 1782/2729] Create 2653.Sliding-Subarray-Beauty.cpp --- .../2653.Sliding-Subarray-Beauty.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp diff --git a/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp b/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp new file mode 100644 index 000000000..58905c1a3 --- /dev/null +++ b/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + vector getSubarrayBeauty(vector& nums, int k, int x) + { + multisetSet1; + multisetSet2; + vectorrets; + int count_neg = 0; + for (int i=0; i nums[i]) + { + Set1.erase(Set1.find(v)); + Set2.insert(v); + Set1.insert(nums[i]); + } + else + { + Set2.insert(nums[i]); + } + } + + if (i>=k-1) + { + int v = *Set1.rbegin(); + rets.push_back(min(v, 0)); + } + + if (i>=k-1) + { + int v = nums[i-k+1]; + auto iter = Set2.find(v); + if (iter!=Set2.end()) + Set2.erase(iter); + else + { + Set1.erase(Set1.find(v)); + if (!Set2.empty()) + { + Set1.insert(*Set2.begin()); + Set2.erase(Set2.begin()); + } + } + } + } + + return rets; + + } +}; From cc0b9cb72c63865c77b489f991a4ecce8f49bf26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 17:51:16 -0700 Subject: [PATCH 1783/2729] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 47bb683d6..f5f3fb925 100644 --- a/Readme.md +++ b/Readme.md @@ -208,6 +208,7 @@ 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) @@ -444,7 +445,8 @@ [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) -[2402.Meeting-Rooms-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2402.Meeting-Rooms-III) (M+) +[2402.Meeting-Rooms-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2402.Meeting-Rooms-III) (M+) +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) * ``Sort+PQ`` [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) From c5c50c7f698df81c652adeb3ded870a059087b59 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 17:54:53 -0700 Subject: [PATCH 1784/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index f5f3fb925..30c6d3f7a 100644 --- a/Readme.md +++ b/Readme.md @@ -207,12 +207,12 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) -[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) [2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) +[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From 58d68acadadcc39edc764be537811978f771c5f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 18:11:16 -0700 Subject: [PATCH 1785/2729] Create Readme.md --- Heap/2653.Sliding-Subarray-Beauty/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Heap/2653.Sliding-Subarray-Beauty/Readme.md diff --git a/Heap/2653.Sliding-Subarray-Beauty/Readme.md b/Heap/2653.Sliding-Subarray-Beauty/Readme.md new file mode 100644 index 000000000..f9ee488d0 --- /dev/null +++ b/Heap/2653.Sliding-Subarray-Beauty/Readme.md @@ -0,0 +1,8 @@ +### 2653.Sliding-Subarray-Beauty + +本题如果利用`-50 <= nums[i] <= 50`的条件,那么可以变得很容易。在这里我们只讲更一般的解法。 + +和`Dual PQ`的思路一样,设计两个有序容器,分别是装“最小的x的元素”Set1,和“剩余的元素”Set2。对于新元素nums[i],我们需要操作的步骤是: +1. 判断应该将nums[i]放入Set1还是Set2. 如果比Set1的最大元素还大,就放入Set2;否则就将Set1的最大元素转移到Set2,并将nums[i]放入Set1。 +2. 如果i>=x-1,输出Set1里的最大元素作为答案。 +3. 将nums[i-x+1]从集合中移除。需要判断nums[i-x+1]此时在Set1里还是Set2里。如果是前者的话,需要将Set2里的元素转移一个过去, From a867e53b43eea17e614ae1d62c5ce1aa821fd081 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 21:15:17 -0700 Subject: [PATCH 1786/2729] Update 2653.Sliding-Subarray-Beauty.cpp --- .../2653.Sliding-Subarray-Beauty.cpp | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp b/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp index 58905c1a3..a30b6f08d 100644 --- a/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp +++ b/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp @@ -5,7 +5,7 @@ class Solution { multisetSet1; multisetSet2; vectorrets; - int count_neg = 0; + for (int i=0; i=k-1) + + if (Set1.size() + Set2.size() == k) { int v = *Set1.rbegin(); rets.push_back(min(v, 0)); - } - + } + if (i>=k-1) { int v = nums[i-k+1]; auto iter = Set2.find(v); - if (iter!=Set2.end()) + if (iter!=Set2.end()) Set2.erase(iter); else { @@ -44,12 +44,11 @@ class Solution { { Set1.insert(*Set2.begin()); Set2.erase(Set2.begin()); - } + } } - } + } } - + return rets; - } }; From fb611cf9d3b64a02448ef95db5d8341e91abfda0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 22:23:02 -0700 Subject: [PATCH 1787/2729] Update 2599.Make-the-Prefix-Sum-Non-negative.cpp --- .../2599.Make-the-Prefix-Sum-Non-negative.cpp | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp index 52d63e36c..8a544602c 100644 --- a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp +++ b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp @@ -11,28 +11,22 @@ class Solution { if (x>=0) { sum +=x; - continue; } - - if (sum+x < 0) + else if (sum + x >= 0) + { + sum +=x; + pq.push(abs(x)); + } + else { if (!pq.empty() && pq.top() > abs(x)) { - sum = sum + pq.top() + x; + sum = sum + x + pq.top() ; pq.pop(); pq.push(abs(x)); - ret++; } - else - { - ret++; - } + ret++; } - else - { - sum +=x; - pq.push(abs(x)); - } } return ret; } From 804332f34f32cc096dd27b156124812175294ba6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 22:38:46 -0700 Subject: [PATCH 1788/2729] Update 2599.Make-the-Prefix-Sum-Non-negative.cpp --- .../2599.Make-the-Prefix-Sum-Non-negative.cpp | 31 +++++++++---------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp index 8a544602c..ffeb7dd93 100644 --- a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp +++ b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp @@ -1,33 +1,30 @@ -using LL = long long; class Solution { public: int makePrefSumNonNegative(vector& nums) { + priority_queuepq; + long long sum = 0; int ret = 0; - LL sum = 0; - priority_queuepq; + for (int x: nums) { - if (x>=0) + if (x >= 0) + sum += x; + else if (sum + x >=0) { - sum +=x; - } - else if (sum + x >= 0) - { - sum +=x; + sum += x; pq.push(abs(x)); } - else + else { - if (!pq.empty() && pq.top() > abs(x)) - { - sum = sum + x + pq.top() ; - pq.pop(); - pq.push(abs(x)); - } + pq.push(abs(x)); + sum += x; + int y = pq.top(); + pq.pop(); + sum += y; ret++; } } - return ret; + return ret; } }; From 0c7e1e62def0f74d59cddb7bfe3ff8862d21c90c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 23:37:25 -0700 Subject: [PATCH 1789/2729] Create 2638.Count-the-Number-of-K-Free-Subsets.cpp --- ...638.Count-the-Number-of-K-Free-Subsets.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/2638.Count-the-Number-of-K-Free-Subsets.cpp diff --git a/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/2638.Count-the-Number-of-K-Free-Subsets.cpp b/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/2638.Count-the-Number-of-K-Free-Subsets.cpp new file mode 100644 index 000000000..368b6575f --- /dev/null +++ b/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/2638.Count-the-Number-of-K-Free-Subsets.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + long long countTheNumOfKFreeSubsets(vector& nums, int k) + { + vector>arr(k); + for (int x: nums) + arr[x%k].push_back(x); + + long long ret = 1; + for (int i=0; i& nums, int k) + { + sort(nums.begin(), nums.end()); + long long take = 0, no_take = 1; + for (int i=0; i=1 && nums[i] == nums[i-1]+k) + { + take = no_take_temp; + no_take = take_temp + no_take_temp; + } + else + { + take = take_temp + no_take_temp; + no_take = take_temp + no_take_temp; + } + } + return take + no_take; + } +}; From c80af47c360264fae982b26655ee949a703a1c8e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 23:38:24 -0700 Subject: [PATCH 1790/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 30c6d3f7a..d01dee9de 100644 --- a/Readme.md +++ b/Readme.md @@ -690,6 +690,7 @@ [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) [2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (H) +[2638.Count-the-Number-of-K-Free-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets) (M+) [2320.Count-Number-of-Ways-to-Place-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses) (M+) [1388.Pizza-With-3n-Slices](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1388.Pizza-With-3n-Slices) (H-) [276.Paint-Fence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/276.Paint-Fence) (H-) From 5415442411a4c01af3c99872a8f0b45195ba8383 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 23:45:05 -0700 Subject: [PATCH 1791/2729] Create Readme.md --- .../2638.Count-the-Number-of-K-Free-Subsets/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/Readme.md diff --git a/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/Readme.md b/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/Readme.md new file mode 100644 index 000000000..6b7d53111 --- /dev/null +++ b/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/Readme.md @@ -0,0 +1,7 @@ +### 2638.Count-the-Number-of-K-Free-Subsets + +此题和2597一模一样。将所有元素按照对k的模分组。 + +对于每组里的元素进行排序后,可以取任意的组合,但是相邻两个元素如果相差为k的话就不能同时取。这就是一个典型的house robber。 + +对于不同的组,彼此的取法互不影响,所以是乘法关系。 From 5254809ce70f11276d6300fdce666c9707e99fe6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Apr 2023 00:15:14 -0700 Subject: [PATCH 1792/2729] Create 1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp --- ...r-of-Neighbors-at-a-Threshold-Distance.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp diff --git a/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp b/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp new file mode 100644 index 000000000..4146467f4 --- /dev/null +++ b/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) + { + int dp[n][n]; + for (int i=0; i Date: Mon, 24 Apr 2023 00:17:14 -0700 Subject: [PATCH 1793/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d01dee9de..a316b26b5 100644 --- a/Readme.md +++ b/Readme.md @@ -1045,7 +1045,6 @@ [753.Cracking-the-Safe](https://github.com/wisdompeak/LeetCode/tree/master/Hash/753.Cracking-the-Safe) (H) [1059.All-Paths-from-Source-Lead-to-Destination](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1059.All-Paths-from-Source-Lead-to-Destination) (H) [1192.Critical-Connections-in-a-Network](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1192.Critical-Connections-in-a-Network) (H) -1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance (TBD) 1361.Validate-Binary-Tree-Nodes (TBD) [1719.Number-Of-Ways-To-Reconstruct-A-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1719.Number-Of-Ways-To-Reconstruct-A-Tree) (H+) [1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph) (M+) @@ -1055,6 +1054,8 @@ [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) +* ``Floyd`` +[1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) From 99ac886d16c176f233ae3af908cf94aaefc7c4e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Apr 2023 00:33:03 -0700 Subject: [PATCH 1794/2729] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/Readme.md diff --git a/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/Readme.md b/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/Readme.md new file mode 100644 index 000000000..72e3cd74e --- /dev/null +++ b/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/Readme.md @@ -0,0 +1,3 @@ +### 1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance + +本题就是Floy的模板题,用o(N^3)时间可以计算出任意两点之间的最短距离,然后再用o(N^2)寻找答案。 From 28f2f5a89f7c09eda64c3be45396b6d290eb2d75 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 11:54:44 -0700 Subject: [PATCH 1795/2729] Create 2647.Color-the-Triangle-Red.cpp --- .../2647.Color-the-Triangle-Red.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp diff --git a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp new file mode 100644 index 000000000..45dcc937e --- /dev/null +++ b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + vector> colorRed(int n) + { + vector>rets; + vector>val(n+1, vector(2*n+2)); + + for (int j=1; j<=2*n-1; j+=2) + { + val[n][j] = 1; + rets.push_back({n,j}); + } + + bool forward = 1; + for (int i=n-1; i>=2; i--) + { + int j, end, delta; + if (forward) { + j = 1; end = 2*i; delta = 1; + } else { + j = 2*i-1; end = 0; delta = -1; + } + + while (j != end) + { + if (val[i][j]==0){ + if (j%2 == 1) { // a normal triangle cell. Its bottom neighbour must have been filled. + if (val[i][j-1] || val[i][j+1]) { + } else { // favor next row cell, as its previous row neighbour must be filled in the next round. + val[i][j+delta] = 1; + rets.push_back({i, j+delta}); + } + } else { // a up-side-down triangle cell. Its up neighbour must have not been filled. + if (val[i][j-1] && val[i][j + 1]) { + } else { // favor upper cell, as its next neighbour must be filled in the next round. + val[i-1][j-1] = 1; + rets.push_back({i-1, j-1}); + } + } + val[i][j] = 1; + } + + j+= delta; + } + + forward = !forward; + } + + if (rets.back()[0]!=1 && rets.back()[1]!=1) { + rets.push_back({1,1}); + } + + return rets; + } +}; From ff57e6e905a571eb21d01bcf8f0ce9b52fa9b81d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 11:55:17 -0700 Subject: [PATCH 1796/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a316b26b5..1b8405322 100644 --- a/Readme.md +++ b/Readme.md @@ -1377,6 +1377,7 @@ [2380.Time-Needed-to-Rearrange-a-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2380.Time-Needed-to-Rearrange-a-Binary-String) (H) [2453.Destroy-Sequential-Targets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2453.Destroy-Sequential-Targets) (M) [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) +[2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 1ffe735bf944a631b33a9e4d808af85ca9476c98 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 12:08:14 -0700 Subject: [PATCH 1797/2729] Create Readme.md --- Others/2647.Color-the-Triangle-Red/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Others/2647.Color-the-Triangle-Red/Readme.md diff --git a/Others/2647.Color-the-Triangle-Red/Readme.md b/Others/2647.Color-the-Triangle-Red/Readme.md new file mode 100644 index 000000000..287e6d54b --- /dev/null +++ b/Others/2647.Color-the-Triangle-Red/Readme.md @@ -0,0 +1,11 @@ +### 2647.Color-the-Triangle-Red + +纯粹的贪心找规律。 + +初始,先将最后一行从左边开始,每隔一个cell进行染色。 + +然后,从最后一行开始,逐行扫描,按照顺序和逆序交替进行检查每个cell。如果已经被染色,则跳过。下面分情况讨论: +1. 如果该cell的列编号是奇数,说明是个正三角,它的下邻居必然已经染色(我们是逐行处理)。此时如果它的左右行邻居有一个被染色了,那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居还没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的下一个行邻居,这样它自身也可以”被动“染色。 +2. 如果该cell的列编号是偶数,说明是个倒三角,它的上邻居必然还没有被染色。此时如果它的左右行邻居都已经被染色了,那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居有任何一个没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的上邻居,这样它自身也可以”被动“染色*(因为已经有一个行邻居)。 + +这种算法可能会收录{1,2},我们要将其去掉,换成{1,1}。 From 60d949e49e7c04c669f84a3098fd7d9b47357f94 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 12:30:19 -0700 Subject: [PATCH 1798/2729] Update 2647.Color-the-Triangle-Red.cpp --- .../2647.Color-the-Triangle-Red.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp index 45dcc937e..65b4c3149 100644 --- a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp +++ b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp @@ -24,15 +24,17 @@ class Solution { while (j != end) { if (val[i][j]==0){ - if (j%2 == 1) { // a normal triangle cell. Its bottom neighbour must have been filled. - if (val[i][j-1] || val[i][j+1]) { - } else { // favor next row cell, as its previous row neighbour must be filled in the next round. + if (j%2 == 1) { // a normal triangle cell. Its bottom neighbour must have been filled. + if (val[i][j-delta]==0) { + // Noramlly, the previous row neighbour must have been filled. The exception is the case when (i,j) is already the edge. val[i][j+delta] = 1; rets.push_back({i, j+delta}); } } else { // a up-side-down triangle cell. Its up neighbour must have not been filled. - if (val[i][j-1] && val[i][j + 1]) { - } else { // favor upper cell, as its next neighbour must be filled in the next round. + if (val[i][j+delta]==0) { + // Noramlly, the next row neighbour must have not been filled. + // The exception is the case when (i,j) is already the edge, or the next row neighbour is filled by the previous row. + // favor upper cell, as its next neighbour must be filled in the next round. val[i-1][j-1] = 1; rets.push_back({i-1, j-1}); } From c61e3e82f1556c7b55c8cb74b5f212af7327b414 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 12:33:12 -0700 Subject: [PATCH 1799/2729] Update Readme.md --- Others/2647.Color-the-Triangle-Red/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Others/2647.Color-the-Triangle-Red/Readme.md b/Others/2647.Color-the-Triangle-Red/Readme.md index 287e6d54b..b9275d5b3 100644 --- a/Others/2647.Color-the-Triangle-Red/Readme.md +++ b/Others/2647.Color-the-Triangle-Red/Readme.md @@ -5,7 +5,7 @@ 初始,先将最后一行从左边开始,每隔一个cell进行染色。 然后,从最后一行开始,逐行扫描,按照顺序和逆序交替进行检查每个cell。如果已经被染色,则跳过。下面分情况讨论: -1. 如果该cell的列编号是奇数,说明是个正三角,它的下邻居必然已经染色(我们是逐行处理)。此时如果它的左右行邻居有一个被染色了,那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居还没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的下一个行邻居,这样它自身也可以”被动“染色。 -2. 如果该cell的列编号是偶数,说明是个倒三角,它的上邻居必然还没有被染色。此时如果它的左右行邻居都已经被染色了,那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居有任何一个没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的上邻居,这样它自身也可以”被动“染色*(因为已经有一个行邻居)。 +1. 如果该cell的列编号是奇数,说明是个正三角,它的下邻居必然已经染色(我们是逐行处理)。此时如果它之前的行邻居被染色了(通常情况下必然是的),那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居都还没有被染色(意味着它本身是该行的第一个),则它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的下一个行邻居,这样它自身也可以”被动“染色。 +2. 如果该cell的列编号是偶数,说明是个倒三角,它的上邻居必然还没有被染色。此时如果它的左右行邻居都已经被染色了(通常情况下前一个行邻居必然已经被染色,而下一个行邻居也有可能被跨行染色过),那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居有任何一个没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的上邻居,这样它自身也可以”被动“染色*(因为已经有一个行邻居)。 这种算法可能会收录{1,2},我们要将其去掉,换成{1,1}。 From cf9e1a2d1af189e80f6ef2cd7c3f22dc69cea40f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 12:34:05 -0700 Subject: [PATCH 1800/2729] Update 2647.Color-the-Triangle-Red.cpp --- .../2647.Color-the-Triangle-Red.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp index 65b4c3149..f057641ed 100644 --- a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp +++ b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp @@ -33,8 +33,8 @@ class Solution { } else { // a up-side-down triangle cell. Its up neighbour must have not been filled. if (val[i][j+delta]==0) { // Noramlly, the next row neighbour must have not been filled. - // The exception is the case when (i,j) is already the edge, or the next row neighbour is filled by the previous row. - // favor upper cell, as its next neighbour must be filled in the next round. + // The exception is the case when the next row neighbour is filled by the previous row. + // Favor upper cell, as its next neighbour must be filled in the next round. val[i-1][j-1] = 1; rets.push_back({i-1, j-1}); } From b0bbe758c91ac8f5b6d5c5f509d07168944e7708 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 15:29:53 -0700 Subject: [PATCH 1801/2729] Create 2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp --- ...m-Cost-of-a-Path-With-Special-Roads_v2.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp new file mode 100644 index 000000000..c4fba38db --- /dev/null +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp @@ -0,0 +1,46 @@ +using LL = long long; +using PLL = pair; +class Solution { +public: + int minimumCost(vector& start, vector& target, vector>& specialRoads) + { + mapdist; + + specialRoads.push_back({start[0], start[1], target[0], target[1], abs(start[0]-target[0])+abs(start[1]-target[1])}); + + priority_queue, greater<>>pq; + pq.push({0, encode(start[0], start[1])}); + + while (!pq.empty()) + { + auto [len, pos] = pq.top(); + pq.pop(); + if (dist.find(pos)!=dist.end()) continue; + dist[pos] = len; + auto [x,y] = decode(pos); + + if (x==target[0] && y==target[1]) return len; + + for (auto& road: specialRoads) + { + int x1 = road[0], y1 = road[1]; + int x2 = road[2], y2 = road[3]; + int cost = road[4]; + LL pos1 = encode(x1,y1); + LL pos2 = encode(x2,y2); + + if (dist.find(pos2)==dist.end()) + { + int d1 = abs(x-x1)+abs(y-y1) + cost; + int d2 = abs(x-x2)+abs(y-y2); + pq.push({len+min(d1,d2), pos2}); + } + } + } + + return -1; + } + + LL encode(LL x, LL y) {return (x<<32) + y;} + PLL decode(LL p) {return {p>>32, p%(1LL<<32)};} +}; From c222888a836d290924aab8e916dfb78f149acc35 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 15:30:40 -0700 Subject: [PATCH 1802/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1b8405322..fb4e9f97b 100644 --- a/Readme.md +++ b/Readme.md @@ -591,6 +591,7 @@ [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) +[2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From b42362186300670721ced9a70a1f00772c4f8b4e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 15:52:14 -0700 Subject: [PATCH 1803/2729] Create Readme.md --- .../Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md new file mode 100644 index 000000000..8d7bb0795 --- /dev/null +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md @@ -0,0 +1,6 @@ +### 2662.Minimum-Cost-of-a-Path-With-Special-Roads + +#### 解法2:Dijkstra +对于每条special road,它的起点其实都是无关紧要的,保底用start到其曼哈顿距离即可。只有这些special road的终点才是改变这张图拓扑关系的关键点(否则永远都是trivial的网格结构)。所以我们可以用Dijkstra算法,来更新start到各个road终点的最短距离。最后在所有的终点x里,挑一个最小的`start->x->target`的距离,其中`x->target`是曼哈顿距离。 + +更具体地,我们从pq里弹出当前某点p的最短距离len,那么我们就可以利用从x到y的road,更新从p到y的距离:`len + abs|p-x| + cost`. From 4e10fd535add2fcc2daeb48aa3bc9d0b6d30a2cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 15:52:42 -0700 Subject: [PATCH 1804/2729] Update 2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp --- ...m-Cost-of-a-Path-With-Special-Roads_v2.cpp | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp index c4fba38db..05920e795 100644 --- a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp @@ -6,11 +6,16 @@ class Solution { { mapdist; - specialRoads.push_back({start[0], start[1], target[0], target[1], abs(start[0]-target[0])+abs(start[1]-target[1])}); - priority_queue, greater<>>pq; pq.push({0, encode(start[0], start[1])}); + for (auto& road: specialRoads) + { + int x2 = road[2], y2 = road[3]; + LL pos2 = encode(x2,y2); + pq.push({abs(start[0]-x2)+abs(start[1]-y2), pos2}); + } + LL ret = INT_MAX; while (!pq.empty()) { auto [len, pos] = pq.top(); @@ -19,7 +24,7 @@ class Solution { dist[pos] = len; auto [x,y] = decode(pos); - if (x==target[0] && y==target[1]) return len; + ret = min(ret, len+abs(x-target[0])+abs(y-target[1])); for (auto& road: specialRoads) { @@ -28,17 +33,13 @@ class Solution { int cost = road[4]; LL pos1 = encode(x1,y1); LL pos2 = encode(x2,y2); - + if (dist.find(pos2)==dist.end()) - { - int d1 = abs(x-x1)+abs(y-y1) + cost; - int d2 = abs(x-x2)+abs(y-y2); - pq.push({len+min(d1,d2), pos2}); - } + pq.push({len + abs(x-x1)+abs(y-y1) + cost, pos2}); } } - return -1; + return ret; } LL encode(LL x, LL y) {return (x<<32) + y;} From ec162a733df6b780c8ed212be7cf5a04a1cb2127 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 16:20:46 -0700 Subject: [PATCH 1805/2729] Create 2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp --- ...m-Cost-of-a-Path-With-Special-Roads_v1.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp new file mode 100644 index 000000000..659589a21 --- /dev/null +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp @@ -0,0 +1,57 @@ +using LL = long long; +class Solution { + int dp[405][405]; +public: + int minimumCost(vector& start, vector& target, vector>& specialRoads) + { + specialRoads.push_back({start[0], start[1], target[0], target[1], abs(start[0]-target[0])+abs(start[1]-target[1])}); + + vector>point; + mapreverseMap; + for (int i=0; i Date: Mon, 1 May 2023 16:26:21 -0700 Subject: [PATCH 1806/2729] Update Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md index 8d7bb0795..ab5677766 100644 --- a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md @@ -1,5 +1,12 @@ ### 2662.Minimum-Cost-of-a-Path-With-Special-Roads +#### 解法1:Floyd +考虑到有200条road,意味着400个点。用n^3的floyd算法,也许可以在时间范围内勉强求得任意两点之间的最短距离。我们只需要在special roads里加一条从start到target的曼哈顿距离,就可以构图套用模板了。 + +注意本题需要将点去重,否则会TLE。 + +注意,本题的初始化包括:1.同一点的距离是0 2.任意两点之间的距离有曼哈顿距离保底 3.road的两点之间的距离可以更新为cost。 + #### 解法2:Dijkstra 对于每条special road,它的起点其实都是无关紧要的,保底用start到其曼哈顿距离即可。只有这些special road的终点才是改变这张图拓扑关系的关键点(否则永远都是trivial的网格结构)。所以我们可以用Dijkstra算法,来更新start到各个road终点的最短距离。最后在所有的终点x里,挑一个最小的`start->x->target`的距离,其中`x->target`是曼哈顿距离。 From db51e1d4f4907f37209b96556da11bbbb79de149 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 2 May 2023 00:17:17 -0700 Subject: [PATCH 1807/2729] Create 2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp --- ...m-Cost-of-a-Path-With-Special-Roads_v2.cpp | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp index 05920e795..2517f4ea4 100644 --- a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp @@ -4,44 +4,42 @@ class Solution { public: int minimumCost(vector& start, vector& target, vector>& specialRoads) { - mapdist; - - priority_queue, greater<>>pq; + priority_queue, greater<>>pq; // {dist to node, node id} pq.push({0, encode(start[0], start[1])}); for (auto& road: specialRoads) - { - int x2 = road[2], y2 = road[3]; - LL pos2 = encode(x2,y2); - pq.push({abs(start[0]-x2)+abs(start[1]-y2), pos2}); + { + int x = road[2], y = road[3]; + pq.push({abs(start[0]-x)+abs(start[1]-y), encode(x,y)}); } + mapdist; LL ret = INT_MAX; while (!pq.empty()) { - auto [len, pos] = pq.top(); + auto [len, id] = pq.top(); pq.pop(); - if (dist.find(pos)!=dist.end()) continue; - dist[pos] = len; - auto [x,y] = decode(pos); + if (dist.find(id)!=dist.end()) continue; + dist[id] = len; + auto [x,y] = decode(id); - ret = min(ret, len+abs(x-target[0])+abs(y-target[1])); + ret = min(ret, len + abs(x-target[0])+abs(y-target[1])); for (auto& road: specialRoads) { int x1 = road[0], y1 = road[1]; int x2 = road[2], y2 = road[3]; int cost = road[4]; - LL pos1 = encode(x1,y1); - LL pos2 = encode(x2,y2); + LL id2 = encode(x2,y2); - if (dist.find(pos2)==dist.end()) - pq.push({len + abs(x-x1)+abs(y-y1) + cost, pos2}); + if (dist.find(id2)==dist.end()) + pq.push({len + abs(x-x1)+abs(y-y1) + cost, id2}); } + } return ret; } LL encode(LL x, LL y) {return (x<<32) + y;} - PLL decode(LL p) {return {p>>32, p%(1LL<<32)};} + PLL decode(LL id) {return {id>>32, id%(1LL<<32)};} }; From 0b60ff0bf9663fee44318f65afe9d032b0e47789 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 May 2023 19:10:31 -0700 Subject: [PATCH 1808/2729] Update 386.Lexicographical-Numbers.cpp --- .../386.Lexicographical-Numbers.cpp | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/Greedy/386.Lexicographical-Numbers/386.Lexicographical-Numbers.cpp b/Greedy/386.Lexicographical-Numbers/386.Lexicographical-Numbers.cpp index 8f50d6c7c..abbe47eb0 100644 --- a/Greedy/386.Lexicographical-Numbers/386.Lexicographical-Numbers.cpp +++ b/Greedy/386.Lexicographical-Numbers/386.Lexicographical-Numbers.cpp @@ -2,24 +2,25 @@ class Solution { public: vector lexicalOrder(int n) { - int current=1; - vectorresults(n); + vectorrets = {1}; + int i=1; - for (int i=0; in) - current=current/10; - current++; - while (current % 10==0) - current/=10; + i=i*10; } - } - return results; + else + { + while (i+1>n || (i%10==9)) + i = i/10; + i+=1; + } + + rets.push_back(i); + } + + return rets; } }; From b4b8c7ba1c8bdecbf924ce9759e78acede853642 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 May 2023 19:18:55 -0700 Subject: [PATCH 1809/2729] Update Readme.md --- Greedy/386.Lexicographical-Numbers/Readme.md | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Greedy/386.Lexicographical-Numbers/Readme.md b/Greedy/386.Lexicographical-Numbers/Readme.md index 39240a944..14fbd992e 100644 --- a/Greedy/386.Lexicographical-Numbers/Readme.md +++ b/Greedy/386.Lexicographical-Numbers/Readme.md @@ -1,12 +1,8 @@ ### 386.Lexicographical-Numbers -研究序列[1,10,11,12,13,2,3,4,5,6,7,8,9],找出字典序的规律。 +对于字典序列的next,核心就是 +1. 尝试往后加0, 否则 +2. 找最低的、加1不需要进位的位置,在该位置加1后,舍弃之后的位置即可。 -规律1:不考虑上限,元素1后面跟什么元素?10, 100 … 也就是不断乘以10。 -规律2:如果99是上限,那么10后面的元素不能是100了,该怎么办?答案是11,也就是加1,这样个位上的数变大了。如果加1导致进位的话,虽然个位数变0,但十位上的数会变大,总之肯定字典序往后移。但此时得到的并不是下一个的目标,因为把其末尾的0去掉会得到字典序相对更前的数。砍掉0之后就可以重复规律1的操作了。 - -规律3:如果上限是19,那么19后面的元素就不能是20了,该怎么办?答案是将19除以10,然后再重复规律2(也就是加1),也就是得到2,之后又可以重复规律1了。 - - -[Leetcode Link](https://leetcode.com/problems/lexicographical-numbers) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/lexicographical-numbers) From 5ac67e83cfc685271e9e8a02d845aaaf9148d4d7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 May 2023 19:22:44 -0700 Subject: [PATCH 1810/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index fb4e9f97b..7b0860e05 100644 --- a/Readme.md +++ b/Readme.md @@ -1011,7 +1011,7 @@ [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [397.Integer-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/397.Integer-Replacement) (M+) -440.K-th-Smallest-in-Lexicographical-Order (H) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/440.K-th-Smallest-in-Lexicographical-Order) (H-) [761.Special-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/761.Special-Binary-String) (H) 779.K-th-Symbol-in-Grammar (M) [780.Reaching-Points](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/780.Reaching-Points) (H-) From 68158dc5b85dd108e368ed895e519afc0b714c7a Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Thu, 4 May 2023 19:57:37 -0700 Subject: [PATCH 1811/2729] mv 440 --- .../440.K-th-Smallest-in-Lexicographical-Order.cpp | 0 .../440.K-th-Smallest-in-Lexicographical-Order/Readme.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {Recursion => Others}/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp (100%) rename {Recursion => Others}/440.K-th-Smallest-in-Lexicographical-Order/Readme.md (100%) diff --git a/Recursion/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp similarity index 100% rename from Recursion/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp rename to Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp diff --git a/Recursion/440.K-th-Smallest-in-Lexicographical-Order/Readme.md b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md similarity index 100% rename from Recursion/440.K-th-Smallest-in-Lexicographical-Order/Readme.md rename to Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md From 8f0aba87da37163c4626c519d735d32c2fc4ebaa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 May 2023 19:58:26 -0700 Subject: [PATCH 1812/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7b0860e05..bd8216e8b 100644 --- a/Readme.md +++ b/Readme.md @@ -1011,7 +1011,6 @@ [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [397.Integer-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/397.Integer-Replacement) (M+) -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/440.K-th-Smallest-in-Lexicographical-Order) (H-) [761.Special-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/761.Special-Binary-String) (H) 779.K-th-Symbol-in-Grammar (M) [780.Reaching-Points](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/780.Reaching-Points) (H-) @@ -1451,6 +1450,7 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) From 4f6dc7ec74d523048aca8c6d4be635edc2f39416 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 May 2023 00:09:15 -0700 Subject: [PATCH 1813/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index bd8216e8b..32d4fd13a 100644 --- a/Readme.md +++ b/Readme.md @@ -1450,7 +1450,7 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/440.K-th-Smallest-in-Lexicographical-Order) (H-) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) From f2333c9f700345192ec1111bb1359b9a90236644 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 13:30:57 -0700 Subject: [PATCH 1814/2729] Update 440.K-th-Smallest-in-Lexicographical-Order.cpp --- ...K-th-Smallest-in-Lexicographical-Order.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp index c0d853bbf..e02e8bacb 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp @@ -7,35 +7,36 @@ class Solution { } // return the Lexicographically Kth element that begin with the prefix - // excluding the prefix itself + // if k==0, return the prefix itself. int FindKthNumberBeginWith(int prefix, int n, int k) { - if (k==0) return prefix; + if (k==0) return prefix; for (int i=(prefix==0?1:0); i<=9; i++) { - int count = TotalNumbersBeginWith(prefix*10+i,n); + int count = 1 + TotalNumbersBeginWith(prefix*10+i,n); if (count n) break; + + if(min <= n && n <= max) { count += (n-min+1); break; From e87ff063e7d138258f4caed2266b8a0bfaccf55a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 17:34:46 -0700 Subject: [PATCH 1815/2729] Update Readme.md --- .../Readme.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md index 1bc3a3dfc..d9ada75a0 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md @@ -1,8 +1,12 @@ ### 440.K-th-Smallest-in-Lexicographical-Order -本题初看和```386.Lexicographical-Numbers```非常相似,但解法大不相同.在386题中,因为需要将按照字典序从小到大所有的元素打印出来,所以可以用构造法把这些数都找出来.但本题中,如果K很大,要将从1到K个的字典序元素都生成是很费时的. +本题初看和```386.Lexicographical-Numbers```非常相似,但解法大不相同.在386题中,因为需要将按照字典序从小到大所有的元素打印出来,所以可以用构造法把这些数都找出来.但本题中,如果K很大,要将从1到K个的字典序元素都生成是很费时的. -此题的解法很巧妙.举个例子,假设n=23456,k=10000,我们期待的结果是R.我们如何找到R呢?我们肯定会先尝试R的第一个数字是否会是1.此时,一个快速的筛选准则是:考察所有小于n的1xxxx(x的个数随意),可以计算总共有几个这样的数,我们假设是M.我们应该发现,这M个数其实就是字典序里的前M个(因为首元素是1,字典序最小).如果Mk的话,我们就确定了首元素必须是1,进而考虑第二个数字,也是从1的可能性考虑起--我们发现,这就是在递归重复之前的步骤. +此题可以用递归的思路来拆解每个digit,逐步将k化小。我们先考察所有以1开头的数字`1xx..xx`,它们必然在字典序里是最靠前的一拨。如果它们的个数count1小于k,那么就意味着答案的首数字必然不会是1,我们就可以`k-=count1`。我们再考察所有以2开头的数字`2xx..xx`,同理此时它们必然在字典序里是最靠前的一拨。如果它们的个数count1大于k,说明我们的答案的首数字必然就是2! + +接下来我们同理,处理第二位数字。我们先考察所有以20开头的数字`20xx..xx`,如果它们的个数count20小于k,那么就意味着答案的首两位数字必然不会是20,我们就可以`k-=count20`。我们再考察所有以21开头的数字`21xx..xx`,同理此时它们必然在字典序里是最靠前的一拨。如果它们的个数count21小于k,说明答案的首两位数字必然不会是21,我们继续`k-=count21`。直至我们发现`22xx..xx`的个数count22大于k,说明最终答案的首二位数字就是22. + +所以我们可以重复调用主函数`FindKthNumberBeginWith(prefix, k)`,表示求以prefix为前缀的第k个字典序排列的元素。如果k为0,就输出prefix本身。 代码的流程大致如下: ```cpp @@ -12,7 +16,7 @@ int FindKthNumberBeginWith(prefix,k) for i=0 to 9 { - count = TotalNumbersBeginWith(prefix+[i]); + count = TotalNumbersBeginWith(prefix+[i], n); if (count Date: Sun, 7 May 2023 17:35:02 -0700 Subject: [PATCH 1816/2729] Update Readme.md --- Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md index d9ada75a0..244cbdcfc 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md @@ -25,7 +25,7 @@ int FindKthNumberBeginWith(prefix,k) } ``` -此外我们需要辅助函数`TotalNumbersBeginWith(prefix, n)`,计算所有以prefix为前缀的、不大于n的元素的数量。对此,我们只需要枚举前缀后面还需要加几位即可。加一位,就有0~9这些可能;加两位,就有00~99这些可能;直至位数加长到m,发现`prefix+999...999`超过了n,那么就不再尝试加长了。 +此外我们需要辅助函数`TotalNumbersBeginWith(prefix, n)`,计算所有以prefix为前缀的、不大于n的元素的数量。对此,我们只需要枚举前缀后面还需要加几位即可。加一位,就有`0~9`这些可能;加两位,就有`00~99`这些可能;直至位数加长到m,发现`prefix+999...999`超过了n,那么就不再尝试加长了。 [Leetcode Link](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order) From 81a55a9864de9b34cfefd047df8bd7ea5698fded Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 21:47:19 -0700 Subject: [PATCH 1817/2729] Update 440.K-th-Smallest-in-Lexicographical-Order.cpp --- ...K-th-Smallest-in-Lexicographical-Order.cpp | 68 ++++++++++--------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp index e02e8bacb..fe5afc34a 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp @@ -1,50 +1,54 @@ class Solution { - public: int findKthNumber(int n, int k) - { - return FindKthNumberBeginWith(0,n,k); + { + return FindKthNUmberBeginWith(0, n, k); } - - // return the Lexicographically Kth element that begin with the prefix - // if k==0, return the prefix itself. - int FindKthNumberBeginWith(int prefix, int n, int k) - { + + // return the Lexicographically k-th element that begins with prefix + // if k==0, return prefix itself + int FindKthNUmberBeginWith(int prefix, int n, int k) + { if (k==0) return prefix; - - for (int i=(prefix==0?1:0); i<=9; i++) + + int start = (prefix == 0) ? 1 : 0; + for (int i=start; i<=9; i++) { - int count = 1 + TotalNumbersBeginWith(prefix*10+i,n); - if (count n) break; - - if(min <= n && n <= max) + long lower = prefix * exp; + long upper = prefix * exp + exp + 1; + if (lower > n) break; + if (lower <= n && upper >= n) { - count += (n-min+1); + count += (n - lower +1); break; } - else - count += fac; - fac *= 10; + else + { + count += exp; + } + + exp *= 10; } + return count; - } + } }; + From 8c11c9ec44626add89a1a01d1c9ae34c6773815c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 22:01:37 -0700 Subject: [PATCH 1818/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 32d4fd13a..c496cfa9c 100644 --- a/Readme.md +++ b/Readme.md @@ -1022,7 +1022,6 @@ [1088.Confusing-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1088.Confusing-Number-II) (H) [1199.Minimum-Time-to-Build-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1199.Minimum-Time-to-Build-Blocks) (H+) [1274.Number-of-Ships-in-a-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1274.Number-of-Ships-in-a-Rectangle) (M) -[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) 1545. Find Kth Bit in Nth Binary String (TBD) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) @@ -1451,6 +1450,7 @@ * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) [440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) +[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) From 1f4ff9d68984d2f7945320f875515612bdc5dace Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 22:16:44 -0700 Subject: [PATCH 1819/2729] Update Readme.md --- Readme.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index c496cfa9c..89d03f004 100644 --- a/Readme.md +++ b/Readme.md @@ -1022,7 +1022,6 @@ [1088.Confusing-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1088.Confusing-Number-II) (H) [1199.Minimum-Time-to-Build-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1199.Minimum-Time-to-Build-Blocks) (H+) [1274.Number-of-Ships-in-a-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1274.Number-of-Ships-in-a-Rectangle) (M) -1545. Find Kth Bit in Nth Binary String (TBD) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) * ``Evaluate Expressions`` @@ -1037,6 +1036,12 @@ [1510.Stone-Game-IV](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1510.Stone-Game-IV) (M) [1563.Stone-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1563.Stone-Game-V) (H-) [2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) +* ``Digit counting & finding`` +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) +[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) +[1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) +1545. Find Kth Bit in Nth Binary String (TBD) +[2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) @@ -1453,7 +1458,6 @@ [1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) -[2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) From ea847ac4b2f864d5e4163a6d5959241254459bae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 22:17:22 -0700 Subject: [PATCH 1820/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 89d03f004..9c73a60a7 100644 --- a/Readme.md +++ b/Readme.md @@ -1040,7 +1040,7 @@ [440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) -1545. Find Kth Bit in Nth Binary String (TBD) +1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) From 9cd0a06ef2d5fd41a0cf5a87476a3dc53f1dd55c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 22:18:18 -0700 Subject: [PATCH 1821/2729] Update Readme.md --- Readme.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/Readme.md b/Readme.md index 9c73a60a7..bef9a5ba2 100644 --- a/Readme.md +++ b/Readme.md @@ -1454,8 +1454,6 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) -[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) From c1c7f603bd5a7b3dbb075bc37a069980379d0ac3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 00:01:03 -0700 Subject: [PATCH 1822/2729] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md index 4bd11e3cc..a53009d20 100644 --- a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md +++ b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md @@ -6,6 +6,6 @@ #### 解法2 更聪明点的递归。 -当我们尝试填写长度为n的字符串的首字母时,无论首字母是什么,之后的n-1位都有pow(2,n-1)种填写方法。所以我们用k/pow(2,n-1)就可以确定此时的首字母ch应该是字母表的第几个。注意这里的k应该用0-index更为方便。比如k=0,那么ch应该就是'a',如果k=1,那么ch应该就是'b'. +当我们尝试填写长度为n的字符串的首字母时,无论首字母是什么,之后的n-1位都有pow(2,n-1)种填写方法。所以我们用`t = k/pow(2,n-1)`就可以确定此时的首字母ch应该是字母表的第几个。注意这里的k和t都用0-index更为方便。比如t=0,那么ch应该就是'a',如果t=1,那么ch应该就是'b'. -但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着当前字母基数应该加1。因为此位我们不能尝试和前面一样的字母,所以会少pow(2,n-1)的可能性。 +但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着当前字母基数应该加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过“一圈”。但此时的位置上我们只能填'c'而不是'b',这是因为`aaxx..xx`不是happy string无法计入序列。所以我们只能跳过`abxx..xx`,递归处理`acxx.xx`的情况。 From 386b73b32459f59100e2c2490d38a9283abbe426 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 00:01:42 -0700 Subject: [PATCH 1823/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md index a53009d20..eefc0de5f 100644 --- a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md +++ b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md @@ -8,4 +8,4 @@ 当我们尝试填写长度为n的字符串的首字母时,无论首字母是什么,之后的n-1位都有pow(2,n-1)种填写方法。所以我们用`t = k/pow(2,n-1)`就可以确定此时的首字母ch应该是字母表的第几个。注意这里的k和t都用0-index更为方便。比如t=0,那么ch应该就是'a',如果t=1,那么ch应该就是'b'. -但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着当前字母基数应该加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过“一圈”。但此时的位置上我们只能填'c'而不是'b',这是因为`aaxx..xx`不是happy string无法计入序列。所以我们只能跳过`abxx..xx`,递归处理`acxx.xx`的情况。 +但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着实际填写的ch还需要再加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过“一圈”。但此时的位置上我们只能填'c'而不是'b',这是因为`aaxx..xx`不是happy string无法计入序列。所以我们只能跳过`abxx..xx`,递归处理`acxx.xx`的情况。 From 520bfd33ec437a8eb3cf4e36ce5a9273331f49b9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 00:06:02 -0700 Subject: [PATCH 1824/2729] Update Readme.md --- .../Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md index eefc0de5f..2757aebc5 100644 --- a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md +++ b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md @@ -8,4 +8,5 @@ 当我们尝试填写长度为n的字符串的首字母时,无论首字母是什么,之后的n-1位都有pow(2,n-1)种填写方法。所以我们用`t = k/pow(2,n-1)`就可以确定此时的首字母ch应该是字母表的第几个。注意这里的k和t都用0-index更为方便。比如t=0,那么ch应该就是'a',如果t=1,那么ch应该就是'b'. -但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着实际填写的ch还需要再加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过“一圈”。但此时的位置上我们只能填'c'而不是'b',这是因为`aaxx..xx`不是happy string无法计入序列。所以我们只能跳过`abxx..xx`,递归处理`acxx.xx`的情况。 +但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着实际填写的ch还需要再加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过`2^(n-1)`种排列。但注意这`2^(n-1)`种排列并不是对应的`axx..xx`,因为它与上一个位置'a'冲突。所以我们只能认为这`2^(n-1)`种排列对应的是`bxx..xx`。故跳过他们之后,我们认为本位置必须是填写`c`. + From 9f2503764066a65e289b6b0c9c19b788140fc146 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 23:17:54 -0700 Subject: [PATCH 1825/2729] Create 031.Next-Permutation.cpp --- .../031.Next-Permutation.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Greedy/031.Next-Permutation/031.Next-Permutation.cpp diff --git a/Greedy/031.Next-Permutation/031.Next-Permutation.cpp b/Greedy/031.Next-Permutation/031.Next-Permutation.cpp new file mode 100644 index 000000000..c3752dcd9 --- /dev/null +++ b/Greedy/031.Next-Permutation/031.Next-Permutation.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + void nextPermutation(vector& nums) + { + int i = nums.size()-1; + while (i>=1 && nums[i]<=nums[i-1]) + i--; + + if (i==0) + { + sort(nums.begin(), nums.end()); + return; + } + + i--; + + int j = nums.size()-1; + while (nums[j]<=nums[i]) + j--; + swap(nums[i], nums[j]); + sort(nums.begin()+i+1, nums.end()); + return; + } +}; From 81d16e111408fb805eccecbcb3d78d104761462f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 23:22:45 -0700 Subject: [PATCH 1826/2729] Create Readme.md --- Greedy/031.Next-Permutation/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/031.Next-Permutation/Readme.md diff --git a/Greedy/031.Next-Permutation/Readme.md b/Greedy/031.Next-Permutation/Readme.md new file mode 100644 index 000000000..250ef1182 --- /dev/null +++ b/Greedy/031.Next-Permutation/Readme.md @@ -0,0 +1,7 @@ +### 031.Next-Permutation + +首先,如果已经是完全降序的序列,它是没有next permuation的。此时输出重新按升序排列的数组。 + +接下来,我们从后往前遍历,当第一次出现`nums[i] Date: Mon, 8 May 2023 23:23:32 -0700 Subject: [PATCH 1827/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bef9a5ba2..7a3c5b9f4 100644 --- a/Readme.md +++ b/Readme.md @@ -1155,6 +1155,7 @@ [2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) +[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M+) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) From 46e586efd06c25d9d4359dfbe2a592da89ccccca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 23:58:08 -0700 Subject: [PATCH 1828/2729] Create 1358.Number-of-Substrings-Containing-All-Three-Characters.cpp --- ...trings-Containing-All-Three-Characters.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp diff --git a/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp new file mode 100644 index 000000000..d33a927b8 --- /dev/null +++ b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int numberOfSubstrings(string s) + { + int j = 0; + int count1 = 0, count2 = 0, count3 = 0; + int ret = 0; + for (int i=0; i Date: Mon, 8 May 2023 23:58:45 -0700 Subject: [PATCH 1829/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7a3c5b9f4..b9fff2641 100644 --- a/Readme.md +++ b/Readme.md @@ -38,6 +38,7 @@ [930.Binary-Subarrays-With-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/930.Binary-Subarrays-With-Sum) (M+) [1004.Max-Consecutive-Ones-III](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1004.Max-Consecutive-Ones-III) (M) [1052.Grumpy-Bookstore-Owner](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1052.Grumpy-Bookstore-Owner) (M) +[1358.Number-of-Substrings-Containing-All-Three-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters) (M) [1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [1763.Longest-Nice-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1763.Longest-Nice-Substring) (H) From 897586ef42edff7536306e100a72307f27921c63 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 9 May 2023 00:10:44 -0700 Subject: [PATCH 1830/2729] Update 1358.Number-of-Substrings-Containing-All-Three-Characters.cpp --- ...8.Number-of-Substrings-Containing-All-Three-Characters.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp index d33a927b8..8f44c1324 100644 --- a/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp +++ b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp @@ -7,14 +7,14 @@ class Solution { int ret = 0; for (int i=0; i 0) ret += s.size()-j+1; if (s[i]=='a') count1--; From 033d935a5b96a57ce790cc059fa7285dc235bed0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 9 May 2023 00:17:09 -0700 Subject: [PATCH 1831/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/Readme.md diff --git a/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/Readme.md b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/Readme.md new file mode 100644 index 000000000..927942064 --- /dev/null +++ b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/Readme.md @@ -0,0 +1,7 @@ +### 1358.Number-of-Substrings-Containing-All-Three-Characters + +我们固定滑窗的左端点i,向右探索右端点j。当我们发现移动到某处的j,使得[i:j]恰好至少包含a,b,c各一个的时候,那么意味着右端点其实可以直至在从j到n-1的任何位置,都满足条件。这样的区间有n-j个。 + +此时我们查看下一个i作为左端点,同样为了满足[i:j]恰好至少包含a,b,c各一个,j必然向右移动。同理,可以计算出以i为左端点、符合条件的区间的个数。 + +最终答案就是以每个i作为左端点时,符合条件的右端点的数目的总和。 From 46140c0c10f1a2082f6f535afd00cf8678068301 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:12:21 -0700 Subject: [PATCH 1832/2729] Create 2681.Power-of-Heroes.cpp --- .../2681.Power-of-Heroes.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Others/2681.Power-of-Heroes/2681.Power-of-Heroes.cpp diff --git a/Others/2681.Power-of-Heroes/2681.Power-of-Heroes.cpp b/Others/2681.Power-of-Heroes/2681.Power-of-Heroes.cpp new file mode 100644 index 000000000..edf467eee --- /dev/null +++ b/Others/2681.Power-of-Heroes/2681.Power-of-Heroes.cpp @@ -0,0 +1,25 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int sumOfPower(vector& nums) + { + sort(nums.begin(), nums.end()); + + LL sum = 0; + LL ret = 0; + + for (int i=0; i=1) + sum = sum * 2 % M + (LL)nums[i-1]; + + ret += mx * sum % M + mx * nums[i] % M; + ret %= M; + } + + return ret; + } +}; From 4f6381a40e87a3ea3d1354e5769fb5247712dac4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:12:55 -0700 Subject: [PATCH 1833/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b9fff2641..9511703d6 100644 --- a/Readme.md +++ b/Readme.md @@ -1439,6 +1439,7 @@ [1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/Others/1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions) (M+) [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) +[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From cc8905dc73583cbad9f77b7548e855cfcded7ac2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:33:58 -0700 Subject: [PATCH 1834/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9511703d6..4db991d63 100644 --- a/Readme.md +++ b/Readme.md @@ -1398,6 +1398,7 @@ [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) +[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) @@ -1439,7 +1440,6 @@ [1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/Others/1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions) (M+) [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) -[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 2a3563f048223ee3171d0e080d39283c5bdb8b49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:36:35 -0700 Subject: [PATCH 1835/2729] Create 2680.Maximum-OR.cpp --- .../2680.Maximum-OR/2680.Maximum-OR.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Bit_Manipulation/2680.Maximum-OR/2680.Maximum-OR.cpp diff --git a/Bit_Manipulation/2680.Maximum-OR/2680.Maximum-OR.cpp b/Bit_Manipulation/2680.Maximum-OR/2680.Maximum-OR.cpp new file mode 100644 index 000000000..60d85e143 --- /dev/null +++ b/Bit_Manipulation/2680.Maximum-OR/2680.Maximum-OR.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { +public: + long long maximumOr(vector& nums, int k) + { + vectorcount(32); + + for (int i = 0; i< nums.size(); i++) + { + for (int j=0; j<=31; j++) + { + if ((nums[i]>>j)&1) + count[j]++; + } + } + + LL ret = 0; + for (int i = 0; i< nums.size(); i++) + { + auto temp = count; + for (int j=0; j<=31; j++) + { + if ((nums[i]>>j)&1) + temp[j]--; + } + LL ans = 0; + for (int j=0; j<=31; j++) + { + if (temp[j]>0) + ans += (1< Date: Sat, 13 May 2023 10:36:58 -0700 Subject: [PATCH 1836/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4db991d63..e55114d0c 100644 --- a/Readme.md +++ b/Readme.md @@ -879,6 +879,7 @@ 1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K (TBD) [1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) [2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) +[2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From bd6b370815dfffed483694b21a50968381d09dad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:49:27 -0700 Subject: [PATCH 1837/2729] Create Readme.md --- Others/2681.Power-of-Heroes/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Others/2681.Power-of-Heroes/Readme.md diff --git a/Others/2681.Power-of-Heroes/Readme.md b/Others/2681.Power-of-Heroes/Readme.md new file mode 100644 index 000000000..2a92eba56 --- /dev/null +++ b/Others/2681.Power-of-Heroes/Readme.md @@ -0,0 +1,15 @@ +### 2681.Power-of-Heroes + +我们将所有元素排序之后,假设nums[i]是所选子集的最大值,那么意味着子集的其他元素必然是在[0:i-1]里面选择。我们依次枚举最小值的话,那么所有子集的最小值的和 +``` +sum = nums[0]* 2^(i-2) + nums[1] * 2^(i-1) + ... + nums[i-1]* 2^0; +``` +别忘了nums[i]本身也可以是最小值(子集只有一个元素)。所以答案就是`sum * nums[i]^2 + nums[i] * nums[i]^2`。 + +当我们右移i,考虑新的nums[i]是所选自己的最大值时,sum依然是 +``` +sum = nums[0]* 2^(i-2) + nums[1] * 2^(i-1) + ... + nums[i-1]* 2^0; +``` +和之前的sum相比,变动就是`sum = (sum + nums[i-1]) * 2`,o(1)时间就可以更新sum。 + +所以本题的算法就是:排序后,假设nums[i]是所选子集的最大值,更新sum,然后最终答案加上`sum * nums[i]^2 + nums[i] * nums[i]^2` From 7797177c38935aa8af2d732b9b0ca781fe2abe2d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:55:39 -0700 Subject: [PATCH 1838/2729] Create Readme.md --- Bit_Manipulation/2680.Maximum-OR/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Bit_Manipulation/2680.Maximum-OR/Readme.md diff --git a/Bit_Manipulation/2680.Maximum-OR/Readme.md b/Bit_Manipulation/2680.Maximum-OR/Readme.md new file mode 100644 index 000000000..2ac6739e0 --- /dev/null +++ b/Bit_Manipulation/2680.Maximum-OR/Readme.md @@ -0,0 +1,5 @@ +### 2680.Maximum-OR + +显然最贪心的策略是,我们将最高位的bit 1推地越远越好,最终的答案一定最大。所以直观上,我们应该把k次机会都给最大的元素,才能更高效地提升最高位的1。 + +但是从例子中可以发现,如果有多个元素都含有相同最高位的1,不见得推最大元素是最优解。那么没关系,我们每个元素都试一下抬高k位的效果,取最大值即可。时间复杂度就是o(N). From bfe8316ddaadc2cd775993d92791424f33518e11 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 23:22:01 -0700 Subject: [PATCH 1839/2729] Update 556.Next-Greater-Element-III.cpp --- .../556.Next-Greater-Element-III.cpp | 55 ++++++++----------- 1 file changed, 23 insertions(+), 32 deletions(-) diff --git a/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp b/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp index 2d2ad0681..7ae9d9f89 100644 --- a/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp +++ b/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp @@ -2,42 +2,33 @@ class Solution { public: int nextGreaterElement(int n) { - if (n==0) return -1; - - vectornum; - while (n>0) + vectordigits; + while(n>0) { - num.push_back(n%10); + digits.push_back(n%10); n=n/10; } + int m = digits.size(); + + reverse(digits.begin(), digits.end()); + + int i = m-1; + while (i>=1 && digits[i-1] >= digits[i]) + i--; + if (i==0) return -1; + + i--; + int j = m-1; + while (digits[j] <= digits[i]) + j--; + swap(digits[i], digits[j]); + sort(digits.begin()+i+1, digits.end()); - vectorp; - p.push_back(num[0]); - int i=1; - while (i=num[i-1]) - { - p.push_back(num[i]); - i++; - } - if (i==num.size()) return -1; // all the digits are descending - - int j=0; - while (p[j]<=num[i]) j++; - swap(num[i],p[j]); - - sort(p.begin(),p.end()); - reverse(p.begin(),p.end()); - - for (int k=0; k=0; i--) - result = result*10+num[i]; + long long ret=0; + for (int i=0; iINT_MAX) - return -1; - else - return result; + if (ret>INT_MAX) return -1; + else return ret; } }; From a39e3495f9b5f6baeb8ca650b5c8eae069195b26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 23:23:14 -0700 Subject: [PATCH 1840/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e55114d0c..c56b8c864 100644 --- a/Readme.md +++ b/Readme.md @@ -918,7 +918,6 @@ [388.Longest-Absolute-File-Path](https://github.com/wisdompeak/LeetCode/tree/master/String/388.Longest-Absolute-File-Path) (M+) [418.Sentence-Screen-Fitting](https://github.com/wisdompeak/LeetCode/tree/master/String/418.Sentence-Screen-Fitting) (M+) [423.Reconstruct-Original-Digits-from-English](https://github.com/wisdompeak/LeetCode/tree/master/Others/423.Reconstruct-Original-Digits-from-English) (H-) -[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/String/556.Next-Greater-Element-III) (H-) 616.Add-Bold-Tag-in-String (M) [467.Unique-Substrings-in-Wraparound-String](https://github.com/wisdompeak/LeetCode/tree/master/String/467.Unique-Substrings-in-Wraparound-String) (H-) [564.Find-the-Closest-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/String/564.Find-the-Closest-Palindrome) (H) @@ -1157,7 +1156,8 @@ [2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) -[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M+) +[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) +[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/String/556.Next-Greater-Element-III) (M) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) From 981520142d0eaed5f6b9dbc40e2895d5d0ffa67d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 23:23:45 -0700 Subject: [PATCH 1841/2729] Update Readme.md --- String/556.Next-Greater-Element-III/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/String/556.Next-Greater-Element-III/Readme.md b/String/556.Next-Greater-Element-III/Readme.md index 3702936d9..aa3aff20a 100644 --- a/String/556.Next-Greater-Element-III/Readme.md +++ b/String/556.Next-Greater-Element-III/Readme.md @@ -1,8 +1,10 @@ ### 556.Next-Greater-Element-III +此题和`031.next permuation`一模一样 + 首先,从低位到高位找到第一个不满足升序的数字。显然,如果从低位到高位都是升序的话,那么找不到任何可以比这个数字更大的变换了。 假设找到这样的数字在第n+1位(记做k),那么在1\~n这个n个低位数字中找到恰比k大的数字(记做m),交换k和m。于是变换后的第n+1位就这么定下来了(可以分析出这就是最小的改动)。剩下来的第1~n位(记得其中有一个是之前调换过来的k),我们让它们按照降序排列即可。 -[Leetcode Link](https://leetcode.com/problems/next-greater-element-iii) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/next-greater-element-iii) From 9bc7020987b74143e8418257d78896ba036c8afc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 00:31:14 -0700 Subject: [PATCH 1842/2729] mv 556 go Greedy --- .../556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp | 0 {String => Greedy}/556.Next-Greater-Element-III/Readme.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {String => Greedy}/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp (100%) rename {String => Greedy}/556.Next-Greater-Element-III/Readme.md (100%) diff --git a/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp b/Greedy/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp similarity index 100% rename from String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp rename to Greedy/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp diff --git a/String/556.Next-Greater-Element-III/Readme.md b/Greedy/556.Next-Greater-Element-III/Readme.md similarity index 100% rename from String/556.Next-Greater-Element-III/Readme.md rename to Greedy/556.Next-Greater-Element-III/Readme.md From b9ca3554f9a3455be772457e1096c761b2c9b3eb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 00:31:45 -0700 Subject: [PATCH 1843/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c56b8c864..a58d4b55e 100644 --- a/Readme.md +++ b/Readme.md @@ -1157,7 +1157,7 @@ #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) -[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/String/556.Next-Greater-Element-III) (M) +[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) From 3d296800c6f0153233487ec1e04a1bfa8b1fe546 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 10:23:33 -0700 Subject: [PATCH 1844/2729] Create 2663.Lexicographically-Smallest-Beautiful-String.cpp --- ...ographically-Smallest-Beautiful-String.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp diff --git a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp new file mode 100644 index 000000000..5973240df --- /dev/null +++ b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + string smallestBeautifulString(string s, int k) + { + string temp = s; + int n = s.size(); + int flag = 0; + for (int i=n-1; i>=0; i--) + { + for (char ch=s[i]+1; ch<'a'+k; ch++) + { + if (!checkOK(s, i, ch)) continue; + flag = 1; + s[i] = ch; + for (int j=i+1; j=0 && s[i-1]==ch) return false; + if (i-2>=0 && s[i-2]==ch) return false; + return true; + } +}; From c5d9363709c0eb3f1f51a600f063ebde2e802718 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 10:25:50 -0700 Subject: [PATCH 1845/2729] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index a58d4b55e..eae121981 100644 --- a/Readme.md +++ b/Readme.md @@ -1156,8 +1156,6 @@ [2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) -[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) -[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) @@ -1228,6 +1226,10 @@ [2551.Put-Marbles-in-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2551.Put-Marbles-in-Bags) (M+) [2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) +* ``Lexicographical Sequence`` +[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) +[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) +[2663.Lexicographically-Smallest-Beautiful-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2663.Lexicographically-Smallest-Beautiful-String) (H-) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From 267d334b52e6fd9a6c142a8428c38f9e65f11d93 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 10:47:48 -0700 Subject: [PATCH 1846/2729] Update 2663.Lexicographically-Smallest-Beautiful-String.cpp --- ...ographically-Smallest-Beautiful-String.cpp | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp index 5973240df..6a98eb1af 100644 --- a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp +++ b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp @@ -2,7 +2,7 @@ class Solution { public: string smallestBeautifulString(string s, int k) { - string temp = s; + string original = s; int n = s.size(); int flag = 0; for (int i=n-1; i>=0; i--) @@ -10,32 +10,34 @@ class Solution { for (char ch=s[i]+1; ch<'a'+k; ch++) { if (!checkOK(s, i, ch)) continue; - flag = 1; s[i] = ch; + for (int j=i+1; j=0 && s[i-1]==ch) return false; - if (i-2>=0 && s[i-2]==ch) return false; + if (i>=1 && s[i-1]==ch) return false; + if (i>=2 && s[i-2]==ch) return false; return true; } }; From f7b51fdd4382ff4585a8b72b22cdc59cff66d161 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:10:50 -0700 Subject: [PATCH 1847/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md diff --git a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md new file mode 100644 index 000000000..93c58153e --- /dev/null +++ b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md @@ -0,0 +1,7 @@ +### 2663.Lexicographically-Smallest-Beautiful-String + +本题的关键就是如何解读“不能出现回文子串”。其实这个约束可以简化为“没有任何两个相邻的字符相同”,且“没有任何长度为3的子串里第一个和第三个字符相同”。 + +然后我们就可以贪心地从低位往高位遍历,查看某位置i上能否填写一个比原先更大的字符,且满足上述的约束。如果可以,那么我们必然会尝试贪心地将[i+1:n-1]这一段构造为字典序最小、且符合约束的字符串。事实上,我们总是能构造成功的,因为在任何的位置上,我们只有两个约束(不能与前一个字符相同,不能与前前字符相同),但是`k>=4`,我们至少可以有四种候选。故这样的构造必然存在。 + +因此,只要我们从低位往高位遍历,找到第一个实现上述构造(即s[i]和s[i+1:n-1]都满足条件)的位置,那么就有了最终答案。 From 81fd5d4c6079ab0c8ce7d293cccdc6b6404b8776 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:11:33 -0700 Subject: [PATCH 1848/2729] Update Readme.md --- .../2663.Lexicographically-Smallest-Beautiful-String/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md index 93c58153e..d03848765 100644 --- a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md +++ b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md @@ -2,6 +2,6 @@ 本题的关键就是如何解读“不能出现回文子串”。其实这个约束可以简化为“没有任何两个相邻的字符相同”,且“没有任何长度为3的子串里第一个和第三个字符相同”。 -然后我们就可以贪心地从低位往高位遍历,查看某位置i上能否填写一个比原先更大的字符,且满足上述的约束。如果可以,那么我们必然会尝试贪心地将[i+1:n-1]这一段构造为字典序最小、且符合约束的字符串。事实上,我们总是能构造成功的,因为在任何的位置上,我们只有两个约束(不能与前一个字符相同,不能与前前字符相同),但是`k>=4`,我们至少可以有四种候选。故这样的构造必然存在。 +然后我们就可以贪心地从低位往高位遍历,查看某位置i上能否填写一个比原先更大的字符,且满足上述的约束。如果可以,那么我们必然会尝试贪心地将[i+1:n-1]这一段构造为字典序最小、且符合约束的字符串。事实上,我们总是能构造成功的,因为在任何的位置上,我们只有两个约束(不能与前一个字符相同,不能与前前字符相同),但是`k>=4`,我们至少可以有四种候选。故这样的贪心构造法必然能实现,且保证字典序最小。 因此,只要我们从低位往高位遍历,找到第一个实现上述构造(即s[i]和s[i+1:n-1]都满足条件)的位置,那么就有了最终答案。 From 4685cbf037a8e5baff570d34847757c235f329d1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:15:43 -0700 Subject: [PATCH 1849/2729] Create 2659.Make-Array-Empty.cpp --- .../2659.Make-Array-Empty.cpp | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Segment_Tree/2659.Make-Array-Empty/2659.Make-Array-Empty.cpp diff --git a/Segment_Tree/2659.Make-Array-Empty/2659.Make-Array-Empty.cpp b/Segment_Tree/2659.Make-Array-Empty/2659.Make-Array-Empty.cpp new file mode 100644 index 000000000..8fea5b15d --- /dev/null +++ b/Segment_Tree/2659.Make-Array-Empty/2659.Make-Array-Empty.cpp @@ -0,0 +1,91 @@ +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; + long long M = 1e9+7; + + void init(int N) + { + this->N = N; + bitArr.resize(N+1); + nums.resize(N+1); + } + + // increase nums[i] by delta + void updateDelta(int i, long long delta) { + int idx = i; + while (idx <= N) + { + bitArr[idx]+=delta; + // bitArr[idx] %= M; + idx+=idx&(-idx); + } + } + + // sum of a range nums[1:j] inclusively + long long queryPreSum(int idx){ + long long result = 0; + while (idx){ + result += bitArr[idx]; + // result %= M; + idx-=idx&(-idx); + } + return result; + } + + // sum of a range nums[i:j] inclusively + long long sumRange(int i, int j) + { + if (i>j) return 0; + return queryPreSum(j)-queryPreSum(i-1); + } +}; + + +class Solution { +public: + long long countOperationsToEmptyArray(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + BIT bit; + bit.init(n+10); + + for (int i=1; i<=n; i++) + { + bit.updateDelta(i, 1); + } + + mapMap; + for (int i=1; i<=n; i++) + Map[nums[i]] = i; + + long long ret = 0; + int last_p = -1; + for (auto& [v, p]: Map) + { + if (last_p==-1) + { + ret += bit.sumRange(1, p-1); + last_p = p; + bit.updateDelta(p, -1); + continue; + } + + if (last_p <= p) + { + ret += bit.sumRange(last_p, p-1); + } + else + { + ret += bit.sumRange(1, p-1); + ret += bit.sumRange(last_p+1, n); + } + last_p = p; + bit.updateDelta(p, -1); + } + + return ret + n; + } +}; From 1aea045edd2ac41a7de029edd884a46488cf3ce2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:16:16 -0700 Subject: [PATCH 1850/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index eae121981..18211a471 100644 --- a/Readme.md +++ b/Readme.md @@ -321,6 +321,7 @@ [1649.Create-Sorted-Array-through-Instructions](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions) (H) [2031.Count-Subarrays-With-More-Ones-Than-Zeros](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros) (H) [2179.Count-Good-Triplets-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2179.Count-Good-Triplets-in-an-Array) (H) +[2659.Make-Array-Empty](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2659.Make-Array-Empty) (H) #### [Design](https://github.com/wisdompeak/LeetCode/tree/master/Design) [380.Insert-Delete-GetRandom-O(1)](https://github.com/wisdompeak/LeetCode/tree/master/Design/380.Insert-Delete-GetRandom-O-1/) (M+) From 52475656a7fc2f2d2a5dfc30566fdb38c7362292 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:34:52 -0700 Subject: [PATCH 1851/2729] Create Readme.md --- Segment_Tree/2659.Make-Array-Empty/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Segment_Tree/2659.Make-Array-Empty/Readme.md diff --git a/Segment_Tree/2659.Make-Array-Empty/Readme.md b/Segment_Tree/2659.Make-Array-Empty/Readme.md new file mode 100644 index 000000000..deab212a3 --- /dev/null +++ b/Segment_Tree/2659.Make-Array-Empty/Readme.md @@ -0,0 +1,11 @@ +2659.Make-Array-Empty + +假设一个序列里面前三个最小的元素是x,y,z,他们在序列中的位置如下:`***x****z****y*****` + +首先我们必然会x,它是第一个会被消除的元素,那么在x之前的元素我们都会挪动到最后。所以操作的次数是x之前的元素的个数。 + +其次我们需要消除y,那么所有在x与y之间的元素都会被挪动到最后。所需要的操作次数也就是x与y之间的元素的个数。 + +接着我们需要消除z。注意在上一步之后,所有在y之前的元素都已经被挪到最后去了。想要消除z,必须先挪动从y+1到z-1之间的元素,其实是一个wrap around的过程。从原始序列上看,因为z的位置在y的前面,那么我们需要挪动的元素其实包含了[y+1,n-1]以及[0:z-1]两部分。特别注意,我们要扣除掉x,因为它已经被消除了。 + +所以这就提示我们可以用线段树或者BIT,支持任意单个元素的删减操作,并可以高效求出任意一段区间内的剩余元素个数。 From d6f391a2919b49e057df7eb42131d6762f75de78 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:39:39 -0700 Subject: [PATCH 1852/2729] Update BIT.cpp --- Template/Binary_Index_Tree/BIT.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/Binary_Index_Tree/BIT.cpp b/Template/Binary_Index_Tree/BIT.cpp index 576d03984..ee395e497 100644 --- a/Template/Binary_Index_Tree/BIT.cpp +++ b/Template/Binary_Index_Tree/BIT.cpp @@ -41,7 +41,7 @@ class BIT{ }; int main() - { +{ int N = 100000; BIT bit; bit.init(N); @@ -50,6 +50,6 @@ int main() for (int i=1; i Date: Sat, 27 May 2023 12:10:19 -0700 Subject: [PATCH 1853/2729] Create 2709.Greatest-Common-Divisor-Traversal.cpp --- ...2709.Greatest-Common-Divisor-Traversal.cpp | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 Union_Find/2709.Greatest-Common-Divisor-Traversal/2709.Greatest-Common-Divisor-Traversal.cpp diff --git a/Union_Find/2709.Greatest-Common-Divisor-Traversal/2709.Greatest-Common-Divisor-Traversal.cpp b/Union_Find/2709.Greatest-Common-Divisor-Traversal/2709.Greatest-Common-Divisor-Traversal.cpp new file mode 100644 index 000000000..496887207 --- /dev/null +++ b/Union_Find/2709.Greatest-Common-Divisor-Traversal/2709.Greatest-Common-Divisor-Traversal.cpp @@ -0,0 +1,89 @@ +class Solution { +public: + int Father[2*100005]; + + + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (x>y) Father[y] = x; + else Father[x] = y; + } + + vectorEratosthenes(int n) + { + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); + } + return primes; + } + + bool canTraverseAllPairs(vector& nums) + { + int MX = *max_element(nums.begin(), nums.end()); + vectorprimes = Eratosthenes(MX); + int M = primes.size(); + + int N = nums.size(); + unordered_mapidx; + for (int j=0; j x) break; + if (p*p > x) + { + if (FindFather(i)!=FindFather(N+idx[x])) + Union(i, N+idx[x]); + break; + } + + if (x%p==0) + { + if (FindFather(i)!=FindFather(N+j)) + Union(i, N+j); + while (x%p==0) + x /= p; + } + } + } + + for (int i=0; i Date: Sat, 27 May 2023 12:10:45 -0700 Subject: [PATCH 1854/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 18211a471..d20340302 100644 --- a/Readme.md +++ b/Readme.md @@ -997,6 +997,7 @@ [952.Largest-Component-Size-by-Common-Factor](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/952.Largest-Component-Size-by-Common-Factor) (H) [1627.Graph-Connectivity-With-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1627.Graph-Connectivity-With-Threshold) (M+) [1998.GCD-Sort-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1998.GCD-Sort-of-an-Array) (H-) +[2709.Greatest-Common-Divisor-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2709.Greatest-Common-Divisor-Traversal) (H-) * ``MST`` [1135.Connecting-Cities-With-Minimum-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1135.Connecting-Cities-With-Minimum-Cost) (M+) [1168.Optimize-Water-Distribution-in-a-Village](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1168.Optimize-Water-Distribution-in-a-Village) (H-) From 7b04ec4388ace1cd7bec280cb93e8dc5267682c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 27 May 2023 12:21:19 -0700 Subject: [PATCH 1855/2729] Create Readme.md --- Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md diff --git a/Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md b/Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md new file mode 100644 index 000000000..3a176228c --- /dev/null +++ b/Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md @@ -0,0 +1,5 @@ +### 2709.Greatest-Common-Divisor-Traversal + +很显然,我们不会把所有元素两两进行考察GCD,那样会是n^2的复杂度。我们会对每个元素nums[i]进行分解质因数,将nums[i]和它的所有质因数进行Union。最终考察所有的元素是否被union到了一起。 + +对每个元素nums[i]进行因数分解需要的时间复杂度是sqrt(M),其中M是数值范围1e5。更准确一些,如果是质因数分解的话,需要搜索的次数是sqrt(M)范围内的质数的个数。考虑到sqrt(100000)以内的质数大概是300个,最多尝试300次就可以完成对一个数的质因数分解。所以总的时间复杂度大约是o(300n). From b07816864aca0e79acc933e198938e3eca63a4e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 May 2023 10:25:58 -0700 Subject: [PATCH 1856/2729] Create 2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp --- ...m-Strictly-Inreasing-Cells-in-a-Matrix.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp diff --git a/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp new file mode 100644 index 000000000..f23bc8079 --- /dev/null +++ b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp @@ -0,0 +1,42 @@ +using AI3 = array; +using PII = pair; +class Solution { +public: + int maxIncreasingCells(vector>& mat) + { + int m = mat.size(), n = mat[0].size(); + vector>rows(m); + vector>cols(n); + vectornums; + for (int i=0; isecond + 1); + + iter = cols[j].lower_bound(val); + ret = max(ret, prev(iter)->second + 1); + + rows[i][val] = max(rows[i][val], ret); + cols[j][val] = max(cols[j][val], ret); + + ans = max(ans, ret); + } + + return ans; + + } +}; From 3c921f39a05158da2027ebf876d3e54b74c5c09f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 May 2023 10:26:24 -0700 Subject: [PATCH 1857/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d20340302..0c3aeed80 100644 --- a/Readme.md +++ b/Readme.md @@ -689,6 +689,7 @@ [2338.Count-the-Number-of-Ideal-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays) (H) [2431.Maximize-Total-Tastiness-of-Purchased-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits) (M+) [2484.Count-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences) (H-) +[2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 7924679ad69b49601675dcd9c68cac75b15ad56b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 May 2023 10:50:02 -0700 Subject: [PATCH 1858/2729] Update 2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp --- ...m-Strictly-Inreasing-Cells-in-a-Matrix.cpp | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp index f23bc8079..ab794e709 100644 --- a/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp +++ b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp @@ -1,42 +1,42 @@ using AI3 = array; -using PII = pair; class Solution { public: int maxIncreasingCells(vector>& mat) { int m = mat.size(), n = mat[0].size(); - vector>rows(m); - vector>cols(n); vectornums; for (int i=0; i> rows(m); + vector> cols(n); + for (int i=0; isecond + 1); - + iter = prev(iter); + len = max(len, iter->second + 1); + iter = cols[j].lower_bound(val); - ret = max(ret, prev(iter)->second + 1); - - rows[i][val] = max(rows[i][val], ret); - cols[j][val] = max(cols[j][val], ret); - - ans = max(ans, ret); + iter = prev(iter); + len = max(len, iter->second + 1); + + rows[i][val] = max(len, rows[i][val]); + cols[j][val] = max(len, cols[j][val]); + + ret = max(ret, len); } - - return ans; - + + return ret; } }; From 8c958a3842186487d4a44d854c9e6efc6c05a365 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 May 2023 17:33:36 -0700 Subject: [PATCH 1859/2729] Create Reamdme.md --- .../Reamdme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/Reamdme.md diff --git a/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/Reamdme.md b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/Reamdme.md new file mode 100644 index 000000000..71a10c72e --- /dev/null +++ b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/Reamdme.md @@ -0,0 +1,7 @@ +### 2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix + +我们肯定是将所有的元素排序之后逐个处理。对于(i,j)考虑以它为结尾的递增序列可以多少长,必然会查看序列里它之前的元素,而前一个元素必然是在同一行或者同一列。所以我们只要在同行同列里查找所有比`mat[i][j]`小的位置(x,y)。以(x,y)为结尾的递增序列可以多少长,那么以(i,j)为结尾的递增序列长度就可以增加1。问题就转化为了递归或者动态规划。 + +接下来的问题是,如果扫描同行同列的所有元素,那么总的时间复杂度是`o(MN*M)`。事实上我们只需要查看同行(或者同列)里元素值恰好比`mat[i][j]`小的位置和对应的序列长度即可。所以我们给每行(以及每列)维护一个key有序的map,比如`rows[i][v] = 3`表示第三行里,以值为v的格子为结尾的递增序列的最大长度是3. 所以对于(i,j),我们用`prev(rows[i].lower_bound(mat[i][j])`就能定位最后一个恰好比mat[i][j]`小的位置。 + +注意在对所有的rows[i]和cols[j],初始化的时候添加一个`{INT_MIN, 0}`的key-val对,可以避免lower_bound出现越界。 From 9536687deed33a668f3188684d356f0540e01d00 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 11:08:05 -0700 Subject: [PATCH 1860/2729] Create 2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp --- ....Minimum-Cost-to-Make-All-Characters-Equal.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp new file mode 100644 index 000000000..9a47b6cfb --- /dev/null +++ b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp @@ -0,0 +1,15 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(string s) + { + int n = s.size(); + long long ret = 0; + for (int i=1; i Date: Mon, 29 May 2023 11:09:19 -0700 Subject: [PATCH 1861/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0c3aeed80..3499c220e 100644 --- a/Readme.md +++ b/Readme.md @@ -1341,6 +1341,7 @@ [2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) +[2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 213b4e0bac6d7d487f2334d4fceb39fcf6d5b965 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 11:14:29 -0700 Subject: [PATCH 1862/2729] Create Readme.md --- .../2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md new file mode 100644 index 000000000..3e28f7933 --- /dev/null +++ b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md @@ -0,0 +1,5 @@ +### 2712.Minimum-Cost-to-Make-All-Characters-Equal + +我们考察每一处`s[i-1]!=s[i]`的交界点,为了使他们相等个,我们必须在此处做一次翻转,要么将左边子串全部翻转,要么将右边子串全部翻转,否则无法使得元素相等。 + +那么选择哪一边翻转呢?从贪心的角度来说,会选择较短的一边翻转。但是这样的贪心会带来什么影响呢?其实没有,选择任何一边进行翻转,都不会改变其他交界点依然需要翻转的事实,以及翻转的策略(即要么将左边子串全部翻转,要么将右边子串全部翻转)。既然如此,索性贪心的策略就是最佳的。 From 1ec668f8dc07b9a26a69c5152ea45a6816240b85 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 11:52:29 -0700 Subject: [PATCH 1863/2729] Create 2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp --- ...m-Cost-to-Make-All-Characters-Equal_v2.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp new file mode 100644 index 000000000..007267e64 --- /dev/null +++ b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp @@ -0,0 +1,67 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(string s) + { + LL ret1 = solve(s); + for (int i=0; ileft(n); + int lastOne = -1; + LL sum = 0; + for (int i=0; i=1 && s[i-1]=='1') + sum = sum+1; + else + sum += (i+1) + i; + + left[i] = sum; + lastOne = i; + } + + vectorright(n); + lastOne = n; + sum = 0; + for (int i=n-1; i>=0; i--) + { + if (s[i]=='0') + { + right[i] = sum; + continue; + } + + if (i+1 Date: Mon, 29 May 2023 11:52:41 -0700 Subject: [PATCH 1864/2729] Rename 2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp to 2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp --- ....cpp => 2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/{2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp => 2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp} (100%) diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp similarity index 100% rename from Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp rename to Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp From e7b1f542edce830401164dff3be8a49db1c788e5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 11:55:08 -0700 Subject: [PATCH 1865/2729] Update Readme.md --- .../2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md index 3e28f7933..6e3d09004 100644 --- a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md +++ b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md @@ -1,5 +1,9 @@ ### 2712.Minimum-Cost-to-Make-All-Characters-Equal +#### 解法1 我们考察每一处`s[i-1]!=s[i]`的交界点,为了使他们相等个,我们必须在此处做一次翻转,要么将左边子串全部翻转,要么将右边子串全部翻转,否则无法使得元素相等。 那么选择哪一边翻转呢?从贪心的角度来说,会选择较短的一边翻转。但是这样的贪心会带来什么影响呢?其实没有,选择任何一边进行翻转,都不会改变其他交界点依然需要翻转的事实,以及翻转的策略(即要么将左边子串全部翻转,要么将右边子串全部翻转)。既然如此,索性贪心的策略就是最佳的。 + +#### 解法2 +直观上肯定有一个分界点i,使得[0:i]的翻转一定都是选择左半边,[i+1:n-1]的翻转一定都是选择右半边。我们预处理得到left[i]表示将前缀i依靠左半边翻转都处理成0的最小代价,right[i]表示将后缀i依靠右半边翻转都处理成0的最小代价,然后找到全局最小的`left[i]+right[i+1]`即可。 From e5de569161f6830a2986617138d1e22102eee335 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 12:18:46 -0700 Subject: [PATCH 1866/2729] Create 2699.Modify-Graph-Edge-Weights.cpp --- .../2699.Modify-Graph-Edge-Weights.cpp | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Graph/2699.Modify-Graph-Edge-Weights/2699.Modify-Graph-Edge-Weights.cpp diff --git a/Graph/2699.Modify-Graph-Edge-Weights/2699.Modify-Graph-Edge-Weights.cpp b/Graph/2699.Modify-Graph-Edge-Weights/2699.Modify-Graph-Edge-Weights.cpp new file mode 100644 index 000000000..c9a2d2947 --- /dev/null +++ b/Graph/2699.Modify-Graph-Edge-Weights/2699.Modify-Graph-Edge-Weights.cpp @@ -0,0 +1,69 @@ +using PII = pair; +class Solution { + unordered_map next[105]; + int todo[105][105]; +public: + vector> modifiedGraphEdges(int n, vector>& edges, int source, int destination, int target) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], c=edge[2]; + if (c==-1) + { + c = 1; + todo[a][b] = 1; + todo[b][a] = 1; + } + next[a][b] = c; + next[b][a] = c; + } + + priority_queue, greater<>>pq; + vectordist1(n, INT_MAX/3); + + pq.push({0, destination}); + while (!pq.empty()) + { + auto [d, cur] = pq.top(); + pq.pop(); + if (dist1[cur]!=INT_MAX/3) continue; + dist1[cur] = d; + for (auto [nxt, weight]: next[cur]) + { + if (dist1[nxt]!=INT_MAX/3) continue; + pq.push({d+weight, nxt}); + } + } + + + vectordist(n, INT_MAX/3); + pq.push({0, source}); + while (!pq.empty()) + { + auto [d, cur] = pq.top(); + pq.pop(); + if (dist[cur]!=INT_MAX/3) continue; + dist[cur] = d; + if (cur==destination && d != target) return {}; + for (auto [nxt, weight]: next[cur]) + { + if (dist[nxt]!=INT_MAX/3) continue; + if (todo[cur][nxt]==1 && dist[cur]+weight+dist1[nxt] < target) + { + weight = target-dist[cur]-dist1[nxt]; + next[cur][nxt] = weight; + next[nxt][cur] = weight; + } + pq.push({d+weight, nxt}); + } + } + + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + edge[2] = next[a][b]; + } + + return edges; + } +}; From 327524707d091f5aadf9f88d00275fe0ed28b70f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 12:19:34 -0700 Subject: [PATCH 1867/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3499c220e..8658f4e25 100644 --- a/Readme.md +++ b/Readme.md @@ -1062,6 +1062,7 @@ [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) +[2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From b075e304ab761a598a1b46f55ee2d6fc6b686e64 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 15:28:44 -0700 Subject: [PATCH 1868/2729] Create Readme.md --- Graph/2699.Modify-Graph-Edge-Weights/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Graph/2699.Modify-Graph-Edge-Weights/Readme.md diff --git a/Graph/2699.Modify-Graph-Edge-Weights/Readme.md b/Graph/2699.Modify-Graph-Edge-Weights/Readme.md new file mode 100644 index 000000000..f1bd2a819 --- /dev/null +++ b/Graph/2699.Modify-Graph-Edge-Weights/Readme.md @@ -0,0 +1,9 @@ +### 2699.Modify-Graph-Edge-Weights + +因为最终修正边权之后的图里要求所有的边都是正数,所以我们第一步肯定先将所有能修改的边从-1改为为最小的正数值1放入图中。 + +最暴力的思想就是不停地跑Dijkstra求起点到终点的最短距离。如果当前的最短距离已经大于target,那么无解。如果当前的最短距离就是target,那么我们就不需要改动。如果当前的最短距离小于target,且最短距离里不包括任何可修改的边,那么也是无解。剩下的情况就是最短距离小于target,且其中包含了至少一条可修改的边,那么我们可以贪心地将该边权调大,使得路径恰为target。这样我们就消灭了一条小于target的路径。然后重复以上的过程。这样的算法可能会跑o(E)遍的Dijkstra,会TLE。 + +我们再审视一下我们的Dijkstra算法。注意当我们每次从PQ里弹出一个已经确定最短距离的的点,会尝试通过其邻接的边将一个新点加入PQ,如果我们所用到的所有的边都是不可修改的,那么我们弹出的点及其最短路径也都是不可修改的。但是当我们需要用到一条可修改的边时,比如说已知从起点到a的最短路径,然后a与b有一条可修改的边,此时我们在将b加入PQ时就会有所顾虑。如果“起点到a的最短距离”+“ab之间的边权1”+“b到终点的最短距离”小于target的话,那么我们就违反了题意。所以我们可以贪心地更改这条可修改边,使得三段距离之和变成target。这就意味着我们需要提前计算“b到终点的最短距离”。这样,当b收录进入PQ的时候,我们就保证了这条到达b的路径,不会造成任何“起点到终点的最短路径小于target”,我们可以放心地加入PQ共后续使用。 + +所以依据上面的算法,可以在一次的Dijkstra的过程中不断地贪心地设置可修改边的边权。知道我们发现终点从PQ里弹出时,意味着我们已经确定了起点到终点的最短距离。如果这个距离不为target,那么就是无解。 From 05fcfdfde5b0579ce94963a6c03301cb9ae31491 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 May 2023 19:28:18 -0700 Subject: [PATCH 1869/2729] Create 2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp --- ...perations-to-Make-Numbers-Non-positive.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp diff --git a/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp new file mode 100644 index 000000000..8b10248b8 --- /dev/null +++ b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minOperations(vector& nums, int x, int y) + { + sort(nums.rbegin(), nums.rend()); + int left = 0, right = INT_MAX/2; + while (left < right) + { + int mid = left+(right-left)/2; + if (isOK(mid, nums, x, y)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(int k, vector& nums, int x, int y) + { + int count = 0; + for (int i=0; i k) return false; + } + return true; + } +}; From 098b8fc30fcfe210df98553b0f0d3be498b8bd9d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 May 2023 19:28:47 -0700 Subject: [PATCH 1870/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8658f4e25..ae792d7b5 100644 --- a/Readme.md +++ b/Readme.md @@ -128,6 +128,7 @@ [2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) [2604.Minimum-Time-to-Eat-All-Grains](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains) (H-) [2616.Minimize-the-Maximum-Difference-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs) (H-) +[2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From d175f2fa76dde30aa790382ebd0b375ebf10aab7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 May 2023 19:36:01 -0700 Subject: [PATCH 1871/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/Readme.md diff --git a/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/Readme.md b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/Readme.md new file mode 100644 index 000000000..79d01f3e9 --- /dev/null +++ b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/Readme.md @@ -0,0 +1,5 @@ +### 2702.Minimum-Operations-to-Make-Numbers-Non-positive + +此题很容易知道贪心的策略,肯定是将当前数组里最大的元素减去x,其他元素减去y。然后不断重复处理。但问题是如此暴力的模拟,在时间复杂度上无法接受。 + +此时二分搜值的想法就比较容易。我们尝试判定m次操作是否能将所有元素都降到0以下。关键之处在于我们可以将每次操作拆分为:将全部元素减去y,再挑一个元素减去x-y。那么m次操作必然是将所有元素都减掉了m个y,此外我们还有m次操作将剩余没有变成0的元素减去x-y。我们只要贪心的查看这些操作是否够将所有元素变成0即可。 From 593202428c0ba5a0cde8601ff9bd66ad6c044722 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 May 2023 19:38:15 -0700 Subject: [PATCH 1872/2729] Update 2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp --- .../2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp index 8b10248b8..6a530d58b 100644 --- a/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp +++ b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp @@ -20,7 +20,8 @@ class Solution { int count = 0; for (int i=0; i k) return false; } return true; From 01da1ede6e31d29772c14c52dfa58a9022765cec Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Jun 2023 19:16:19 -0700 Subject: [PATCH 1873/2729] Create 2646.Minimize-the-Total-Price-of-the-Trips.cpp --- ....Minimize-the-Total-Price-of-the-Trips.cpp | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Recursion/2646.Minimize-the-Total-Price-of-the-Trips/2646.Minimize-the-Total-Price-of-the-Trips.cpp diff --git a/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/2646.Minimize-the-Total-Price-of-the-Trips.cpp b/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/2646.Minimize-the-Total-Price-of-the-Trips.cpp new file mode 100644 index 000000000..803fab38d --- /dev/null +++ b/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/2646.Minimize-the-Total-Price-of-the-Trips.cpp @@ -0,0 +1,94 @@ +class Solution { + vectornext[55]; + int n; + int count[55]; + int plan0[55]; + int plan1[55]; + int val[55]; +public: + int minimumTotalPrice(int n, vector>& edges, vector& price, vector>& trips) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + for (int i=0; i Date: Thu, 1 Jun 2023 19:17:49 -0700 Subject: [PATCH 1874/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ae792d7b5..33169d162 100644 --- a/Readme.md +++ b/Readme.md @@ -1012,6 +1012,7 @@ [133.Clone-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/133.Clone-Graph) (M+) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (H-) [337.House-Robber-III](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/337.House-Robber-III) (M+) +[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) [2378.Choose-Edges-to-Maximize-Score-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree) (H-) [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) From d03125b4fb24a70969248909584900fd91b67ac2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 2 Jun 2023 00:05:34 -0700 Subject: [PATCH 1875/2729] Create 2714.Find-Shortest-Path-with-K-Hops.cpp --- .../2714.Find-Shortest-Path-with-K-Hops.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 BFS/2714.Find-Shortest-Path-with-K-Hops/2714.Find-Shortest-Path-with-K-Hops.cpp diff --git a/BFS/2714.Find-Shortest-Path-with-K-Hops/2714.Find-Shortest-Path-with-K-Hops.cpp b/BFS/2714.Find-Shortest-Path-with-K-Hops/2714.Find-Shortest-Path-with-K-Hops.cpp new file mode 100644 index 000000000..ceaf49038 --- /dev/null +++ b/BFS/2714.Find-Shortest-Path-with-K-Hops/2714.Find-Shortest-Path-with-K-Hops.cpp @@ -0,0 +1,37 @@ +using AI3 = array; +using PII = pair; +class Solution { + vectornext[500]; +public: + int shortestPathWithHops(int n, vector>& edges, int source, int destination, int k) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], w = edge[2]; + next[a].push_back({b,w}); + next[b].push_back({a,w}); + } + priority_queue, greater<>>pq; + pq.push({0, source, k}); + + vector>dist(n, vector(k+1, INT_MAX/2)); + + while (!pq.empty()) + { + auto [d, cur, t] = pq.top(); + pq.pop(); + if (dist[cur][t]!=INT_MAX/2) continue; + dist[cur][t] = d; + if (cur==destination) return d; + + for (auto [nxt, weight]:next[cur]) + { + if (dist[nxt][t]==INT_MAX/2) + pq.push({d+weight, nxt, t}); + if (t>=1 && dist[nxt][t-1]==INT_MAX/2) + pq.push({d, nxt, t-1}); + } + } + return -1; + } +}; From f3acbba31f63524495e5d6925552761129f28027 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 2 Jun 2023 00:06:20 -0700 Subject: [PATCH 1876/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 33169d162..a9cf17047 100644 --- a/Readme.md +++ b/Readme.md @@ -591,6 +591,7 @@ [1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (M+) [2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) +[2714.Find-Shortest-Path-with-K-Hops](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2714.Find-Shortest-Path-with-K-Hops) (M+) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) From 2ed402c91fdd3242364e27ac2bd7c79d8384046c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 2 Jun 2023 00:11:59 -0700 Subject: [PATCH 1877/2729] Create Readme.md --- BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md diff --git a/BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md b/BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md new file mode 100644 index 000000000..e133f601f --- /dev/null +++ b/BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md @@ -0,0 +1,5 @@ +### 2714.Find-Shortest-Path-with-K-Hops + +此题和`2093.Minimum-Cost-to-Reach-City-With-Discounts`几乎一样。我们用Dijkstra求最短距离时需要有两个参量,即`dist[node][hops]`表示还剩hops机会时node离原点的最短距离。当某状态向量`(dist, node, hops)`弹出队列时,我们可以加入两种相邻的状态`{dist+weight, nxt, hops}`或者`{dist, nxt, hops-1}`. + +注意当PQ第一次弹出destination时,无论hops是多少,即可以输出最短距离。 From 3d18ae55882adab3d627a51fd2f166c509edc9bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Jun 2023 15:50:17 -0700 Subject: [PATCH 1878/2729] Create Readmd.md --- .../2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Recursion/2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md diff --git a/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md b/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md new file mode 100644 index 000000000..6b2f8f7b9 --- /dev/null +++ b/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md @@ -0,0 +1,9 @@ +### 2646.Minimize-the-Total-Price-of-the-Trips + +首先我们遍历所有的trip,记录每个节点被访问的次数count[i],这样每个节点的实际price就是`price[i]*count[i]`,也就是说没有访问过的节点其实不贡献price。 + +之后就是常见的house-robber的套路。对于每个节点node,我们考察“不可以取半价”和“可以取半价”两种状态下可以得到的子树的最小price,分别记做plan0[node]和plan1[node]。 + +如果node本身不可以取半价,那么自然它的所有孩子都可以取半价。即`plan0[node] = price[node] + sum(plan1[child])`. + +如果node本身可以取半价,那么它就对应两种策略:即真的取半价,对应地它的所有孩子都不可以取半价;或者它仍然不取半价,对应地它的所有孩子都可以取半价。两者取小为最优策略。以此递归下去求出每个节点的plan0和plan1. 即`plan0[node] = min(price[node] + sum(plan1[child]), price[node]/2 + sum(plan0[child])`. From 2bff93ded6167995a7392e17bb499e804418e9ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 17:23:39 -0700 Subject: [PATCH 1879/2729] Create 2719.Count-of-Integers.cpp --- .../2719.Count-of-Integers.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp diff --git a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp new file mode 100644 index 000000000..bce5776b3 --- /dev/null +++ b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp @@ -0,0 +1,58 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int count(string num1, string num2, int min_sum, int max_sum) + { + LL ret = (ValidNumbersNoGreaterThan(num2, max_sum)-ValidNumbersNoGreaterThan(num2, min_sum-1)) - (ValidNumbersNoGreaterThan(num1, max_sum)-ValidNumbersNoGreaterThan(num1, min_sum-1)); + + int digitSum = getDigitSum(num1); + if (digitSum>=min_sum && digitSum<=max_sum) ret = (ret+1) % M; + return ret; + } + + int getDigitSum(string s) + { + int ret = 0; + for (auto ch: s) ret += ch-'0'; + return ret; + } + + + LL ValidNumbersNoGreaterThan(string num, int max_sum) + { + vector>memo(25, vector(405, -1)); + return dfs(num, max_sum, 0, 0, memo, true); + } + + LL dfs(string num, int max_sum, int i, int sum, vector>&memo, int isSame) + { + if (sum > max_sum) return 0; + if (!isSame && memo[i][sum]!=-1) return memo[i][sum]; + if (i==num.size()) return 1; + + LL ret = 0; + if (!isSame) + { + for (int k=0; k<=9; k++) + { + ret += dfs(num, max_sum, i+1, sum+k, memo, false); + ret %= M; + } + } + else + { + for (int k=0; k Date: Sun, 4 Jun 2023 17:24:10 -0700 Subject: [PATCH 1880/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a9cf17047..d9147da36 100644 --- a/Readme.md +++ b/Readme.md @@ -1049,6 +1049,7 @@ [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) +[2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 47482c3eeb3e3da52f7054f2f7f3dfc54a3b81c5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 17:46:32 -0700 Subject: [PATCH 1881/2729] Create Readme.md --- Recursion/2719.Count-of-Integers/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Recursion/2719.Count-of-Integers/Readme.md diff --git a/Recursion/2719.Count-of-Integers/Readme.md b/Recursion/2719.Count-of-Integers/Readme.md new file mode 100644 index 000000000..4c29803cd --- /dev/null +++ b/Recursion/2719.Count-of-Integers/Readme.md @@ -0,0 +1,13 @@ +### 2719.Count-of-Integers + +求介于两个范围[low, high]之间的、符合条件的元素个数,一个非常常见的套路,就是只写一个求不高于某上界、符合条件的元素个数`NoGreaterThan`.这样答案就是`NoGreaterThan(high)-NoGreaterThan(low-1)`. + +本题有两个不同类型的范围限制,数值大小的范围和digitsum的范围。我们用同样的套路,写函数`NoGreaterThan(string num, int max_sum)`,求数值上不超过num,digitSum不超过max_sum的元素个数,这样最终答案就是 +``` +return (NoGreaterThan(num2, max_sum)-NoGreaterThan(num2, min_sum-1)) + - (NoGreaterThan(num1-1, max_sum)-NoGreaterThan(num1-1, min_sum-1)); +``` + +在编写`NoGreaterThan`的时候,我们递归考察num的每个位置,尝试可以填写哪些digits。用记忆化来避免重复的函数调用。 + +其中一个比较重要的逻辑就是,如果我们给前i位设置的digits比num对应前缀要小,那么第i位上我们可以任意设置0~9都可以满足要求(即不超过num)。反之,如果给前i位设置的digits与num的对应前缀完全吻合,那么在第i位上的设置就不能超过num[i]。所以递归的时候我们需要有一个bool量的标记,表示在处理当前位i之前,我们是否设置了完全与num前缀相同的digits。 From 470303b0611f911ca2ffe87e8a51c3782e00cb5a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 17:46:55 -0700 Subject: [PATCH 1882/2729] Update Readme.md --- Recursion/2719.Count-of-Integers/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/2719.Count-of-Integers/Readme.md b/Recursion/2719.Count-of-Integers/Readme.md index 4c29803cd..7feb9d6ee 100644 --- a/Recursion/2719.Count-of-Integers/Readme.md +++ b/Recursion/2719.Count-of-Integers/Readme.md @@ -10,4 +10,4 @@ return (NoGreaterThan(num2, max_sum)-NoGreaterThan(num2, min_sum-1)) 在编写`NoGreaterThan`的时候,我们递归考察num的每个位置,尝试可以填写哪些digits。用记忆化来避免重复的函数调用。 -其中一个比较重要的逻辑就是,如果我们给前i位设置的digits比num对应前缀要小,那么第i位上我们可以任意设置0~9都可以满足要求(即不超过num)。反之,如果给前i位设置的digits与num的对应前缀完全吻合,那么在第i位上的设置就不能超过num[i]。所以递归的时候我们需要有一个bool量的标记,表示在处理当前位i之前,我们是否设置了完全与num前缀相同的digits。 +其中一个比较重要的逻辑就是,如果我们给前i位设置的digits比num对应前缀要小,那么第i位上我们可以任意设置0~9都可以满足要求(即不超过num)。反之,如果给前i位设置的digits与num的对应前缀完全吻合,那么在第i位上的设置就不能超过num[i](否则就超过了num)。所以递归的时候我们需要有一个bool量的标记,表示在处理当前位i之前,我们是否设置了完全与num前缀相同的digits。 From f4223ca7d1b310c36eaa1ca89cf7220703355e1b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 17:51:57 -0700 Subject: [PATCH 1883/2729] Update 2719.Count-of-Integers.cpp --- .../2719.Count-of-Integers.cpp | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp index bce5776b3..1da880b8a 100644 --- a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp +++ b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp @@ -4,7 +4,7 @@ class Solution { public: int count(string num1, string num2, int min_sum, int max_sum) { - LL ret = (ValidNumbersNoGreaterThan(num2, max_sum)-ValidNumbersNoGreaterThan(num2, min_sum-1)) - (ValidNumbersNoGreaterThan(num1, max_sum)-ValidNumbersNoGreaterThan(num1, min_sum-1)); + LL ret = (CountNoGreaterThan(num2, max_sum)-CountNoGreaterThan(num2, min_sum-1)) - (CountNoGreaterThan(num1, max_sum)-CountNoGreaterThan(num1, min_sum-1)); int digitSum = getDigitSum(num1); if (digitSum>=min_sum && digitSum<=max_sum) ret = (ret+1) % M; @@ -19,16 +19,16 @@ class Solution { } - LL ValidNumbersNoGreaterThan(string num, int max_sum) + LL CountNoGreaterThan(string num, int max_sum) { - vector>memo(25, vector(405, -1)); - return dfs(num, max_sum, 0, 0, memo, true); + vector>>memo(2, vector>(25, vector(405, -1))); + return dfs(num, max_sum, 0, 0, true, memo); } - LL dfs(string num, int max_sum, int i, int sum, vector>&memo, int isSame) + LL dfs(string num, int max_sum, int i, int sum, int isSame, vector>>&memo) { if (sum > max_sum) return 0; - if (!isSame && memo[i][sum]!=-1) return memo[i][sum]; + if (memo[isSame][i][sum]!=-1) return memo[isSame][i][sum]; if (i==num.size()) return 1; LL ret = 0; @@ -36,7 +36,7 @@ class Solution { { for (int k=0; k<=9; k++) { - ret += dfs(num, max_sum, i+1, sum+k, memo, false); + ret += dfs(num, max_sum, i+1, sum+k, false, memo); ret %= M; } } @@ -44,14 +44,14 @@ class Solution { { for (int k=0; k Date: Sun, 4 Jun 2023 17:52:55 -0700 Subject: [PATCH 1884/2729] Update Readme.md --- Recursion/2719.Count-of-Integers/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Recursion/2719.Count-of-Integers/Readme.md b/Recursion/2719.Count-of-Integers/Readme.md index 7feb9d6ee..e578450c2 100644 --- a/Recursion/2719.Count-of-Integers/Readme.md +++ b/Recursion/2719.Count-of-Integers/Readme.md @@ -11,3 +11,5 @@ return (NoGreaterThan(num2, max_sum)-NoGreaterThan(num2, min_sum-1)) 在编写`NoGreaterThan`的时候,我们递归考察num的每个位置,尝试可以填写哪些digits。用记忆化来避免重复的函数调用。 其中一个比较重要的逻辑就是,如果我们给前i位设置的digits比num对应前缀要小,那么第i位上我们可以任意设置0~9都可以满足要求(即不超过num)。反之,如果给前i位设置的digits与num的对应前缀完全吻合,那么在第i位上的设置就不能超过num[i](否则就超过了num)。所以递归的时候我们需要有一个bool量的标记,表示在处理当前位i之前,我们是否设置了完全与num前缀相同的digits。 + +此外,对于cpp而言,我们比较难直接得到num-1的字符串形式。技巧是我们将num1单独处理即可。 From 34ae2b4c31474af6bbf66733e18c6196f187a1d1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 23:24:41 -0700 Subject: [PATCH 1885/2729] Create 2718.Sum-of-Matrix-After-Queries.cpp --- .../2718.Sum-of-Matrix-After-Queries.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Others/2718.Sum-of-Matrix-After-Queries/2718.Sum-of-Matrix-After-Queries.cpp diff --git a/Others/2718.Sum-of-Matrix-After-Queries/2718.Sum-of-Matrix-After-Queries.cpp b/Others/2718.Sum-of-Matrix-After-Queries/2718.Sum-of-Matrix-After-Queries.cpp new file mode 100644 index 000000000..4babc2cfa --- /dev/null +++ b/Others/2718.Sum-of-Matrix-After-Queries/2718.Sum-of-Matrix-After-Queries.cpp @@ -0,0 +1,32 @@ +using LL = long long; +class Solution { +public: + long long matrixSumQueries(int n, vector>& queries) + { + vectorrow(n, -1); + vectorcol(n, -1); + LL rowLeft = n; + LL colLeft = n; + LL ret = 0; + reverse(queries.begin(), queries.end()); + for (auto & q: queries) + { + int type = q[0], idx = q[1], val = q[2]; + if (type==0) + { + if (row[idx]!=-1) continue; + row[idx] = val; + ret += rowLeft * val; + colLeft--; + } + else + { + if (col[idx]!=-1) continue; + col[idx] = val; + ret += colLeft * val; + rowLeft--; + } + } + return ret; + } +}; From 03303e3353f5f20e5ec6ab01d3bb9c5e8e65c1ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 23:27:11 -0700 Subject: [PATCH 1886/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d9147da36..e02126e45 100644 --- a/Readme.md +++ b/Readme.md @@ -1396,6 +1396,7 @@ [2453.Destroy-Sequential-Targets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2453.Destroy-Sequential-Targets) (M) [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) +[2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 0792274b1ab76d59f7165ebf523d2165de6d3033 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 23:35:26 -0700 Subject: [PATCH 1887/2729] Create Readme.md --- Others/2718.Sum-of-Matrix-After-Queries/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2718.Sum-of-Matrix-After-Queries/Readme.md diff --git a/Others/2718.Sum-of-Matrix-After-Queries/Readme.md b/Others/2718.Sum-of-Matrix-After-Queries/Readme.md new file mode 100644 index 000000000..23cdc4007 --- /dev/null +++ b/Others/2718.Sum-of-Matrix-After-Queries/Readme.md @@ -0,0 +1,5 @@ +### 2718.Sum-of-Matrix-After-Queries + +很明显,后面的操作会覆盖前者,我们必然会从后往前复盘,这样已经被填充的格子就不会再更改,更方便分析。 + +假设我们第一步是将某一行填充数字a,那么我们发现,以后的任何一次列操作都只会影响到n-1个格子。再假设第二步是将某一列填充数字b,然后我们发现,以后的任何一次列操作也都只会影响到n-1个格子。所以我们只需要维护两个量来记录当前任何一行还剩多少格子需要填充,以及任何一列还剩多少格子需要填充,这样当我们复盘操作的时候,就可以知道实际该行或该列只增加了多少sum。 From a2ec4f133ba259eaf7817e372aaf1838932eaa3d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 7 Jun 2023 18:03:14 -0700 Subject: [PATCH 1888/2729] Create 2612.Minimum-Reverse-Operations.cpp --- .../2612.Minimum-Reverse-Operations.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp diff --git a/Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp b/Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp new file mode 100644 index 000000000..d4f90937b --- /dev/null +++ b/Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + vector minReverseOperations(int n, int p, vector& banned, int k) + { + setodd; + seteven; + setbanned_set(banned.begin(), banned.end()); + for (int i=0; iq; + q.push(p); + vectorrets(n, -1); + rets[p] = 0; + + int step = 0; + while (!q.empty()) + { + step++; + int len = q.size(); + while (len--) + { + int i = q.front(); + q.pop(); + int L0 = max(0, i-k+1); + int j0 = (2*L0+k-1)-i; + + int L1 = min(n-k, i); + int j1 = (2*L1+k-1)-i; + + set*s; + if (j0%2==0) s = &even; + else s = &odd; + + auto iter = s->lower_bound(j0); + while (iter!=s->end() && *iter<=j1) + { + rets[*iter] = step; + q.push(*iter); + s->erase(iter++); + } + } + } + + return rets; + } +}; From 510715ebe07b83e5105e0581a13b9f5252d97deb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 7 Jun 2023 18:04:07 -0700 Subject: [PATCH 1889/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e02126e45..473a48c3b 100644 --- a/Readme.md +++ b/Readme.md @@ -209,6 +209,7 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) +[2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) From c064b788513e8f16e4c4863335a19e65c9147bde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 7 Jun 2023 19:03:05 -0700 Subject: [PATCH 1890/2729] Create Readme.md --- Heap/2612.Minimum-Reverse-Operations/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Heap/2612.Minimum-Reverse-Operations/Readme.md diff --git a/Heap/2612.Minimum-Reverse-Operations/Readme.md b/Heap/2612.Minimum-Reverse-Operations/Readme.md new file mode 100644 index 000000000..9a8588740 --- /dev/null +++ b/Heap/2612.Minimum-Reverse-Operations/Readme.md @@ -0,0 +1,9 @@ +### 2612.Minimum-Reverse-Operations + +此题类似于jump game,从起点开始,根据滑窗的不同位置,可以将1移动到多个不同的地方。然后下一轮,再根据滑窗的不同位置,可以将1继续移动到不同的地方。依次类推,可以用BFS求出1到达各个位置所用的最短步数(也就是用了几轮BFS)。 + +我们假设1的初始位置是i,滑窗的左右边界是L和R(且`R-L+1=k`),那么1就可以通过翻转从i到新位置`j = L+R-i = 2*L-i-1`,这是一个仅关于L的函数。考虑滑窗长度固定,且必须包含位置i,所以L的最左边可以到达`i-k+1`,最右边可以到达`i`。此外,L不能越界,即必须在[0,n-1]内,所以L的左边界其实是`L0=max(0,i-k+1)`,右边界其实是`min(i,n-1)`. 于是对应的j的移动范围就是`2*L0-i-1`到`2*L1-i-1`之间,并且随着L从小到大移动,j的变动始终是+2. + +我们在尝试进行BFS的时候,最大的问题就是,我们通过i进行一次revert得到的j会有很多位置(因为滑窗可以运动),其中很多j可能是之前已经遍历过的(也就是已经确定了一个更少的步数就可以到达),我们需要挨个检验的话时间复杂度就会很高。本题有巧解。对于一次revert,j的候选点的编号要么都是同奇数(要么都是偶数),并且在奇数(或者偶数)意义上是连续的!所以我们事先将所有编号是奇数的点作为一个集合odd,将所有编号是偶数的点作为一个集合even,那么这次revert相当于在odd(或者even)上删除一段区间range(删除意味着遍历过)。只要集合是有序的,那么我们就可以很快定位到range在集合里的位置,将range在集合里面的元素都删除。因为每个元素只会在集合里最多被删除一次(以后的range定位都不会涉及已经删除的元素),所以我们可以用近乎线性的时间知道每个元素是在什么时候从集合里删除的,这就是可以到达的最小步数。 + +对于banned里面的元素,只需要实现从odd和even里排除即可。 From e23355fd167e496ad33e7efeab23957be638d346 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 8 Jun 2023 22:41:15 -0700 Subject: [PATCH 1891/2729] Update 307.Range-Sum-Query-Mutable_BIT.cpp --- .../307.Range-Sum-Query-Mutable_BIT.cpp | 81 +++++++++++++------ 1 file changed, 58 insertions(+), 23 deletions(-) diff --git a/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp b/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp index e738ea721..db7a5ddb3 100644 --- a/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp +++ b/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp @@ -1,41 +1,76 @@ -class NumArray { -public: - vectorbitArr; - vectornums; +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; + long long M = 1e9+7; - NumArray(vector& nums) { - this->nums = nums; - bitArr.resize(nums.size()+1); - for (int i=0; iN = N; + bitArr.resize(N+1); + nums.resize(N+1); } - void update(int i, int val){ - my_update(i, val-nums[i]); - nums[i] = val; - } - - void my_update(int i, int delta) { - int idx = i+1; - while (idxnums; +public: + NumArray(vector& nums) + { + this->nums = nums; + int n = nums.size(); + bit.init(n+10); + + for (int i=0; iupdate(index,val); + * int param_2 = obj->sumRange(left,right); + */ From d78d7ed9fd212232ec37778478230e5ecb468135 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 10:16:39 -0700 Subject: [PATCH 1892/2729] Create 2731.Movement-of-Robots.cpp --- .../2731.Movement-of-Robots.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp diff --git a/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp b/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp new file mode 100644 index 000000000..10e1ea152 --- /dev/null +++ b/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp @@ -0,0 +1,30 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int sumDistance(vector& nums, string s, int d) + { + int n = nums.size(); + vectorpos; + for (int i=0; i Date: Sat, 10 Jun 2023 10:18:50 -0700 Subject: [PATCH 1893/2729] Update Readme.md --- Readme.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Readme.md b/Readme.md index 473a48c3b..f1c471a76 100644 --- a/Readme.md +++ b/Readme.md @@ -1398,6 +1398,9 @@ [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) +* ``Physics`` +1503. Last Moment Before All Ants Fall Out of a Plank (M) +[2731.Movement-of-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Others/2731.Movement-of-Robots) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 0df80de4c8774288bb8fdb8bf495d97f66c01ec9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 10:46:34 -0700 Subject: [PATCH 1894/2729] Create Readmd.md --- Others/2731.Movement-of-Robots/Readmd.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2731.Movement-of-Robots/Readmd.md diff --git a/Others/2731.Movement-of-Robots/Readmd.md b/Others/2731.Movement-of-Robots/Readmd.md new file mode 100644 index 000000000..6f8a06a4e --- /dev/null +++ b/Others/2731.Movement-of-Robots/Readmd.md @@ -0,0 +1,7 @@ +### 2731.Movement-of-Robots + +本题的关键点有两处。 + +首先,任何A与B“弹性碰撞”的后果,都可以虚拟地认为是A和B不受变化地按照原方向、原速率继续前进,只不过A和B的真实身份互换了一下。所以我们只需要计算每个robot按照初始方向前进d之后的位置,得到的新的坐标数组,排序之后就是所有robot的最终坐标。 + +其次,计算`the sum of distances between all the pairs of robots`时,最简单的计数方法就是考察每一段相邻机器人之间的距离s。如果该间隔左边有x个机器人,右边有y个机器人,那么这段s将会被重复计数`x*y`次。所以依次考察所有相邻间距即可。 From d0d25c618c88269e7fb7eeb4ab6c7ca5d76ed99b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:14:54 -0700 Subject: [PATCH 1895/2729] Create 2732.Find-a-Good-Subset-of-the-Matrix.cpp --- .../2732.Find-a-Good-Subset-of-the-Matrix.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp b/Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp new file mode 100644 index 000000000..f7863611b --- /dev/null +++ b/Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + vector goodSubsetofBinaryMatrix(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + unordered_map>Map; + for (int i=0; i>j)&1)) + { + flag = 0; + break; + } + } + if (flag==0) continue; + if (Map[s].size()==0) continue; + + for (int k: Map[s]) + { + if (k!=i) + { + vectorrets({i,k}); + sort(rets.begin(), rets.end()); + return rets; + } + } + } + } + + return {}; + } +}; From be0f7faecee62b1ce5e44a5bdd2fe0852dfeb714 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:37:51 -0700 Subject: [PATCH 1896/2729] Create Readmd.md --- .../2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md b/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md new file mode 100644 index 000000000..daa971062 --- /dev/null +++ b/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md @@ -0,0 +1,13 @@ +### 2732.Find-a-Good-Subset-of-the-Matrix + +我们将每行用一个最多含5 bit的二进制数编码来表示它的每个列位置是0还是1. 为了增大复杂度,我们令列数是5. + +首先,我们考虑两种特殊情况。如果有一行的编码是0,那么它自身组成的集合就符合条件。另外,如果有两行的编码的“交集”为零,那么这两行组成的集合也符合条件。 + +接下来考虑,如果任何两行的state的交集都不为0,那么会出现什么情况。 + +我们可以知道,想要有解,至少存在一行,最多含有两个bit 1. 理由是,如果所有的行都存在三个或以上的bit 1,那么无论选取哪些k行,总的bit 1的数就是大于等于3k,但是根据题意“任何一列的bit 1的数目不能超过行数的一半”,即总的bit 1的数目不能超过`0.5k*5=2.5k`,从而产生矛盾。不失一般性地,我们可以令某一行的编码是b00011。 + +回到之前的前提,“如果任何两行的编码的交集都不为0”,那么其他选取的k-1行里,在第0和1的位置上至少有一个bit 1。于是总体的这k行里,就有了至少k+1个bit 1。这就说明了在第0和1的位置上,不可能有任何一列的bit 1的个数少于等于`floor(k/2)`。得到矛盾,因此“任何两行的编码交集都不为0”情况下,是不可能有解的。 + +综上,我们只需要考察之前所述的两种特殊情况即可找出解,或者判定无解。对于第二种特殊情况,我们建立`编码->行号`的映射,就可以知道对于行A而言,是否存在与之符合条件的行B了。 From a0e00837a03968b8df501815a55f8e492b1f7514 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:38:31 -0700 Subject: [PATCH 1897/2729] Rename Readmd.md to Readme.md --- .../{Readmd.md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2732.Find-a-Good-Subset-of-the-Matrix/{Readmd.md => Readme.md} (100%) diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md b/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md similarity index 100% rename from Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md rename to Math/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md From a36541ec5af6fd1e132e301ddfe4b306942553c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:39:18 -0700 Subject: [PATCH 1898/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f1c471a76..752ae4a32 100644 --- a/Readme.md +++ b/Readme.md @@ -1348,6 +1348,7 @@ [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) +[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Math/2732.Find-a-Good-Subset-of-the-Matrix) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From b979378955d1206f9cdce5e29470ce9b3516077e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:49:51 -0700 Subject: [PATCH 1899/2729] Rename Readme.md to Readme.md --- {Math => Greedy}/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Math => Greedy}/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md (100%) diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md b/Greedy/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md similarity index 100% rename from Math/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md rename to Greedy/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md From 5e42bb4e2952a32b94d02411fdfaf2b169497b2e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:50:28 -0700 Subject: [PATCH 1900/2729] Rename 2732.Find-a-Good-Subset-of-the-Matrix.cpp to 2732.Find-a-Good-Subset-of-the-Matrix.cpp --- .../2732.Find-a-Good-Subset-of-the-Matrix.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Math => Greedy}/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp (100%) diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp b/Greedy/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp similarity index 100% rename from Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp rename to Greedy/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp From 2bc53b402e9152f640afa3fdcaf8dbfaa5ca7aff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:50:46 -0700 Subject: [PATCH 1901/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 752ae4a32..b9250647a 100644 --- a/Readme.md +++ b/Readme.md @@ -1348,7 +1348,7 @@ [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) -[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Math/2732.Find-a-Good-Subset-of-the-Matrix) (H) +[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From b4636e2d926928dc625588f6cab7455e5b1957aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 22:41:06 -0700 Subject: [PATCH 1902/2729] Update 2719.Count-of-Integers.cpp --- .../2719.Count-of-Integers.cpp | 49 ++++++++++--------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp index 1da880b8a..fc28f6661 100644 --- a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp +++ b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp @@ -4,33 +4,35 @@ class Solution { public: int count(string num1, string num2, int min_sum, int max_sum) { - LL ret = (CountNoGreaterThan(num2, max_sum)-CountNoGreaterThan(num2, min_sum-1)) - (CountNoGreaterThan(num1, max_sum)-CountNoGreaterThan(num1, min_sum-1)); - - int digitSum = getDigitSum(num1); - if (digitSum>=min_sum && digitSum<=max_sum) ret = (ret+1) % M; - return ret; + LL ret = (CountNoGreater(num2, max_sum) - CountNoGreater(num2, min_sum-1) + M) % M +- (CountNoGreater(num1, max_sum) - CountNoGreater(num1, min_sum-1) + M) % M; + + ret = (ret + M) % M; + + int digitSum = calculate(num1); + if (digitSum>=min_sum && digitSum<=max_sum) ret = (ret+1)%M; + return ret; } - - int getDigitSum(string s) + + int calculate(string& s) { int ret = 0; - for (auto ch: s) ret += ch-'0'; + for (auto ch:s) ret += ch-'0'; return ret; } - - - LL CountNoGreaterThan(string num, int max_sum) - { - vector>>memo(2, vector>(25, vector(405, -1))); + + LL CountNoGreater(string num, int max_sum) + { + vector>>memo(2, vector>(25, vector(405, -1))); return dfs(num, max_sum, 0, 0, true, memo); } - - LL dfs(string num, int max_sum, int i, int sum, int isSame, vector>>&memo) + + LL dfs(string num, int max_sum, int i, int sum, bool isSame, vector>>&memo) { - if (sum > max_sum) return 0; + if (sum > max_sum) return 0; if (memo[isSame][i][sum]!=-1) return memo[isSame][i][sum]; - if (i==num.size()) return 1; - + if (i==num.size()) return 1; + LL ret = 0; if (!isSame) { @@ -38,21 +40,22 @@ class Solution { { ret += dfs(num, max_sum, i+1, sum+k, false, memo); ret %= M; - } + } } else { - for (int k=0; k Date: Sat, 10 Jun 2023 23:47:32 -0700 Subject: [PATCH 1903/2729] Update 2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp --- ...nt-Subarrays-With-More-Ones-Than-Zeros.cpp | 43 ++++++++++++------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp b/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp index 08aac66cd..fa361d9d9 100644 --- a/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp +++ b/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp @@ -1,16 +1,21 @@ -const int MAX_N = 200003; -using LL = long long; - -class Solution { - int OFFSET = 100001; - long long bitArr[MAX_N]; - long long nums[MAX_N]; // Note: nums is 1-index +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; long long M = 1e9+7; - // increase nums[i] by delta (1-index) + void init(int N) + { + this->N = N; + bitArr.resize(N+1); + nums.resize(N+1); + } + + // increase nums[i] by delta void updateDelta(int i, long long delta) { int idx = i; - while (idx <= MAX_N) + while (idx <= N) { bitArr[idx]+=delta; bitArr[idx] %= M; @@ -18,7 +23,7 @@ class Solution { } } - // sum of a range nums[1:j] inclusively, 1-index + // sum of a range nums[1:j] inclusively long long queryPreSum(int idx){ long long result = 0; while (idx){ @@ -32,23 +37,29 @@ class Solution { // sum of a range nums[i:j] inclusively long long sumRange(int i, int j) { return queryPreSum(j)-queryPreSum(i-1); - } - + } +}; + +using LL = long long; +LL OFFSET = 1e5+10; +LL M = 1e9+7; +class Solution { public: int subarraysWithMoreZerosThanOnes(vector& nums) { - cout< Date: Mon, 12 Jun 2023 00:09:48 -0700 Subject: [PATCH 1904/2729] Create 2730.Find-the-Longest-Semi-Repetitive-Substring.cpp --- ...-the-Longest-Semi-Repetitive-Substring.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/2730.Find-the-Longest-Semi-Repetitive-Substring.cpp diff --git a/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/2730.Find-the-Longest-Semi-Repetitive-Substring.cpp b/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/2730.Find-the-Longest-Semi-Repetitive-Substring.cpp new file mode 100644 index 000000000..8b4516dde --- /dev/null +++ b/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/2730.Find-the-Longest-Semi-Repetitive-Substring.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int longestSemiRepetitiveSubstring(string s) + { + int n = s.size(); + int ret = 0; + int j = 0; + int count = 0; + for (int i=0; ii && s[j]==s[j-1]) < 2)) + { + count += (j>i && s[j]==s[j-1]); + j++; + } + ret = max(ret, j-i); + + if (i+1 Date: Mon, 12 Jun 2023 00:10:24 -0700 Subject: [PATCH 1905/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b9250647a..e020d58fc 100644 --- a/Readme.md +++ b/Readme.md @@ -50,6 +50,7 @@ [2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) [2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (M+) [2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2564.Substring-XOR-Queries) (H-) +[2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 5ca1a131d2c496fce4d1f5320583d741b443640e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 00:36:21 -0700 Subject: [PATCH 1906/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/Readme.md diff --git a/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/Readme.md b/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/Readme.md new file mode 100644 index 000000000..472a71482 --- /dev/null +++ b/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/Readme.md @@ -0,0 +1,5 @@ +### 2730.Find-the-Longest-Semi-Repetitive-Substring + +典型的双指针滑窗。我们试图维护一个合法的`[i,j)`的滑窗。 + +基本的算法是,固定一个i的位置,向右滑动右边界j,直至发现加入j后会使得[i:j]范围内“consecutive pair”的count达到2,此时停止j的移动。然后我们再开始下一个回合(i指向右边的位置)前,注意count是否需要因为i的移动而减一。 From fc0bb26d671ff730502f7a930471c37a48cc95ca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 02:19:56 -0700 Subject: [PATCH 1907/2729] Update 1473.Paint-House-III_v2.cpp --- .../1473.Paint-House-III_v2.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp index 0ad79e05c..a57e5af19 100644 --- a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp +++ b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp @@ -10,11 +10,19 @@ class Solution { for (int j=0; j<=target; j++) for (int k=0; k<=n; k++) dp[i][j][k] = INT_MAX/2; + + if (houses[1]!=0) + { + dp[1][1][houses[1]] = 0; + } + else + { + for (int k=1; k<=n; k++) + dp[1][1][k] = cost[1][k-1]; - for (int k=0; k<=n; k++) - dp[0][0][k] = 0; + } - for (int i=1; i<=m; i++) + for (int i=2; i<=m; i++) { if (houses[i]!=0) { @@ -28,10 +36,11 @@ class Solution { else dp[i][j][k] = min(dp[i][j][k], dp[i-1][j-1][kk]); } + } } else - { + { for (int j=1; j<=target; j++) { vector>temp; From cecc8c79978273cf79699853d8005d97e3c90db2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 02:21:11 -0700 Subject: [PATCH 1908/2729] Update 1473.Paint-House-III_v1.cpp --- .../1473.Paint-House-III_v1.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v1.cpp b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v1.cpp index 84e963611..9340c7dfe 100644 --- a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v1.cpp +++ b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v1.cpp @@ -11,10 +11,17 @@ class Solution { for (int k=0; k<=n; k++) dp[i][j][k] = INT_MAX/2; - for (int k=0; k<=n; k++) - dp[0][0][k] = 0; + if (houses[1]!=0) + { + dp[1][1][houses[1]] = 0; + } + else + { + for (int k=1; k<=n; k++) + dp[1][1][k] = cost[1][k-1]; + } - for (int i=1; i<=m; i++) + for (int i=2; i<=m; i++) { if (houses[i]!=0) { From aa171f8d3a6aaab0aa5805dcf23f9205bcca524a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 02:21:22 -0700 Subject: [PATCH 1909/2729] Update 1473.Paint-House-III_v2.cpp --- .../1473.Paint-House-III/1473.Paint-House-III_v2.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp index a57e5af19..50eca43e6 100644 --- a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp +++ b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp @@ -19,7 +19,6 @@ class Solution { { for (int k=1; k<=n; k++) dp[1][1][k] = cost[1][k-1]; - } for (int i=2; i<=m; i++) From 370a01f2bbe86ba319db1a90399fd514c67c0592 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 02:23:18 -0700 Subject: [PATCH 1910/2729] Update Readme.md --- Dynamic_Programming/1473.Paint-House-III/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1473.Paint-House-III/Readme.md b/Dynamic_Programming/1473.Paint-House-III/Readme.md index 02ee623bd..b325e8394 100644 --- a/Dynamic_Programming/1473.Paint-House-III/Readme.md +++ b/Dynamic_Programming/1473.Paint-House-III/Readme.md @@ -7,7 +7,7 @@ 2. 当```house[i]==0```,说明第i个房子可以任意喷涂k=1,2,..,n,记得加上喷涂成本. 同理,遍历前一个房子的颜色kk。如果kk与k相同,那么第i个房子和前面的房子可以合并为一个block,即```dp[i][j][k] = min{self, dp[i-1][j][kk]+cost[i][k]}```。如果kk与k不同,那么第i个房子就是第j个block的第一个,即```dp[i][j][k] = min{self, dp[i-1][j-1][kk]+cost[i][k]}```。 -初始状态是```dp[0][0][j] = 0```,其余的状态都是无穷大。 +初始状态较为容易的写法是对第1座房子做单独分析。如果第一座房子已经喷涂,那么`dp[1][1][houses[1]] = 0`,否则`dp[1][1][k] = cost[1][k]`.其余的状态都设为无穷大。DP的转移从i=2开始。 最终的答案是在所有房子喷涂完、构造了target个block、最后一个房子颜色任意的前提下,取最小值。即```min{dp[m][target][k],for k=1,2,..,n``` From 50014c331c87435c1a72a4533eb532abbd052600 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 21:27:28 -0700 Subject: [PATCH 1911/2729] Create 2736.Maximum-Sum-Queries.cpp --- .../2736.Maximum-Sum-Queries.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp diff --git a/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp b/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp new file mode 100644 index 000000000..422cd34a4 --- /dev/null +++ b/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + vector maximumSumQueries(vector& nums1, vector& nums2, vector>& queries) + { + map>>Map; + for (int i=0; irets(queries.size(), -1); + + vector>nums; + for (int i=0; ifirst <= x) + { + auto iter2 = iter->second.begin(); + while (iter2 != iter->second.end() && iter2->first <= y) + { + rets[iter2->second] = val; + iter->second.erase(iter2++); + } + if (iter->second.empty()) + Map.erase(iter++); + else + iter++; + } + } + + return rets; + + } +}; From c6c5cec9dbbb486acf54dd0ef671a358b492a4e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 21:28:13 -0700 Subject: [PATCH 1912/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e020d58fc..c81a77981 100644 --- a/Readme.md +++ b/Readme.md @@ -212,6 +212,7 @@ [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) +[2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2736.Maximum-Sum-Queries) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) From e134c9f786b7aaeb5951cea4ce30e2a9ba3d6ed0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:45:40 -0700 Subject: [PATCH 1913/2729] Create Readme.md --- Heap/2736.Maximum-Sum-Queries/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Heap/2736.Maximum-Sum-Queries/Readme.md diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Heap/2736.Maximum-Sum-Queries/Readme.md new file mode 100644 index 000000000..db300f901 --- /dev/null +++ b/Heap/2736.Maximum-Sum-Queries/Readme.md @@ -0,0 +1,7 @@ +### 2736.Maximum-Sum-Queries + +如果我们将每个query独立地去做,需要暴力地扫所有的nums。一种常见的应对思路是`Off-line Querying`,将query进行某种意义上的排序,通常先解决的query会对后面的query帮助。但是这个思路似乎对本题没有帮助。比如说,将query按照x从大到小排序,随着query的逐一解答,我们可用的nums也会逐渐增多,但是并不能帮我们方便地解决如何满足关于y的约束以及怎么取到最大sum。 + +但是此题还有另外一种对偶的思路,将nums进行某种意义上的排序。我们发现,对于sum最大的num,任何满足x和y约束的所有query,必然会取该sum作为答案,既然找到了答案,那么就可以从待求的query的集合中删除。为了容易找到这些满足约束的query,我们可以将所有query先按照x排序,再按照y排序,构造二层的数据结构。这样,在第一层,任何x小于nums1[j]的query都会入选;然后在对应的第二层,任何y小于nums2[j]的query都可以被选中,标记它们的答案是sum。可以发现,这些被选中的query是分块连续的,我们可以很方便地删除。 + +分析时间复杂度:我们令num的个数是m,query的个数是n。我们对于每个num,都会在以x为key的query分组里进行二分。时间复杂度是MlogN。此外在第二层,每个query只会被访问和删除一次。所以总的时间复杂度是`MlogN+N`. From dc15a6498ebfe7be109e57993c59024ca7333bcc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:49:50 -0700 Subject: [PATCH 1914/2729] Update Readme.md --- Heap/2736.Maximum-Sum-Queries/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Heap/2736.Maximum-Sum-Queries/Readme.md index db300f901..5d5095780 100644 --- a/Heap/2736.Maximum-Sum-Queries/Readme.md +++ b/Heap/2736.Maximum-Sum-Queries/Readme.md @@ -4,4 +4,6 @@ 但是此题还有另外一种对偶的思路,将nums进行某种意义上的排序。我们发现,对于sum最大的num,任何满足x和y约束的所有query,必然会取该sum作为答案,既然找到了答案,那么就可以从待求的query的集合中删除。为了容易找到这些满足约束的query,我们可以将所有query先按照x排序,再按照y排序,构造二层的数据结构。这样,在第一层,任何x小于nums1[j]的query都会入选;然后在对应的第二层,任何y小于nums2[j]的query都可以被选中,标记它们的答案是sum。可以发现,这些被选中的query是分块连续的,我们可以很方便地删除。 -分析时间复杂度:我们令num的个数是m,query的个数是n。我们对于每个num,都会在以x为key的query分组里进行二分。时间复杂度是MlogN。此外在第二层,每个query只会被访问和删除一次。所以总的时间复杂度是`MlogN+N`. +分析时间复杂度:我们令num的个数是m,query的个数是n。我们对于每个num,都会在query集合里删除答案对应是num的query。注意在第二层,每个query只会被访问和删除一次。所以代码核心的时间复杂度是`M+N`. 不过预处理有一个对num和query分别排序的过程。 + +注意,为了提高效率,如果某个二层集合里的query被删空了,务必把它们的一层指针也移除。 From 19d954af8262f0741da93563b880e8a883cad587 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:50:45 -0700 Subject: [PATCH 1915/2729] Update Readme.md --- Heap/2736.Maximum-Sum-Queries/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Heap/2736.Maximum-Sum-Queries/Readme.md index 5d5095780..b55499c11 100644 --- a/Heap/2736.Maximum-Sum-Queries/Readme.md +++ b/Heap/2736.Maximum-Sum-Queries/Readme.md @@ -4,6 +4,8 @@ 但是此题还有另外一种对偶的思路,将nums进行某种意义上的排序。我们发现,对于sum最大的num,任何满足x和y约束的所有query,必然会取该sum作为答案,既然找到了答案,那么就可以从待求的query的集合中删除。为了容易找到这些满足约束的query,我们可以将所有query先按照x排序,再按照y排序,构造二层的数据结构。这样,在第一层,任何x小于nums1[j]的query都会入选;然后在对应的第二层,任何y小于nums2[j]的query都可以被选中,标记它们的答案是sum。可以发现,这些被选中的query是分块连续的,我们可以很方便地删除。 +同理,我们再处理sum为次大的num,删除所有答案是它的query。以此类推。 + 分析时间复杂度:我们令num的个数是m,query的个数是n。我们对于每个num,都会在query集合里删除答案对应是num的query。注意在第二层,每个query只会被访问和删除一次。所以代码核心的时间复杂度是`M+N`. 不过预处理有一个对num和query分别排序的过程。 注意,为了提高效率,如果某个二层集合里的query被删空了,务必把它们的一层指针也移除。 From 4608c0f717bd5e9967bc6243f2f5459711ed19ad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:52:32 -0700 Subject: [PATCH 1916/2729] Update Readme.md --- Heap/2736.Maximum-Sum-Queries/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Heap/2736.Maximum-Sum-Queries/Readme.md index b55499c11..c4afc3b96 100644 --- a/Heap/2736.Maximum-Sum-Queries/Readme.md +++ b/Heap/2736.Maximum-Sum-Queries/Readme.md @@ -1,6 +1,6 @@ ### 2736.Maximum-Sum-Queries -如果我们将每个query独立地去做,需要暴力地扫所有的nums。一种常见的应对思路是`Off-line Querying`,将query进行某种意义上的排序,通常先解决的query会对后面的query帮助。但是这个思路似乎对本题没有帮助。比如说,将query按照x从大到小排序,随着query的逐一解答,我们可用的nums也会逐渐增多,但是并不能帮我们方便地解决如何满足关于y的约束以及怎么取到最大sum。 +如果我们将每个query独立地去做,需要暴力地扫所有的nums。一种常见的应对思路是`Off-line Querying`,将query进行某种意义上的排序,通常先解决的query会对后面的query帮助。但是这个思路似乎对本题没有帮助。比如说,将query按照x从大到小排序,随着query的逐一解答,我们可用的nums也会逐渐增多,但是并不能帮我们方便地兼顾“满足关于y的约束”以及“取最大sum”。 但是此题还有另外一种对偶的思路,将nums进行某种意义上的排序。我们发现,对于sum最大的num,任何满足x和y约束的所有query,必然会取该sum作为答案,既然找到了答案,那么就可以从待求的query的集合中删除。为了容易找到这些满足约束的query,我们可以将所有query先按照x排序,再按照y排序,构造二层的数据结构。这样,在第一层,任何x小于nums1[j]的query都会入选;然后在对应的第二层,任何y小于nums2[j]的query都可以被选中,标记它们的答案是sum。可以发现,这些被选中的query是分块连续的,我们可以很方便地删除。 From 03cc39705bbc06f9d7a550225052d2b8028f4f86 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:54:45 -0700 Subject: [PATCH 1917/2729] Update 2736.Maximum-Sum-Queries.cpp --- .../2736.Maximum-Sum-Queries.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp b/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp index 422cd34a4..e9a3b9f92 100644 --- a/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp +++ b/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp @@ -23,13 +23,14 @@ class Solution { while (iter!=Map.end() && iter->first <= x) { - auto iter2 = iter->second.begin(); - while (iter2 != iter->second.end() && iter2->first <= y) + set>& s = iter->second; + auto iter2 = s.begin(); + while (iter2 != s.end() && iter2->first <= y) { rets[iter2->second] = val; - iter->second.erase(iter2++); + s.erase(iter2++); } - if (iter->second.empty()) + if (s.empty()) Map.erase(iter++); else iter++; @@ -37,6 +38,5 @@ class Solution { } return rets; - } }; From e56288971d89b5301d33353c0368d31c6b0556e6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 15:28:24 -0700 Subject: [PATCH 1918/2729] Create 2211.Count-Collisions-on-a-Road.cpp --- .../2211.Count-Collisions-on-a-Road.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Others/2211.Count-Collisions-on-a-Road/2211.Count-Collisions-on-a-Road.cpp diff --git a/Others/2211.Count-Collisions-on-a-Road/2211.Count-Collisions-on-a-Road.cpp b/Others/2211.Count-Collisions-on-a-Road/2211.Count-Collisions-on-a-Road.cpp new file mode 100644 index 000000000..6743dc398 --- /dev/null +++ b/Others/2211.Count-Collisions-on-a-Road/2211.Count-Collisions-on-a-Road.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int countCollisions(string directions) + { + int count = 0; + int n = directions.size(); + + int flag = 0; + for (int i=0; i=0; i--) + { + if (flag == 0 && (directions[i]=='L' || directions[i]=='S')) + flag = 1; + if (flag == 1 && directions[i]=='R') + count++; + } + return count; + } +}; From f2f1cb1e93d433c76b2e6aa30db13ec7e15a5caa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 15:30:02 -0700 Subject: [PATCH 1919/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index c81a77981..cb29f0446 100644 --- a/Readme.md +++ b/Readme.md @@ -1401,8 +1401,9 @@ [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) -* ``Physics`` -1503. Last Moment Before All Ants Fall Out of a Plank (M) +* ``Collision`` +[2211.Count-Collisions-on-a-Road](https://github.com/wisdompeak/LeetCode/tree/master/Others/2211.Count-Collisions-on-a-Road) (M) +1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank (M) [2731.Movement-of-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Others/2731.Movement-of-Robots) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) From ed012cee2581aeb132089869eefeb77759766f68 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 17:08:46 -0700 Subject: [PATCH 1920/2729] Create 853.Car-Fleet.cpp --- Others/853.Car-Fleet/853.Car-Fleet.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Others/853.Car-Fleet/853.Car-Fleet.cpp diff --git a/Others/853.Car-Fleet/853.Car-Fleet.cpp b/Others/853.Car-Fleet/853.Car-Fleet.cpp new file mode 100644 index 000000000..689668754 --- /dev/null +++ b/Others/853.Car-Fleet/853.Car-Fleet.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int carFleet(int target, vector& position, vector& speed) + { + vector>q; + int N= position.size(); + if (N==0) return 0; + + for (int i=0; i Date: Tue, 13 Jun 2023 17:09:25 -0700 Subject: [PATCH 1921/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cb29f0446..89a209738 100644 --- a/Readme.md +++ b/Readme.md @@ -1402,8 +1402,9 @@ [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) * ``Collision`` -[2211.Count-Collisions-on-a-Road](https://github.com/wisdompeak/LeetCode/tree/master/Others/2211.Count-Collisions-on-a-Road) (M) +[853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) 1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank (M) +[2211.Count-Collisions-on-a-Road](https://github.com/wisdompeak/LeetCode/tree/master/Others/2211.Count-Collisions-on-a-Road) (M) [2731.Movement-of-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Others/2731.Movement-of-Robots) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) From ed65a73287608321fb4d4744677c9b18ce37f584 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 23:15:01 -0700 Subject: [PATCH 1922/2729] Update 853.Car-Fleet.cpp --- Others/853.Car-Fleet/853.Car-Fleet.cpp | 27 +++++++++++++------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/Others/853.Car-Fleet/853.Car-Fleet.cpp b/Others/853.Car-Fleet/853.Car-Fleet.cpp index 689668754..586c0301f 100644 --- a/Others/853.Car-Fleet/853.Car-Fleet.cpp +++ b/Others/853.Car-Fleet/853.Car-Fleet.cpp @@ -1,26 +1,25 @@ class Solution { public: int carFleet(int target, vector& position, vector& speed) - { - vector>q; + { int N= position.size(); if (N==0) return 0; + vector>q; for (int i=0; i=0; i--) { - double time = q[i].first*1.0/q[i].second; - int j = i+1; - while (j=0 && (target-q[j].first)*1.0/q[j].second <= T) + j--; count++; - i = j; - } + i = j+1; + } return count; } }; From 567c43aeab3b9fd7633c4eff3d65dd330f9a16b4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 23:23:25 -0700 Subject: [PATCH 1923/2729] Create Readme.md --- Others/853.Car-Fleet/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/853.Car-Fleet/Readme.md diff --git a/Others/853.Car-Fleet/Readme.md b/Others/853.Car-Fleet/Readme.md new file mode 100644 index 000000000..67f7f3e3e --- /dev/null +++ b/Others/853.Car-Fleet/Readme.md @@ -0,0 +1,5 @@ +### 853.Car-Fleet + +我们判断一辆车是否会与前车相撞,只要考察该车到达终点的时间是否小于前车到达终点的时间。所以最终能组成一个fleet的车辆,必然是一段连续区间的车,且该区间里的所有车都会撞上此区间最右边的领头车。 + +所以本题的算法是,从右往左遍历每辆车A,考察它作为领头车的话,它后面会有连续几辆车能在到达终点前撞上它,这个区间就是一个fleet。如果发现后面的某辆车B不会撞上它,那么B就是另一个fleet的领头车了。 From 096a2f94254737605cf026658877cc8d7a23c79d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 23:40:23 -0700 Subject: [PATCH 1924/2729] Update 853.Car-Fleet.cpp --- Others/853.Car-Fleet/853.Car-Fleet.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Others/853.Car-Fleet/853.Car-Fleet.cpp b/Others/853.Car-Fleet/853.Car-Fleet.cpp index 586c0301f..766111ce3 100644 --- a/Others/853.Car-Fleet/853.Car-Fleet.cpp +++ b/Others/853.Car-Fleet/853.Car-Fleet.cpp @@ -3,7 +3,6 @@ class Solution { int carFleet(int target, vector& position, vector& speed) { int N= position.size(); - if (N==0) return 0; vector>q; for (int i=0; i Date: Tue, 13 Jun 2023 23:47:23 -0700 Subject: [PATCH 1925/2729] Create Readmd.md --- Others/2211.Count-Collisions-on-a-Road/Readmd.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/2211.Count-Collisions-on-a-Road/Readmd.md diff --git a/Others/2211.Count-Collisions-on-a-Road/Readmd.md b/Others/2211.Count-Collisions-on-a-Road/Readmd.md new file mode 100644 index 000000000..6f5965d4f --- /dev/null +++ b/Others/2211.Count-Collisions-on-a-Road/Readmd.md @@ -0,0 +1,3 @@ +### 2211.Count-Collisions-on-a-Road + +很显然,只要左边缘有一个静止或者向右运动的车辆,那么它右边任何向左运动的车辆注定都会相撞。同理,只要右边缘有一个静止或者向左运动的车辆,那么它做边任何向右运动的车辆注定都会相撞。 From f7e32a2fa6e6de5cf61922b835dfdb688d31820f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 23:47:35 -0700 Subject: [PATCH 1926/2729] Rename Readmd.md to Readme.md --- Others/2211.Count-Collisions-on-a-Road/{Readmd.md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Others/2211.Count-Collisions-on-a-Road/{Readmd.md => Readme.md} (100%) diff --git a/Others/2211.Count-Collisions-on-a-Road/Readmd.md b/Others/2211.Count-Collisions-on-a-Road/Readme.md similarity index 100% rename from Others/2211.Count-Collisions-on-a-Road/Readmd.md rename to Others/2211.Count-Collisions-on-a-Road/Readme.md From cf4367a01cca7cc756d898cfe17bcc693a730131 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 14 Jun 2023 00:04:43 -0700 Subject: [PATCH 1927/2729] Create 1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp --- ...3.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp diff --git a/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp b/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp new file mode 100644 index 000000000..8f2f9dd12 --- /dev/null +++ b/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int getLastMoment(int n, vector& left, vector& right) + { + sort(left.begin(), left.end()); + sort(right.begin(), right.end()); + return max(left.size()==0?0:left.back(), right.size()==0?0:n-right[0]); + } +}; From 210326c21d5fdc01f23341fc71604eb67d974985 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 14 Jun 2023 00:05:04 -0700 Subject: [PATCH 1928/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 89a209738..3c078bd93 100644 --- a/Readme.md +++ b/Readme.md @@ -1403,7 +1403,7 @@ [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) -1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank (M) +[1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) [2211.Count-Collisions-on-a-Road](https://github.com/wisdompeak/LeetCode/tree/master/Others/2211.Count-Collisions-on-a-Road) (M) [2731.Movement-of-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Others/2731.Movement-of-Robots) (M+) * ``结论转移`` From e5f72ffa279f23ac4f83b1574b404b457ff26186 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 14 Jun 2023 00:10:37 -0700 Subject: [PATCH 1929/2729] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/Readme.md diff --git a/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/Readme.md b/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/Readme.md new file mode 100644 index 000000000..57a956b02 --- /dev/null +++ b/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/Readme.md @@ -0,0 +1,3 @@ +### 1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank + +很明显,任何碰撞事件都不影响宏观上蚂蚁的运动状态(只不过身份调换一下)。所以最后一个从左边掉落的蚂蚁,一定对应着初始时最靠右的、向左运动的蚂蚁。反之,最后一个从右边掉落的蚂蚁,一定对应着初始时最靠左的、向右运动的蚂蚁。 From 51046c0518f3ef08a135d576965a1f96591a874d Mon Sep 17 00:00:00 2001 From: Hacker-Davinci Date: Sat, 17 Jun 2023 23:11:49 +0800 Subject: [PATCH 1930/2729] Update 1187.Make-Array-Strictly-Increasing.cpp The return value only have to be updated once. BTW, really appreciate your hard work and passion. --- .../1187.Make-Array-Strictly-Increasing.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/1187.Make-Array-Strictly-Increasing/1187.Make-Array-Strictly-Increasing.cpp b/Dynamic_Programming/1187.Make-Array-Strictly-Increasing/1187.Make-Array-Strictly-Increasing.cpp index 69556ff6f..5775d3670 100644 --- a/Dynamic_Programming/1187.Make-Array-Strictly-Increasing/1187.Make-Array-Strictly-Increasing.cpp +++ b/Dynamic_Programming/1187.Make-Array-Strictly-Increasing/1187.Make-Array-Strictly-Increasing.cpp @@ -23,7 +23,10 @@ class Solution { int ret = INT_MAX; for (int k=0; k<=n; k++) - if (dp[n][k]!=INT_MAX) ret = min(ret, k); + if (dp[n][k]!=INT_MAX) { + ret = k; + break; + } return ret == INT_MAX ? -1: ret; } From e6ca9e814a293fb63de05846e4bcfce0df0cefde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 21 Jun 2023 21:39:33 -0700 Subject: [PATCH 1931/2729] Create 2742.Painting-the-Walls_v1.cpp --- .../2742.Painting-the-Walls_v1.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v1.cpp diff --git a/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v1.cpp b/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v1.cpp new file mode 100644 index 000000000..eb19d2224 --- /dev/null +++ b/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v1.cpp @@ -0,0 +1,31 @@ +class Solution { + int dp[505][505*2]; + int OFFSET = 505; +public: + int paintWalls(vector& cost, vector& time) + { + int n = cost.size(); + cost.insert(cost.begin(), 0); + time.insert(time.begin(), 0); + + for (int i=0; i<=n; i++) + for (int j=-n; j<=n; j++) + dp[i][j+OFFSET] = INT_MAX/2; + dp[0][OFFSET] = 0; + + for (int i=0; i Date: Wed, 21 Jun 2023 21:40:46 -0700 Subject: [PATCH 1932/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3c078bd93..6fe2438fd 100644 --- a/Readme.md +++ b/Readme.md @@ -868,7 +868,8 @@ [903.Valid-Permutations-for-DI-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence) (H) [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) * ``Infer future from current`` -[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) +[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) +[2742.Painting-the-Walls](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2742.Painting-the-Walls) (H) * ``maximum subarray`` [053.Maximum-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/053.Maximum-Subarray) (E+) [152.Maximum-Product-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/152.Maximum-Product-Subarray) (M+) From 1c882cf69f095a0b7aed571ec812bdf5fc5ae4d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Jun 2023 12:46:26 -0700 Subject: [PATCH 1933/2729] Update 452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp --- ...mum-Number-of-Arrows-to-Burst-Balloons.cpp | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons/452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp b/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons/452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp index 8bfb712a8..fb227b791 100644 --- a/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons/452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp +++ b/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons/452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp @@ -1,23 +1,23 @@ class Solution { - static bool cmp(paira, pairb) + static bool cmp(vector&a, vector&b) { - return a.second>& points) + int findMinArrowShots(vector>& points) { - sort(points.begin(),points.end(),cmp); - - int j=0; - int count=0; - while (j Date: Sun, 2 Jul 2023 12:05:28 -0700 Subject: [PATCH 1934/2729] Create 2762.Continuous-Subarrays.cpp --- .../2762.Continuous-Subarrays.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Deque/2762.Continuous-Subarrays/2762.Continuous-Subarrays.cpp diff --git a/Deque/2762.Continuous-Subarrays/2762.Continuous-Subarrays.cpp b/Deque/2762.Continuous-Subarrays/2762.Continuous-Subarrays.cpp new file mode 100644 index 000000000..072185152 --- /dev/null +++ b/Deque/2762.Continuous-Subarrays/2762.Continuous-Subarrays.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long continuousSubarrays(vector& nums) + { + int n = nums.size(); + + dequedq1; + dequedq2; + + int i = 0; + LL ret = 0; + for (int j=0; j nums[j]) + dq2.pop_back(); + dq2.push_back(j); + + while (!dq1.empty() && !dq2.empty() && nums[dq1.front()]-nums[dq2.front()] > 2) + { + if (!dq1.empty() && dq1.front() <= i) + dq1.pop_front(); + if (!dq2.empty() && dq2.front() <= i) + dq2.pop_front(); + i++; + } + ret += LL(j-i+1); + } + + return ret; + } +}; From a28977d7d5dfa346818eaba17bc5a9dff2587908 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jul 2023 12:05:59 -0700 Subject: [PATCH 1935/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6fe2438fd..de0684426 100644 --- a/Readme.md +++ b/Readme.md @@ -429,6 +429,7 @@ [1696.Jump-Game-VI](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1696.Jump-Game-VI) (M+) [1776.Car-Fleet-II](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1776.Car-Fleet-II) (H) [2398.Maximum-Number-of-Robots-Within-Budget](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2398.Maximum-Number-of-Robots-Within-Budget) (H-) +[2762.Continuous-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2762.Continuous-Subarrays) (M+) #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) From 33ad649cf38c151e53b57e18e2693a8506b9de74 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jul 2023 16:24:04 -0700 Subject: [PATCH 1936/2729] Create Readme.md --- Deque/2762.Continuous-Subarrays/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Deque/2762.Continuous-Subarrays/Readme.md diff --git a/Deque/2762.Continuous-Subarrays/Readme.md b/Deque/2762.Continuous-Subarrays/Readme.md new file mode 100644 index 000000000..0ebeed72f --- /dev/null +++ b/Deque/2762.Continuous-Subarrays/Readme.md @@ -0,0 +1,5 @@ +### 2762.Continuous-Subarrays + +这是一个很常见的滑动窗口的题。总的规律是,窗口越长,越不容易满足条件。所以如果我们固定了左端点i,那么可以找到一个最远的右端点j使得[i:j]满足条件。那么以i为左端点的合法subarray的个数就是`j-i+1`.此后,我们必然只能移动左端点至i+1,而右端点必然也需要单调右移。 + +在窗口滑动的过程中,我们需要满足“最大值与最小值”之差不大于2. 显然我们用两个双端队列就是做到实时维护滑窗的最大值和最小值。 From 6f5b92f37dd75ae75e82eb9ac2fa1f6cfc9e2d3f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jul 2023 17:17:50 -0700 Subject: [PATCH 1937/2729] Update Readme.md --- Deque/2762.Continuous-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Deque/2762.Continuous-Subarrays/Readme.md b/Deque/2762.Continuous-Subarrays/Readme.md index 0ebeed72f..27022ba1e 100644 --- a/Deque/2762.Continuous-Subarrays/Readme.md +++ b/Deque/2762.Continuous-Subarrays/Readme.md @@ -2,4 +2,4 @@ 这是一个很常见的滑动窗口的题。总的规律是,窗口越长,越不容易满足条件。所以如果我们固定了左端点i,那么可以找到一个最远的右端点j使得[i:j]满足条件。那么以i为左端点的合法subarray的个数就是`j-i+1`.此后,我们必然只能移动左端点至i+1,而右端点必然也需要单调右移。 -在窗口滑动的过程中,我们需要满足“最大值与最小值”之差不大于2. 显然我们用两个双端队列就是做到实时维护滑窗的最大值和最小值。 +在窗口滑动的过程中,我们需要满足“最大值与最小值”之差不大于2. 显然我们用两个双端队列就能做到实时维护滑窗的最大值和最小值。 From c02a53d5c7ddf56cc76f3019e5ce0a91c030b149 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 12:03:15 -0700 Subject: [PATCH 1938/2729] Create 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp --- ...-Imbalance-Numbers-of-All-Subarrays_v3.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp new file mode 100644 index 000000000..8640399af --- /dev/null +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int sumImbalanceNumbers(vector& nums) + { + int n = nums.size(); + + vectorprevInvalid(n, -1); + vectorval2pos(1005,-1); + for (int i=0; iafterInvalid(n+1, n); + for (int i=0; i<1005; i++) val2pos[i] = n; + for (int i=n-1; i>=0; i--) + { + afterInvalid[i] = min(val2pos[nums[i]], val2pos[nums[i]+1]); + val2pos[nums[i]] = i; + } + + vectorprevLargerThanOne(n, -1); + stackst; + for (int i=0; iafterLargerThanOne(n, n); + while (!st.empty()) st.pop(); + for (int i=n-1; i>=0; i--) + { + while (!st.empty() && nums[st.top()] <= nums[i]+1) + st.pop(); + if (!st.empty()) afterLargerThanOne[i] = st.top(); + st.push(i); + } + + int ret = 0; + for (int i=0; i Date: Mon, 3 Jul 2023 12:12:30 -0700 Subject: [PATCH 1939/2729] Create 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp --- ...-Imbalance-Numbers-of-All-Subarrays_v2.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp new file mode 100644 index 000000000..43f3fa724 --- /dev/null +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + int sumImbalanceNumbers(vector& nums) + { + int n = nums.size(); + + int ret = 0; + for (int i=0; i=0; j--) + { + if (nums[j]==nums[i]+1) + { + prevInvalid = j; + break; + } + if ((nums[j]>nums[i]+1) && prevLargerThanOne==-1) + prevLargerThanOne = j; + } + + int afterInvalid = n; + int afterLargerThanOne = n; + for (int j=i+1; jnums[i]+1) && afterLargerThanOne==n) + afterLargerThanOne = j; + } + + int a = i - prevInvalid; + int b = afterInvalid - i; + int c = i - max(prevInvalid, prevLargerThanOne); + int d = min(afterInvalid, afterLargerThanOne) - i; + + ret += max(0, a*b - c*d); + } + + return ret; + } +}; From 455135b07ea66f2263f94c0fc45100c3da2aeb2a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 12:13:21 -0700 Subject: [PATCH 1940/2729] Update 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp --- .../2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp index 8640399af..6f1bcce7b 100644 --- a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp @@ -48,7 +48,7 @@ class Solution { int c = i - max(prevInvalid[i], prevLargerThanOne[i]); int d = min(afterInvalid[i], afterLargerThanOne[i]) - i; - ret += max(0, a*b - c*d); + ret += a*b - c*d; } return ret; From d356ea03ff9621fcbb959358e1a56fdf57309515 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 12:13:57 -0700 Subject: [PATCH 1941/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index de0684426..3f88d3fac 100644 --- a/Readme.md +++ b/Readme.md @@ -1422,7 +1422,8 @@ [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) -[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) +[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) +[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From caf268b8843cf03a7367321d0d85ec3d92cfcbe4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 17:47:32 -0700 Subject: [PATCH 1942/2729] Create 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp --- ...-Imbalance-Numbers-of-All-Subarrays_v1.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp new file mode 100644 index 000000000..a9f17618d --- /dev/null +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int sumImbalanceNumbers(vector& nums) + { + int n = nums.size(); + int ret = 0; + + for (int i=0; ivals(1005); + for (int j=i; j Date: Mon, 3 Jul 2023 21:13:04 -0700 Subject: [PATCH 1943/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3f88d3fac..9da94a900 100644 --- a/Readme.md +++ b/Readme.md @@ -1422,7 +1422,7 @@ [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) -[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) +[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) [2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) From 9ac61e41e0f03420fc32ecfaba565abb373b46a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 21:36:24 -0700 Subject: [PATCH 1944/2729] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md new file mode 100644 index 000000000..647c66641 --- /dev/null +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md @@ -0,0 +1,12 @@ +### 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays + +#### 解法1: +因为数据规模不大,可以用n^2的复杂度,那么我们可以暴力模拟每个subarray。当我们固定i为左边界的时候,逐个向右移动j作为右边界,考察此时[i:j]的subarray里有多少个符合条件的index。 + +假设在[i:j-1]的旧subarray里已经有count个符合条件的index,当我们需要考察nums[j]加入后的新subarray时,计数会有什么变化呢?我们发现,新subarray基本上可以继承旧subarray的count,但是我们需要考虑nums[j]带来的变化。 + +1. 通常情况下,如果旧subarray里面的元素分布是稀疏的,那么一个新元素nums[j]的引入大概率会贡献一个合法的index,即`count+=1`。除非旧subarray里面已经有了`nums[j]`这个元素,那么显然,相同数值的元素不能贡献多于一个的合法index,我们会忽略count的变化跳出剩余的判断。 +2. 如果发现旧subarray里面已经有了`nums[j]+1`这个元素,那么nums[j]会因为它的缘故无法被认为是合法的index,故取消刚才的计数`count-=1`. +3. 如果发现旧subarray里面已经有了`nums[j]-1`这个元素,那么nums[j]反而会侵蚀掉一个之前认为是合法的index,故扣减计数`count-=1`. + +综上,此时的count就是[i:j]对应的新subarray的合法index的计数。 From 9f2056d803a4d196ad19f489c766b38658095d6c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 21:37:14 -0700 Subject: [PATCH 1945/2729] Update Readme.md --- Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md index 647c66641..925001439 100644 --- a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md @@ -5,7 +5,7 @@ 假设在[i:j-1]的旧subarray里已经有count个符合条件的index,当我们需要考察nums[j]加入后的新subarray时,计数会有什么变化呢?我们发现,新subarray基本上可以继承旧subarray的count,但是我们需要考虑nums[j]带来的变化。 -1. 通常情况下,如果旧subarray里面的元素分布是稀疏的,那么一个新元素nums[j]的引入大概率会贡献一个合法的index,即`count+=1`。除非旧subarray里面已经有了`nums[j]`这个元素,那么显然,相同数值的元素不能贡献多于一个的合法index,我们会忽略count的变化跳出剩余的判断。 +1. 通常情况下,如果旧subarray里面的元素分布是稀疏的,那么一个新元素nums[j]的引入大概率会贡献一个合法的index(旧subarray为空除外),即`count+=1`。除非旧subarray里面已经有了`nums[j]`这个元素,那么显然,相同数值的元素不能贡献多于一个的合法index,我们会忽略count的变化跳出剩余的判断。 2. 如果发现旧subarray里面已经有了`nums[j]+1`这个元素,那么nums[j]会因为它的缘故无法被认为是合法的index,故取消刚才的计数`count-=1`. 3. 如果发现旧subarray里面已经有了`nums[j]-1`这个元素,那么nums[j]反而会侵蚀掉一个之前认为是合法的index,故扣减计数`count-=1`. From 45522552323f8085fc9bff5589f29071a21ced28 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 21:53:44 -0700 Subject: [PATCH 1946/2729] Update Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md index 925001439..04bbe1b05 100644 --- a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md @@ -10,3 +10,21 @@ 3. 如果发现旧subarray里面已经有了`nums[j]-1`这个元素,那么nums[j]反而会侵蚀掉一个之前认为是合法的index,故扣减计数`count-=1`. 综上,此时的count就是[i:j]对应的新subarray的合法index的计数。 + +#### 解法2: +我们发现,任意的subarray,排序过后里面的每一个index,必然唯一对应着排序之前的某一个index。所以我们想计数排序后合法index的个数,其实直接对排序前的数组进行考察,即思考原始的nums[i]可以是哪些subarray里面的合法index。 + +要是nums[i]在排序后处在一个合法的index,我们必然要求这个subarray不能包括任何数值为`nums[i]+1`的元素,并且在它后面不能有数值为`nums[i]`的元素。(为了方便理解这一点,你可以认为我们制定如下规则:如果同一个subarray里面有多个相同数值的元素,那么这些元素在排序后不改变原始的顺序)。所以我们从i往前推,找到第一个prevInvalid的位置。同时从i往后推,找到第一个afterInvalid的位置,这样就有`(i-prevInvalid)*(afterInvalid-i)`个必然包含nums[i]的subarray,使得nums[i]在排序后不会跟着数值相同、或者相同数值+1的元素。我们记做`a*b`. + +但是以上的计数包括了一种不合法的情况,即nums[i]可能排在了排序后的subarray的最后。所以我们要将这种情况排除。所以我们从i往前推,找到第一个prevLargerThanOne的位置(即·nums[j]>nums[i]+1·)。同时从i往后推,找到第一个afterLargerThanOne的位置。这样就有`(i-prevLargerThanOne)*(afterLargerThanOne-i)`个必然包含nums[i]的subarray,使得nums[i]在排序后是最后一个(因为没有其他合法元素可以排在它后面)。我们记做`c*d`. + +所以`a*b-c*d`就是nums[i]可以贡献的subarray的个数,使得它在这些subarray里面贡献的是一个合法的index. + +特别注意,之前计算的prevLargerThanOne不能往前超越prevInvalid;同理afterLargerThanOne不能往前超越afterInvalid. + +#### 解法3: +上述的解法2是`o(N^2)`的复杂度。运用预处理可以进一步优化到o(N)。 + +我们用Hash表(记录val->pos)从前往后扫一遍,就可以知道任何nums[i]的prevInvalid的位置。 + +我们再利用单调栈的计数从前往后扫一遍,就可以知道任何nums[i]的prevLargerThanOne的位置,具体做法和求prevGreaterElement几乎一样。 From 4c09eda1c0fd860aa2387b497d4ff3c21234b36a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 21:55:15 -0700 Subject: [PATCH 1947/2729] Update Readme.md --- Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md index 04bbe1b05..11e29eb38 100644 --- a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md @@ -20,7 +20,7 @@ 所以`a*b-c*d`就是nums[i]可以贡献的subarray的个数,使得它在这些subarray里面贡献的是一个合法的index. -特别注意,之前计算的prevLargerThanOne不能往前超越prevInvalid;同理afterLargerThanOne不能往前超越afterInvalid. +特别注意,之前计算的prevLargerThanOne不能往前超越prevInvalid;同理afterLargerThanOne不能往后超越afterInvalid,这是因为`c*d`的计数前提依然是valid(即不能有与nums[i]相同数值或者相同数值+1的元素存在)。 #### 解法3: 上述的解法2是`o(N^2)`的复杂度。运用预处理可以进一步优化到o(N)。 From 84ae8029255e9106a1be76948c265c064d79095b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 10:55:54 -0700 Subject: [PATCH 1948/2729] Create 2751.Robot-Collisions.cpp --- .../2751.Robot-Collisions.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Stack/2751.Robot-Collisions/2751.Robot-Collisions.cpp diff --git a/Stack/2751.Robot-Collisions/2751.Robot-Collisions.cpp b/Stack/2751.Robot-Collisions/2751.Robot-Collisions.cpp new file mode 100644 index 000000000..dcdfbe400 --- /dev/null +++ b/Stack/2751.Robot-Collisions/2751.Robot-Collisions.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + vector survivedRobotsHealths(vector& positions, vector& healths, string directions) + { + int n = positions.size(); + vector>robots; + for (int i=0; i>Stack; + for (int i=0; i 0) + Stack.push_back(robots[i]); + } + } + + sort(Stack.begin(), Stack.end(), [](vector&a, vector&b){return a[3]rets; + for (int i=0; i Date: Tue, 4 Jul 2023 10:56:50 -0700 Subject: [PATCH 1949/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9da94a900..1531b024f 100644 --- a/Readme.md +++ b/Readme.md @@ -349,7 +349,8 @@ [460.LFU Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/460.LFU-Cache) (H) [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) -[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) From f5d6d51d9095ff77a8fffcccb5584b776e795601 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 10:58:44 -0700 Subject: [PATCH 1950/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1531b024f..0e3250a65 100644 --- a/Readme.md +++ b/Readme.md @@ -349,7 +349,7 @@ [460.LFU Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/460.LFU-Cache) (H) [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) -[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) [2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) From 58ad18b31fdc882003bac7a7c2a8b334d8408f4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 10:59:30 -0700 Subject: [PATCH 1951/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0e3250a65..266d35083 100644 --- a/Readme.md +++ b/Readme.md @@ -350,7 +350,6 @@ [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) -[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) @@ -369,6 +368,7 @@ [1586.Binary-Search-Tree-Iterator-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1586.Binary-Search-Tree-Iterator-II) (H) [2197.Replace-Non-Coprime-Numbers-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2197.Replace-Non-Coprime-Numbers-in-Array) (H-) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) From a2360965a7d595549cc56a6c3db9c6bf7eb1984a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 11:02:26 -0700 Subject: [PATCH 1952/2729] Create Readme.md --- Stack/2751.Robot-Collisions/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Stack/2751.Robot-Collisions/Readme.md diff --git a/Stack/2751.Robot-Collisions/Readme.md b/Stack/2751.Robot-Collisions/Readme.md new file mode 100644 index 000000000..52e123e46 --- /dev/null +++ b/Stack/2751.Robot-Collisions/Readme.md @@ -0,0 +1,3 @@ +### 2751.Robot-Collisions + +只需要维护一个栈。从左往右遍历元素,如果栈顶元素和当前元素i可能会发生碰撞的话(方向相反),我们根据他们的health来决定保留栈顶元素还是保留当前元素。注意,对于同一个元素i,可能会与多个栈顶元素发生碰撞。最终栈里面的元素就是最后能留存的robots。 From a5527fa8f6e78a42541649c9e81c4ae349bffc89 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 12:06:00 -0700 Subject: [PATCH 1953/2729] Create 2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp --- ...um-Operations-to-Make-the-Integer-Zero.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp diff --git a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp new file mode 100644 index 000000000..8bbf04ca8 --- /dev/null +++ b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp @@ -0,0 +1,20 @@ +using LL = long long; +class Solution { +public: + int makeTheIntegerZero(int num1, int num2) + { + long long x = num1; + long long y = num2; + int k = 1; + while (1) + { + x -= y; + if (x < k) return -1; + + int count = __builtin_popcountll(x); + if (count <= k) return k; + k++; + } + return -1; + } +}; From 814289cfae42366fc0312ac61d18ef64f2639502 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 12:06:27 -0700 Subject: [PATCH 1954/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 266d35083..fe5d2fc60 100644 --- a/Readme.md +++ b/Readme.md @@ -1353,7 +1353,8 @@ [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) -[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) +[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) +[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 2613e4aa6d070c19d41bf6a8cc5bc75b0465af46 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 15:15:46 -0700 Subject: [PATCH 1955/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md diff --git a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md new file mode 100644 index 000000000..6801d6a1f --- /dev/null +++ b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md @@ -0,0 +1,5 @@ +### 2749.Minimum-Operations-to-Make-the-Integer-Zero + +本题就是寻找最小的操作次数k,使得`num1-k*num2`可以表示为k个`2^i`相加的形式,标记为(*)。 + +我们观察k个`2^i`相加,它有最小值就是k。所以如果`num1-k*num2 Date: Tue, 4 Jul 2023 15:16:34 -0700 Subject: [PATCH 1956/2729] Update Readme.md --- .../2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md index 6801d6a1f..0a59bc74b 100644 --- a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md +++ b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md @@ -2,4 +2,4 @@ 本题就是寻找最小的操作次数k,使得`num1-k*num2`可以表示为k个`2^i`相加的形式,标记为(*)。 -我们观察k个`2^i`相加,它有最小值就是k。所以如果`num1-k*num2 Date: Tue, 4 Jul 2023 15:47:12 -0700 Subject: [PATCH 1957/2729] Create 2745.Construct-the-Longest-New-String.cpp --- .../2745.Construct-the-Longest-New-String.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Greedy/2745.Construct-the-Longest-New-String/2745.Construct-the-Longest-New-String.cpp diff --git a/Greedy/2745.Construct-the-Longest-New-String/2745.Construct-the-Longest-New-String.cpp b/Greedy/2745.Construct-the-Longest-New-String/2745.Construct-the-Longest-New-String.cpp new file mode 100644 index 000000000..9a3d1bfde --- /dev/null +++ b/Greedy/2745.Construct-the-Longest-New-String/2745.Construct-the-Longest-New-String.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int longestString(int x, int y, int z) + { + int t = x+y+z-max(0, (max(x,y)-min(x,y)-1)); + return t*2; + } +}; From 236b421e28c558ee6cd4b90671e7875667649cc8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 15:47:41 -0700 Subject: [PATCH 1958/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index fe5d2fc60..c92c36cdd 100644 --- a/Readme.md +++ b/Readme.md @@ -1353,8 +1353,9 @@ [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) -[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) -[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) +[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) +[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) +[2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From ce8c41a6753fccfcbeeae63142a03f6ec763bcae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 15:48:02 -0700 Subject: [PATCH 1959/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c92c36cdd..69443ea9b 100644 --- a/Readme.md +++ b/Readme.md @@ -1354,7 +1354,7 @@ [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) [2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) -[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) +[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) From 777af70147ba5a93de5424d80c9d7a59754033f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 15:52:40 -0700 Subject: [PATCH 1960/2729] Create Readme.md --- Greedy/2745.Construct-the-Longest-New-String/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2745.Construct-the-Longest-New-String/Readme.md diff --git a/Greedy/2745.Construct-the-Longest-New-String/Readme.md b/Greedy/2745.Construct-the-Longest-New-String/Readme.md new file mode 100644 index 000000000..330d99ac9 --- /dev/null +++ b/Greedy/2745.Construct-the-Longest-New-String/Readme.md @@ -0,0 +1,7 @@ +### 2745.Construct-the-Longest-New-String + +当我们仅考虑AA和BB时,我们可以将其交替串联,如BBAABBAA...,注意最后可以AA或BB结尾,使用两种片段的个数最多差1。这样能使用到的片段个数是 `min(x,y)*2 + min(abs(x-y),1)`. + +然后考虑所有的AB,只需将其插入任何BB与AA之间即可,不影响之前的构造。 + +所以最终能使用到的片段个数是 `min(x,y)*2 + min(abs(x-y),1) +z`. From f5c75c44b9654cc1956a1872ee7be37da6de845f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 16:52:40 -0700 Subject: [PATCH 1961/2729] Create 2746.Decremental-String-Concatenation.cpp --- .../2746.Decremental-String-Concatenation.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp diff --git a/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp b/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp new file mode 100644 index 000000000..b527768e3 --- /dev/null +++ b/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp @@ -0,0 +1,33 @@ +class Solution { + int memo[1005][26][26]; +public: + int minimizeConcatenatedLength(vector& words) + { + return words[0].size() + dfs(1, words[0][0]-'a', words[0].back()-'a', words); + } + + // The minimum letters to be added if we construct the first i words with start & end. + int dfs(int i, int start, int end, vector& words) + { + if (i==words.size()) return 0; + + if (memo[i][start][end]!=0) return memo[i][start][end]; + + int ret = INT_MAX/2; + int a = words[i][0]-'a', b = words[i].back()-'a'; + int len = words[i].size(); + + if (end==a) + ret = min(ret, len-1 + dfs(i+1, start, b, words)); + else + ret = min(ret, len + dfs(i+1, start, b, words)); + + if (start==b) + ret = min(ret, len-1 + dfs(i+1, a, end, words)); + else + ret = min(ret, len + dfs(i+1, a, end, words)); + + memo[i][start][end] = ret; + return ret; + } +}; From db01645d5413e39c9b34f77a126fb61b5231e946 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 16:53:13 -0700 Subject: [PATCH 1962/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 69443ea9b..21a878f94 100644 --- a/Readme.md +++ b/Readme.md @@ -516,7 +516,8 @@ [403.Frog-Jump](https://github.com/wisdompeak/LeetCode/tree/master/DFS/403.Frog-Jump) (M+) [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) [1340.Jump-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1340.Jump-Game-V) (M+) -[1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +[1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +[2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) [1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) From 60ec4f5b9a71162cc4dafad2ebe6743ac7289abf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 16:53:37 -0700 Subject: [PATCH 1963/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 21a878f94..9191152f0 100644 --- a/Readme.md +++ b/Readme.md @@ -516,7 +516,7 @@ [403.Frog-Jump](https://github.com/wisdompeak/LeetCode/tree/master/DFS/403.Frog-Jump) (M+) [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) [1340.Jump-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1340.Jump-Game-V) (M+) -[1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +[1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) [2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) From 49d03176b0a5c91c4960a743329f41f77ab2fcae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 17:06:10 -0700 Subject: [PATCH 1964/2729] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 DFS/2746.Decremental-String-Concatenation/Readme.md diff --git a/DFS/2746.Decremental-String-Concatenation/Readme.md b/DFS/2746.Decremental-String-Concatenation/Readme.md new file mode 100644 index 000000000..a9fc78ce9 --- /dev/null +++ b/DFS/2746.Decremental-String-Concatenation/Readme.md @@ -0,0 +1,22 @@ +### 2746.Decremental-String-Concatenation + +考虑到n的数量不大,估计可以暴力搜索。顺次遍历每一个单词,我们只需要考察将其加在已有str的前面还是后面两种决策。这看上去复杂度会有2^50,但是我们事实我们并不需要枚举这么多状态。假设前两个单词{abc,aec},那么这两个单词的拼接方式对于后续的选择而言没有不同,因为都是`a****c`。我们能否压缩长度的关键,其实只需要关注str的第一个和最后一个字符即可。于是我们实际需要枚举的状态最多只有50*26*26种。 + +由此我们可以定义递归函数`int dfs(int i, int start, int end)`,表示the minimum length to be added if we construct the first i words with start & end. 也就是说,当前i个单词构造出来的str以start开头、end结尾时,我们需要考虑如何使用words[i]:很明显两种方案,放在前面或者放在后面。此时我们就可以根据start/end与words[i]的首尾字符,进行递归处理: +```cpp +int a = words[i][0]-'a', b = words[i].back()-'a'; +// 放后面 +if (end==a) + ret = min(ret, len-1 + dfs(i+1, start, b, words)); +else + ret = min(ret, len + dfs(i+1, start, b, words)); + +// 放前面 +if (start==b) + ret = min(ret, len-1 + dfs(i+1, a, end, words)); +else + ret = min(ret, len + dfs(i+1, a, end, words)); +``` +最终的答案就是初始调用的`words[0].size() + dfs(1, words[0][0], words[0].back())`,因为对于words[0]我们只有唯一的构造形式。 + +另外,我们必然要用记忆化来避免相同参数的dfs重复调用。 From ad7bbb9395f3f034926d5a90a6dbcc61a71720da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 22:30:21 -0700 Subject: [PATCH 1965/2729] Create 2747.Count-Zero-Request-Servers.cpp --- .../2747.Count-Zero-Request-Servers.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Two_Pointers/2747.Count-Zero-Request-Servers/2747.Count-Zero-Request-Servers.cpp diff --git a/Two_Pointers/2747.Count-Zero-Request-Servers/2747.Count-Zero-Request-Servers.cpp b/Two_Pointers/2747.Count-Zero-Request-Servers/2747.Count-Zero-Request-Servers.cpp new file mode 100644 index 000000000..e2154cd91 --- /dev/null +++ b/Two_Pointers/2747.Count-Zero-Request-Servers/2747.Count-Zero-Request-Servers.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + vector countServers(int n, vector>& logs, int x, vector& queries) + { + for (int i=0; i>q; + for (int i=0; irets(q.size()); + unordered_mapMap; + int i = 0; + int j = 0; + for (auto qq: q) + { + int t = qq[0], idx = qq[1]; + while (j Date: Tue, 4 Jul 2023 22:30:55 -0700 Subject: [PATCH 1966/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9191152f0..c001bed7a 100644 --- a/Readme.md +++ b/Readme.md @@ -50,7 +50,8 @@ [2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) [2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (M+) [2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2564.Substring-XOR-Queries) (H-) -[2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) +[2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) +[2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 3a8eb5c84ad6df00f3c1e6c5fecfafe0f93345f1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:07:17 -0700 Subject: [PATCH 1967/2729] Create Readme.md --- Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md diff --git a/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md b/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md new file mode 100644 index 000000000..360b3d7a9 --- /dev/null +++ b/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md @@ -0,0 +1,5 @@ +### 2747.Count-Zero-Request-Servers + +我们将query按照时间顺序排序之后逐个处理,不难发现这就是一个移动的固定长度滑窗。我们需要计算的就是每处滑窗位置时,包含了多少个不同的servers。 + +更具体地,我们先将所有的server request排序。我们用一个Hash表来维护滑窗内的server。当处理某个query对应的时段[t-x,t]时,我们将所有小于等于t的request加入Hash表,同时将小于t-x的request移出Hash表。此时Hash表内的key的数目就是non-zero request servers. 此外,当处理下一个query对应的时段时,在request序列上的滑窗必然是单调移动的。 From ad11778f3a6402ce345833a0e9c1f5c445b2eae2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:09:01 -0700 Subject: [PATCH 1968/2729] Update Readme.md --- Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md b/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md index 360b3d7a9..f6be0cb18 100644 --- a/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md +++ b/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md @@ -1,5 +1,5 @@ ### 2747.Count-Zero-Request-Servers -我们将query按照时间顺序排序之后逐个处理,不难发现这就是一个移动的固定长度滑窗。我们需要计算的就是每处滑窗位置时,包含了多少个不同的servers。 +我们先将所有的server request排序。再将query按照时间顺序排序之后逐个处理,不难发现这就是一个固定长度的滑窗。我们需要计算的就是每处滑窗位置时,里面包含了多少个不同的server request。 -更具体地,我们先将所有的server request排序。我们用一个Hash表来维护滑窗内的server。当处理某个query对应的时段[t-x,t]时,我们将所有小于等于t的request加入Hash表,同时将小于t-x的request移出Hash表。此时Hash表内的key的数目就是non-zero request servers. 此外,当处理下一个query对应的时段时,在request序列上的滑窗必然是单调移动的。 +更具体地,我们用一个Hash表来维护滑窗内的server。当处理某个query对应的时段[t-x,t]时,我们将所有小于等于t的request加入Hash表,同时将小于t-x的request移出Hash表。此时Hash表内的key的数目就是non-zero request servers. 此外,当处理下一个query对应的时段时,在request序列上的滑窗必然是单调移动的。 From f599701528d2e6d4697fb17e56989e738d7349fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:50:19 -0700 Subject: [PATCH 1969/2729] Create 2753.Count-Houses-in-a-Circular-Street-II.cpp --- ...3.Count-Houses-in-a-Circular-Street-II.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Greedy/2753.Count-Houses-in-a-Circular-Street-II/2753.Count-Houses-in-a-Circular-Street-II.cpp diff --git a/Greedy/2753.Count-Houses-in-a-Circular-Street-II/2753.Count-Houses-in-a-Circular-Street-II.cpp b/Greedy/2753.Count-Houses-in-a-Circular-Street-II/2753.Count-Houses-in-a-Circular-Street-II.cpp new file mode 100644 index 000000000..60d204b95 --- /dev/null +++ b/Greedy/2753.Count-Houses-in-a-Circular-Street-II/2753.Count-Houses-in-a-Circular-Street-II.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a street. + * class Street { + * public: + * Street(vector doors); + * void closeDoor(); + * bool isDoorOpen(); + * void moveRight(); + * }; + */ +class Solution { +public: + int houseCount(Street* street, int k) + { + while (!street->isDoorOpen()) + street->moveRight(); + street->moveRight(); + + int step = 1; + int lastOpen = 0; + for (int i=0; iisDoorOpen()) + { + lastOpen = step; + street->closeDoor(); + } + step++; + street->moveRight(); + } + return lastOpen; + } +}; From dfa8b97c570d6aecf42f658d88fe510fcf31d4bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:50:52 -0700 Subject: [PATCH 1970/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c001bed7a..16dc9c089 100644 --- a/Readme.md +++ b/Readme.md @@ -1358,6 +1358,7 @@ [2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) [2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) +[2753.Count-Houses-in-a-Circular-Street-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2753.Count-Houses-in-a-Circular-Street-II) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From c07130f65eedfc57e3a259959a7aee56f33193bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:54:51 -0700 Subject: [PATCH 1971/2729] Create Readme.md --- Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md diff --git a/Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md b/Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md new file mode 100644 index 000000000..47e7a2e56 --- /dev/null +++ b/Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md @@ -0,0 +1,5 @@ +### 2753.Count-Houses-in-a-Circular-Street-II + +我们先找到一处状态为open的门。然后从下一个位置作为起点,连续走k格,图中如果遇到任何open的门就将其关闭,但同时记录并保持更新lastOpen相对于起点的距离。 + +走完k格之后,lastOpen一定就是起点之前的那扇门,于是lastOpen相对于起点的距离就是整圈的长度。 From 7ff5c2237491618aa14416c66f4adabae723f88b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 21:06:44 -0700 Subject: [PATCH 1972/2729] Create 2741.Special-Permutations.cpp --- .../2741.Special-Permutations.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 DFS/2741.Special-Permutations/2741.Special-Permutations.cpp diff --git a/DFS/2741.Special-Permutations/2741.Special-Permutations.cpp b/DFS/2741.Special-Permutations/2741.Special-Permutations.cpp new file mode 100644 index 000000000..2a681d8f7 --- /dev/null +++ b/DFS/2741.Special-Permutations/2741.Special-Permutations.cpp @@ -0,0 +1,50 @@ +using LL = long long; +class Solution { + LL memo[14][1<<14]; + LL M = 1e9+7; + int n; + unordered_map>Map; +public: + int specialPerm(vector& nums) + { + n = nums.size(); + + for (int i=0; i>q)&1) continue; + ret += dfs(i+1, q, state+(1< Date: Wed, 5 Jul 2023 21:07:13 -0700 Subject: [PATCH 1973/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 16dc9c089..7334e2b46 100644 --- a/Readme.md +++ b/Readme.md @@ -518,6 +518,7 @@ [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) [1340.Jump-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1340.Jump-Game-V) (M+) [1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +[2741.Special-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2741.Special-Permutations) (M+) [2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) From dde09314f1268910c981ef195f8092c08541251e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 21:22:06 -0700 Subject: [PATCH 1974/2729] Create Readme.md --- DFS/2741.Special-Permutations/Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 DFS/2741.Special-Permutations/Readme.md diff --git a/DFS/2741.Special-Permutations/Readme.md b/DFS/2741.Special-Permutations/Readme.md new file mode 100644 index 000000000..1dc18d2db --- /dev/null +++ b/DFS/2741.Special-Permutations/Readme.md @@ -0,0 +1,18 @@ +### 2741.Special-Permutations + +考虑到数据规模,算法基本是暴力搜索。我们确定第i位取数字p的时候,那么第i+1位的选择会是有限的几种(要求相邻两位互质)。于是就可以穷举这些选择,然后就用相同的形式递归处理下一个位置。此外,为了记录我们已经选择了哪些数字(不能用于当前的选择),我们需要一个n位的二进制编码state来记录。 + +由此,我们可以写出基本的DFS形式。令`dfs(i,p,state)`表示在第i个位置取数字p、并且已经选取的数字集合编码是state时,可以构造的合法序列的个数。我们有递归的框架: +```cpp +dfs(int i, int p, int state) { + int ret = 0; + for (int q: 与p互质且不在state里的数字) { + ret += dfs(i+1, q, state+(1< Date: Sat, 8 Jul 2023 15:57:50 -0700 Subject: [PATCH 1975/2729] Create 2768.Number-of-Black-Blocks.cpp --- .../2768.Number-of-Black-Blocks.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Others/2768.Number-of-Black-Blocks/2768.Number-of-Black-Blocks.cpp diff --git a/Others/2768.Number-of-Black-Blocks/2768.Number-of-Black-Blocks.cpp b/Others/2768.Number-of-Black-Blocks/2768.Number-of-Black-Blocks.cpp new file mode 100644 index 000000000..1e20e5394 --- /dev/null +++ b/Others/2768.Number-of-Black-Blocks/2768.Number-of-Black-Blocks.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { + int n; +public: + LL encode(LL x, LL y) + { + return x*n + y; + } + + vector countBlackBlocks(int m, int n, vector>& coordinates) + { + unordered_mapMap; + this->n = n; + + int count = 0; + for (auto& c: coordinates) + { + int x = c[0], y = c[1]; + for (int i=x-1; i<=x; i++) + for (int j=y-1; j<=y; j++) + { + if (i>=0 && i=0 && jrets(5); + for (auto [k,v]: Map) + rets[v]+=1; + + rets[0] = LL(m-1)*LL(n-1) - rets[1] - rets[2] - rets[3] -rets[4]; + + return rets; + } +}; From ed8bbed08f6388c3992d9a2a517ec9dab4fd0ade Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 16:01:20 -0700 Subject: [PATCH 1976/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7334e2b46..51ae08e79 100644 --- a/Readme.md +++ b/Readme.md @@ -1471,7 +1471,8 @@ [1714.Sum-Of-Special-Evenly-Spaced-Elements-In-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1714.Sum-Of-Special-Evenly-Spaced-Elements-In-Array) (H) [1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/Others/1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions) (M+) [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) -[2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) +[2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) +[2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From c7f4046b4d0548af6296a7134c7bcbb59aff7c10 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 16:05:39 -0700 Subject: [PATCH 1977/2729] Create Readme.md --- Others/2768.Number-of-Black-Blocks/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2768.Number-of-Black-Blocks/Readme.md diff --git a/Others/2768.Number-of-Black-Blocks/Readme.md b/Others/2768.Number-of-Black-Blocks/Readme.md new file mode 100644 index 000000000..a10a8cbc6 --- /dev/null +++ b/Others/2768.Number-of-Black-Blocks/Readme.md @@ -0,0 +1,7 @@ +### 2768.Number-of-Black-Blocks + +为了不重不漏地数block,我们需要定义cell与block的关系。我们令每个block左上角的cell作为该block的“代表”,那么数block就转换成了数cell。 + +对于每个black cell,我们设想它可能属于block。显然,它最多属于四个不同的block,这些block对应的“代表”就是(x-1,y-1),(x,y-1),(x-1,y),(x,y).于是我们只需要给这四个block(的代表)各自加上一票即可。最终,每个block(的代表)所得的票数就意味着它所包含的black cell的个数。 + +注意,在右边界和下边界的cell是不能代表一个合法的block的。 From 547b476c5eaad290c45284ec95af32e8bcee0079 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 17:24:10 -0700 Subject: [PATCH 1978/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 51ae08e79..3d2e91684 100644 --- a/Readme.md +++ b/Readme.md @@ -873,7 +873,7 @@ [903.Valid-Permutations-for-DI-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence) (H) [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) * ``Infer future from current`` -[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) +[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) [2742.Painting-the-Walls](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2742.Painting-the-Walls) (H) * ``maximum subarray`` [053.Maximum-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/053.Maximum-Subarray) (E+) From 7825a4c44029c99659aa4f877f94e2681939cf5b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 17:34:54 -0700 Subject: [PATCH 1979/2729] Create Readme.md --- .../2742.Painting-the-Walls/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Dynamic_Programming/2742.Painting-the-Walls/Readme.md diff --git a/Dynamic_Programming/2742.Painting-the-Walls/Readme.md b/Dynamic_Programming/2742.Painting-the-Walls/Readme.md new file mode 100644 index 000000000..4465e4a1d --- /dev/null +++ b/Dynamic_Programming/2742.Painting-the-Walls/Readme.md @@ -0,0 +1,15 @@ +### 2742.Painting-the-Walls + +#### 解法1: +此题类似956.Tallest-Billboard,有约束要求两边的高度差为0.所以我们要在dp中加一个维度来标记高度差的状态。 + +本题我们可以类似地,令dp[i][j]表示完成前i面墙的喷涂需要的最小代价,并且满足其中使用付费工人的时间与使用免费工人的时间之差是j。我们最终的答案是`min{dp[n][j]} where j>=0`. + +我们遍历j的范围时,只需要从-n到n。这是因为如果j<=-n,说明至少使用了n个小时的免费工人,必然已经把任务完成。如果j>=n,说明至少使用了n个小时的付费工人,根据规则我们必然可以搭配n个小时的免费工人,也必然已经把任务完成了。所以dp计算的二维循环的时间复杂度是o(n^2). + +注意,本题的转移方程是“从现在到未来的形式”。即已知dp[i][j],我们考虑第i+1个任务时,根据付费还是免费工人两种方案,给未来的两个状态提供优化: +```cpp +dp[i+1][j-1] = min(dp[i+1][j-1], dp[i][j]); +dp[i+1][j+time[i+1]] = min(dp[i+1][j+time[i+1]], dp[i][j+OFFSET]+cost[i+1]); +``` +并且我们要注意`j+time[i+1]`可能会大于n,我们要取cap。这也是我们无法用“从现在到未来的形式”的原因,因为我们无法穷举`dp[i][n]=...`的来源。 From e9246027a0f946288d33b21ff8ed1569d901f833 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 17:39:58 -0700 Subject: [PATCH 1980/2729] Create 2742.Painting-the-Walls_v2.cpp --- .../2742.Painting-the-Walls_v2.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v2.cpp diff --git a/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v2.cpp b/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v2.cpp new file mode 100644 index 000000000..7e6e82954 --- /dev/null +++ b/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v2.cpp @@ -0,0 +1,24 @@ +class Solution { + int dp[505][505]; +public: + int paintWalls(vector& cost, vector& time) + { + int n = cost.size(); + cost.insert(cost.begin(),0); + time.insert(time.begin(),0); + + for (int i=0; i<=n; i++) + for (int j=0; j<=n; j++) + dp[i][j] = INT_MAX/2; + dp[0][0] = 0; + + for (int i=0; i Date: Sat, 8 Jul 2023 17:48:35 -0700 Subject: [PATCH 1981/2729] Update Readme.md --- .../2742.Painting-the-Walls/Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Dynamic_Programming/2742.Painting-the-Walls/Readme.md b/Dynamic_Programming/2742.Painting-the-Walls/Readme.md index 4465e4a1d..69f6f884f 100644 --- a/Dynamic_Programming/2742.Painting-the-Walls/Readme.md +++ b/Dynamic_Programming/2742.Painting-the-Walls/Readme.md @@ -13,3 +13,17 @@ dp[i+1][j-1] = min(dp[i+1][j-1], dp[i][j]); dp[i+1][j+time[i+1]] = min(dp[i+1][j+time[i+1]], dp[i][j+OFFSET]+cost[i+1]); ``` 并且我们要注意`j+time[i+1]`可能会大于n,我们要取cap。这也是我们无法用“从现在到未来的形式”的原因,因为我们无法穷举`dp[i][n]=...`的来源。 + +#### 解法2: +此题还有另外一种巧解。我们将每个付费工人强制捆绑若干个免费工人,即看做可以花cost[i]的代价实现time[i]+1的任务。问至少(不是恰好)实现n个任务的最小代价。这是因为“强制捆绑若干个免费工人”的做法无法保证总完成的任务恰好n,极有可能超过n,如果那种情况发生,我们可以再任意踢掉免费的工人(将完成任务的数量降到n)。 + +此时我们定义状态dp[i][j]表示前i个工人(不一定都用)完成j个任务的最小代价。那么这就是一个典型的背包问题。 + +同理,我们也得用“从现在到未来的形式”,即已知dp[i][j],我们考虑第i+1个工人,根据是否雇佣他两种方案,给未来的两个状态提供优化: +```cpp +dp[i+1][j+time[i+1]+1] = min(dp[i+1][j+time[i+1]+1], dp[i][j]+cost[i+1]); +dp[i+1][j] = min(dp[i+1][j], dp[i][j]); +``` +同理,我们也要注意`j+time[i+1]+1`必须cap by n。 + +最终返回的答案是dp[n][n]. From e24669399eea5a4ca6acca9c696d4988fa2131f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 22:19:05 -0700 Subject: [PATCH 1982/2729] Create 2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp --- ...-Make-All-Array-Elements-Equal-to-Zero.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp diff --git a/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp b/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp new file mode 100644 index 000000000..8abebd858 --- /dev/null +++ b/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool checkArray(vector& nums, int k) + { + if (k==1) return true; + int n = nums.size(); + vectordiff(n+1, 0); + + int cur = 0; + for (int i=0; inums[i]) return false; + int delta = nums[i] - cur; + if (delta > 0 && i+k < n) + diff[i+k] -= delta; + cur += delta; + } + + return cur+diff[n-1] == nums[n-1]; + } +}; From 4664abcfc13d8cc0f761bfc62ad4f439236e065e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 22:23:13 -0700 Subject: [PATCH 1983/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3d2e91684..69df10d14 100644 --- a/Readme.md +++ b/Readme.md @@ -1456,7 +1456,8 @@ [2327.Number-of-People-Aware-of-a-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Others/2327.Number-of-People-Aware-of-a-Secret) (H-) [2381.Shifting-Letters-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/2381.Shifting-Letters-II) (M) [2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) -[2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) +[2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) +[2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero) (H-) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From ddc29e584221b51a488d6571ff0e2349a11ba05c Mon Sep 17 00:00:00 2001 From: Yi Yao Date: Sun, 9 Jul 2023 07:26:58 +0200 Subject: [PATCH 1984/2729] Update Readme.md 26*26 = 676 --- .../2272.Substring-With-Largest-Variance/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md index 9b3376e01..107555228 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md @@ -27,7 +27,7 @@ ``` 特别注意,curSum0的初始值可以是0,但是curSum1的初始值必须设置为INT_MIN. -这样,总的时间复杂度是o(256n). +这样,总的时间复杂度是o(676n). #### 解法2 我们发现在上面的表达式里,当nums[i]不是1也不是-1的时候,curSum0和curSum1都没有更新,循环是空跑的。所以我们其实只需要关心那些nums[i]非0的位置。 @@ -36,7 +36,7 @@ 注意i和j可能会有其中某一个先走到尽头。如果其中一个走到尽头,那么我们必然移动另一个指针。 -这样的时间复杂度是多少?看上去仍然是是o(256n),但事实上,我们每固定了一个最大频次的字符a,其他所有字符都被看做为最小频次的字符,且只访问了一次。所以时间复杂度优化到了o(26n). +这样的时间复杂度是多少?看上去仍然是是o(676n),但事实上,我们每固定了一个最大频次的字符a,其他所有字符都被看做为最小频次的字符,且只访问了一次。所以时间复杂度优化到了o(26n). 补充: 有网友问,我感觉第二种做法不是严格的O(26 * N). https://youtu.be/P6KnO-Dw0Fo?t=2204 即使可以认为b的pos1循环遍26次就是O(N) (e.g. 小x, 小y), 但是a的pos0在内层循环也遍历了26次而不是一次. 所以两者加一起肯定大于o(N)但是小于O(26N) From f2d2242678503d839d7f12418eafa6ee4e993548 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 23:57:29 -0700 Subject: [PATCH 1985/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/Readme.md diff --git a/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/Readme.md b/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/Readme.md new file mode 100644 index 000000000..ff794a194 --- /dev/null +++ b/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/Readme.md @@ -0,0 +1,13 @@ +### 2745.Construct-the-Longest-New-String + +我们将问题反过来看,就是问是否能将一个长度为n的全0数组,通过若干次的“k-size subarray +1”操作变成nums。 + +显然,对于第一个元素,想实现0->nums[0],相差`delta=nums[0]-0`,我们必须通过将[0:k-1]整体增加`delta`来实现。 + +此时观察第二个元素,已经是nums[0]了。如果这个数值大于nums[1],显然我们无法通过任何只增不减的操作实现变换,故返回false。否则意味着我们还差`delta=nums[1]-nums[0]`,必须需要将[1:k]整体提升`delta`。 + +从上面的过程我们已经发现规律。从前往后遍历时,每个位置i可能已经有了某个数值(受之前操作的影响)。为了实现与预定目标nums[i]的匹配(假设相差delta),那必须进行操作将[i:i+k-1]整体提升delta。而这些操作会影响到后续位置的数值。我们通过当前值与预期的nums[i]的大小关系,可以判定是否无解。 + +最终,如果最后一个元素的当前值与nums[n-1]完全一致时,说明整套操作能够实现目标。 + +很明显,对于区间整体的增减,我们需要差分数组来标记。比如,我们要将[i:i+k-1]整体提升d,那么只需要标记`diff[i]+=d, diff[i+k]-=d`即可. 从零开始,一路前往后累积diff差分即可恢复每个位置上的数值。 From afa5a4d897dee53406d06d7ace073934ed1b8ee6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 15 Jul 2023 15:33:05 -0700 Subject: [PATCH 1986/2729] Create 2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp --- ...s-Array-a-Preorder-of-Some-Binary-Tree.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp diff --git a/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp new file mode 100644 index 000000000..50572036e --- /dev/null +++ b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool isPreorder(vector>& nodes) + { + stackstk; + for (auto& node: nodes) + { + if (stk.empty() || node[1] == stk.top()) + stk.push(node[0]); + else + { + while (!stk.empty() && node[1] != stk.top()) + stk.pop(); + if (stk.empty()) return false; + stk.push(node[0]); + } + } + + return true; + } +}; From e51664e6596df2da33c7ee5e1696bec7220b9cee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 15 Jul 2023 15:34:01 -0700 Subject: [PATCH 1987/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 69df10d14..1171a056f 100644 --- a/Readme.md +++ b/Readme.md @@ -369,7 +369,8 @@ [1586.Binary-Search-Tree-Iterator-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1586.Binary-Search-Tree-Iterator-II) (H) [2197.Replace-Non-Coprime-Numbers-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2197.Replace-Non-Coprime-Numbers-in-Array) (H-) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) -[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) +[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) +[2764.is-Array-a-Preorder-of-Some-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree) (M+) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) From 318ca9f3878bd53e3b56794a7ae8b58797b8d2b2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 15 Jul 2023 15:42:31 -0700 Subject: [PATCH 1988/2729] Create Readme.md --- Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md diff --git a/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md new file mode 100644 index 000000000..db2c54a77 --- /dev/null +++ b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md @@ -0,0 +1,5 @@ +### 2764.is-Array-a-Preorder-of-Some-Binary-Tree + +我们维护一个栈来存放访问过的节点。 + +将一棵树进行先序遍历的话,首先访问的必然是最靠左侧的一条支链的节点直至到叶子,这个过程中,每个新元素都是上一个元素的孩子。此后,接下来访问的节点就不再是上一个元素的左孩子,但必然是这条支链的某个位置的右子树。于是我们可以通过不断退出栈顶元素,来回退到这个分叉点。如果找到了,那么就继续按照之前的规则访问元素;如果找不到,那就意味着这个序列不是先序遍历。 From 6c5e5312566e0e209e17230c453aedc09bf66b6d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Jul 2023 00:58:30 -0700 Subject: [PATCH 1989/2729] Create 2781.Length-of-the-Longest-Valid-Substring.cpp --- ....Length-of-the-Longest-Valid-Substring.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 String/2781.Length-of-the-Longest-Valid-Substring/2781.Length-of-the-Longest-Valid-Substring.cpp diff --git a/String/2781.Length-of-the-Longest-Valid-Substring/2781.Length-of-the-Longest-Valid-Substring.cpp b/String/2781.Length-of-the-Longest-Valid-Substring/2781.Length-of-the-Longest-Valid-Substring.cpp new file mode 100644 index 000000000..97c4358c1 --- /dev/null +++ b/String/2781.Length-of-the-Longest-Valid-Substring/2781.Length-of-the-Longest-Valid-Substring.cpp @@ -0,0 +1,50 @@ +using LL = long long; +class Solution { + unordered_setSet; + unordered_map>Map; +public: + int longestValidSubstring(string word, vector& forbidden) + { + for (auto& s: forbidden) + { + LL code = 0; + for (auto ch: s) + code = (code << 5) + (ch-'a'+1); + Set.insert(code); + } + + for (int len = 1; len<=10; len++) + helper(word, len); + + int n = word.size(); + int rightBound = n; + int ret = 0; + for (int i=n-1; i>=0; i--) + { + if (Map.find(i)!=Map.end()) + { + for (int j: Map[i]) + rightBound = min(rightBound, j); + } + ret = max(ret, rightBound-i); + } + return ret; + + } + + void helper(string&word, int len) + { + int n = word.size(); + LL code = 0; + for (int i=0; i=len) + code &= (1LL<<(5*(len-1)))-1; + + code = (code << 5) + word[i]-'a'+1; + + if (i>=len-1 && Set.find(code)!=Set.end()) + Map[i-len+1].push_back(i); + } + } +}; From 2a675d7d62835bb5c62faf383b4a522b7be2dbb1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Jul 2023 00:58:56 -0700 Subject: [PATCH 1990/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1171a056f..b5bb1ff68 100644 --- a/Readme.md +++ b/Readme.md @@ -957,7 +957,8 @@ [2156.Find-Substring-With-Given-Hash-Value](https://github.com/wisdompeak/LeetCode/tree/master/String/2156.Find-Substring-With-Given-Hash-Value) (M) [2168.Unique-Substrings-With-Equal-Digit-Frequency](https://github.com/wisdompeak/LeetCode/tree/master/String/2168.Unique-Substrings-With-Equal-Digit-Frequency) (M+) [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) -[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) +[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) +[2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) From 9371858fb750059fddfdeaceecb13cdf03373903 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:24:18 -0700 Subject: [PATCH 1991/2729] Create 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp --- ...to-Express-an-Integer-as-Sum-of-Powers.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp new file mode 100644 index 000000000..d259288a6 --- /dev/null +++ b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp @@ -0,0 +1,50 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + int n; + LL dp[305][305]; +public: + LL getXPower(int a, int x) + { + LL ret = 1; + for (int i=0; i n) + return INT_MAX; + } + return ret; + } + + int numberOfWays(int n, int x) + { + this->n = n; + + dp[0][0] = 1; + + for (int i=1; i<=n; i++) + { + for (int j=1; j<=n; j++) + { + LL cur = getXPower(j,x); + if (cur>i) break; + + for (int jj=0; jjn) break; + ret += dp[n][j]; + ret %= M; + } + return ret; + } +}; From 48aaeeb52ab5bf750438fbbf37c194409185e8da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:25:15 -0700 Subject: [PATCH 1992/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b5bb1ff68..c21b77544 100644 --- a/Readme.md +++ b/Readme.md @@ -701,6 +701,7 @@ [2431.Maximize-Total-Tastiness-of-Purchased-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits) (M+) [2484.Count-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences) (H-) [2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix) (H-) +[2787.Ways-to-Express-an-Integer-as-Sum-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers) (M+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From db38b37e5b4e9b2c7cd4824998a81c0c15ad9417 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:50:53 -0700 Subject: [PATCH 1993/2729] Create 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp --- ...Express-an-Integer-as-Sum-of-Powers_v2.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp new file mode 100644 index 000000000..31537e934 --- /dev/null +++ b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp @@ -0,0 +1,25 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[305]; +public: + int numberOfWays(int n, int x) + { + dp[0] = 1; + + for (int i=1; i<=n; i++) + { + LL num = 1; + for (int t=0; t= num; s--) + { + dp[s] += dp[s-num]; + dp[s] %= M; + } + } + + return dp[n]; + } +}; From 644d3c0e11d85cff0932587da82744cdfcd2fbc1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:58:34 -0700 Subject: [PATCH 1994/2729] Update 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp --- ...to-Express-an-Integer-as-Sum-of-Powers.cpp | 52 ++++++------------- 1 file changed, 15 insertions(+), 37 deletions(-) diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp index d259288a6..9c0e4656c 100644 --- a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp +++ b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp @@ -1,50 +1,28 @@ using LL = long long; LL M = 1e9+7; -class Solution { - int n; +class Solution { LL dp[305][305]; -public: - LL getXPower(int a, int x) - { - LL ret = 1; - for (int i=0; i n) - return INT_MAX; - } - return ret; - } - +public: int numberOfWays(int n, int x) - { - this->n = n; - + { dp[0][0] = 1; - for (int i=1; i<=n; i++) - { + for (int i=0; i<=n; i++) for (int j=1; j<=n; j++) { - LL cur = getXPower(j,x); - if (cur>i) break; - - for (int jj=0; jjn) break; - ret += dp[n][j]; - ret %= M; - } - return ret; + + return dp[n][n]; } }; From 4fcc55b196987d9022590e31e06e629a8d5ef77b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:58:47 -0700 Subject: [PATCH 1995/2729] Rename 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp to 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp --- ...pp => 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/{2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp => 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp} (100%) diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp similarity index 100% rename from Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp rename to Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp From 8edacc27f485e30efd746b64def27f018562969b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 12:06:25 -0700 Subject: [PATCH 1996/2729] Create Readmd.md --- .../Readmd.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md new file mode 100644 index 000000000..d5cd9e540 --- /dev/null +++ b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md @@ -0,0 +1,13 @@ +### 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers + +#### 解法1: +令dp[i][j]表示数字i可以分解的方案数目,并且要求分解出的最大的因子不能超过j。 + +如果该分解不包含`j^x`,那么就有`dp[i][j] = dp[i][j-1]`; 如果该分解包含了`j^x`,并且`i>=j^x`,则有`dp[i][j] = dp[i-j^x][j-1]`. 两者之后即是dp[i][j]。 + +最终答案是dp[n][n]. + +#### 解法2: +令dp[i]表示数字i可以分解的方案数目。 + +我们从小到大依次考虑因子1,2,3,...n的使用。当可以使用j^x时,所有的dp数列可以更新:`dp_new[i] = dp_old[i] + dp_old[i-j^x]`. 这样刷新n遍dp数组,最终的答案是dp[n]. From cf4b39a98b700a5de502f237e93d547ffc0b0636 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 12:06:37 -0700 Subject: [PATCH 1997/2729] Rename Readmd.md to Readme.md --- .../{Readmd.md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/{Readmd.md => Readme.md} (100%) diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readme.md similarity index 100% rename from Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md rename to Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readme.md From 5579aa1f299bebbe1ef77c668c2c99dc92121f76 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 16:30:38 -0700 Subject: [PATCH 1998/2729] Create 2786.Visit-Array-Positions-to-Maximize-Score.cpp --- ...isit-Array-Positions-to-Maximize-Score.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/2786.Visit-Array-Positions-to-Maximize-Score.cpp diff --git a/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/2786.Visit-Array-Positions-to-Maximize-Score.cpp b/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/2786.Visit-Array-Positions-to-Maximize-Score.cpp new file mode 100644 index 000000000..4db44261b --- /dev/null +++ b/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/2786.Visit-Array-Positions-to-Maximize-Score.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { +public: + long long maxScore(vector& nums, int x) + { + int n = nums.size(); + + vector>dp(n, vector(2,LLONG_MIN/2)); + if (nums[0]%2==0) + dp[0][0] = nums[0]; + else + dp[0][1] = nums[0]; + + for (int i=1; i Date: Sat, 22 Jul 2023 16:31:14 -0700 Subject: [PATCH 1999/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c21b77544..7358ae7d3 100644 --- a/Readme.md +++ b/Readme.md @@ -733,7 +733,8 @@ [2036.Maximum-Alternating-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum) (M+) [2143.Choose-Numbers-From-Two-Arrays-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range) (H) [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) -[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) +[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) +[2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From 09e6ea116411fdfbdac3b66c908508061eec41e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 16:35:06 -0700 Subject: [PATCH 2000/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/Readme.md diff --git a/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/Readme.md b/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/Readme.md new file mode 100644 index 000000000..d4932100c --- /dev/null +++ b/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/Readme.md @@ -0,0 +1,9 @@ +### 2786.Visit-Array-Positions-to-Maximize-Score + +令dp[i][j]表示前i个元素里能够得到的最大值,并且最后一个元素的奇偶性是j。 + +当第i个元素不取时,dp[i][j] = dp[i-1][j] + +当第i个元素取时,查看它的奇偶性,dp[i][j]根据j的奇偶性与nums[i]奇偶性的差异,决定是否减去x的代价。 + +最终答案是dp[n-1][0]和dp[n-1][1]的较大值。 From 55fd53f8d53c1e223863e291528f71d4da9129a6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 29 Jul 2023 14:27:26 -0700 Subject: [PATCH 2001/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7358ae7d3..05f677478 100644 --- a/Readme.md +++ b/Readme.md @@ -959,7 +959,7 @@ [2156.Find-Substring-With-Given-Hash-Value](https://github.com/wisdompeak/LeetCode/tree/master/String/2156.Find-Substring-With-Given-Hash-Value) (M) [2168.Unique-Substrings-With-Equal-Digit-Frequency](https://github.com/wisdompeak/LeetCode/tree/master/String/2168.Unique-Substrings-With-Equal-Digit-Frequency) (M+) [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) -[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) +[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) From 37faf145eeb84615212123a9c49b3d59134c633f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 12:09:23 -0700 Subject: [PATCH 2002/2729] Create 2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp --- ...nimum-Time-to-Make-Array-Sum-At-Most-x.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp diff --git a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp new file mode 100644 index 000000000..da9c00f6f --- /dev/null +++ b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp @@ -0,0 +1,35 @@ +using PII = pair; +using LL = long long; +class Solution { + LL dp[1005][1005]; + LL presum[1005]; + int n; +public: + int minimumTime(vector& nums1, vector& nums2, int x) + { + n = nums1.size(); + + vectorarr; + for (int i=0; i=1) dp[i][j] = min(dp[i][j], dp[i-1][j-1] + presum[i-1]); + } + + for (int t=0; t<=n; t++) + if (dp[n][t]<=x) return t; + return -1; + } +}; From 017229032f0dac290119d605bef37544189185bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 14:58:10 -0700 Subject: [PATCH 2003/2729] Create Readme.md --- .../Readme.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md diff --git a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md new file mode 100644 index 000000000..5c208ee14 --- /dev/null +++ b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md @@ -0,0 +1,25 @@ +### 2809.Minimum-Time-to-Make-Array-Sum-At-Most-x + +首先我们要知道,我们不会给同一个位置的数字重复清零操作,因为后一次清零会完全浪费前一次清零。所以我们最多只会进行n次清零。 + +其次,这道题给人有一种错觉,使用清零次数与达成目标之间存在单调性的关系,即用的清零次数越多,就越容易实现sum<=x的目标。 + +我们先承认这种错觉。那么它会引导我们用二分搜值的思想,即给定清零次数T,我们是否能构造一种方案使得`sum<=x`呢? 我们想象一下,使用了T次清零之后,剩余的sum必然是这种形式 +``` +sum = {0 + nums2[a]*1 + nums2[b]*2 + ... + nums2[c] * (T-1)} + {nums1[x]+nums2[x]*T + nums1[y]+nums2[y]*T + .... nums1[z]+nums2[z]*T} +``` +也就是说,我们需要将元素分为两部分,前一部分是apply了清零操作,后一部分是没有apply清零操作。显然,对于前一部分,为了使得sum最小,我们会按照nums2的数值倒序排列。对于后一部分,对于顺序没有要求。 + +那么我们该如何将元素进行最优的分割呢?暴力尝试的话需要2^n。有更好的方法吗?其实这可以考虑成01背包问题,每个元素有“取”或者“不取”两种决策,求取T个元素时的最小代价。所以我们很容易定义dp[i][j]表示前i个元素里面清零j个元素的最小代价。当清零第i个元素时,说明我们在前i-1个元素依然用了j-1次清零,第j次清零使得nums[i]以0进入代价,同时也让之前的i-1个元素多了一轮“回血”,故增加的代价是nums2[1:i-1]。当不清零第i个元素时,说明第i个元素此时经历了j轮回血,故增加的代价是`nums1[i]+nums2[i]*j`。 + +综上我们可以计算出任意的dp[i][j]. 通过`dp[i][T]<=x`就可以判断能否通过T次清零实现目标。 + +但是注意,本题里的单调性是不成立的。例如 +``` +[9,10,10,5,2,4] +[2,4,0,3,3,4] +40 +``` +这组数据。不清零已经符合条件。清零1次,反而结果最小只能是42了。有可能确实没有单调性。 + +事实上,一次DP已经解决所有的问题。我们只需寻找最小的j,使得`dp[i][j]<=x`即是答案。 From b4ff44af3ec25fca25f00488617cddf9ccd7c4cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 14:58:24 -0700 Subject: [PATCH 2004/2729] Update Readme.md --- .../2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md index 5c208ee14..23dee54b5 100644 --- a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md +++ b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md @@ -6,7 +6,8 @@ 我们先承认这种错觉。那么它会引导我们用二分搜值的思想,即给定清零次数T,我们是否能构造一种方案使得`sum<=x`呢? 我们想象一下,使用了T次清零之后,剩余的sum必然是这种形式 ``` -sum = {0 + nums2[a]*1 + nums2[b]*2 + ... + nums2[c] * (T-1)} + {nums1[x]+nums2[x]*T + nums1[y]+nums2[y]*T + .... nums1[z]+nums2[z]*T} +sum = {0 + nums2[a]*1 + nums2[b]*2 + ... + nums2[c] * (T-1)} + + {nums1[x]+nums2[x]*T + nums1[y]+nums2[y]*T + .... nums1[z]+nums2[z]*T} ``` 也就是说,我们需要将元素分为两部分,前一部分是apply了清零操作,后一部分是没有apply清零操作。显然,对于前一部分,为了使得sum最小,我们会按照nums2的数值倒序排列。对于后一部分,对于顺序没有要求。 From 0c3a8626972157dd5f60ec68c03bc0f75024fe40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 15:00:39 -0700 Subject: [PATCH 2005/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 05f677478..ecfad06c0 100644 --- a/Readme.md +++ b/Readme.md @@ -780,7 +780,8 @@ [1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements) (M+) [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) -[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) +[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) +[2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From ff3811d35343381a03c8e088159eb000508db439 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 15:01:00 -0700 Subject: [PATCH 2006/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ecfad06c0..d019f67f8 100644 --- a/Readme.md +++ b/Readme.md @@ -780,7 +780,7 @@ [1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements) (M+) [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) -[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) +[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) [2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) From 384a7ea584e87545aa1c7ff26b0a2500e3370ecd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 15:13:47 -0700 Subject: [PATCH 2007/2729] Update Readme.md --- .../2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md index 23dee54b5..ca83884e3 100644 --- a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md +++ b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md @@ -11,7 +11,9 @@ sum = {0 + nums2[a]*1 + nums2[b]*2 + ... + nums2[c] * (T-1)} + ``` 也就是说,我们需要将元素分为两部分,前一部分是apply了清零操作,后一部分是没有apply清零操作。显然,对于前一部分,为了使得sum最小,我们会按照nums2的数值倒序排列。对于后一部分,对于顺序没有要求。 -那么我们该如何将元素进行最优的分割呢?暴力尝试的话需要2^n。有更好的方法吗?其实这可以考虑成01背包问题,每个元素有“取”或者“不取”两种决策,求取T个元素时的最小代价。所以我们很容易定义dp[i][j]表示前i个元素里面清零j个元素的最小代价。当清零第i个元素时,说明我们在前i-1个元素依然用了j-1次清零,第j次清零使得nums[i]以0进入代价,同时也让之前的i-1个元素多了一轮“回血”,故增加的代价是nums2[1:i-1]。当不清零第i个元素时,说明第i个元素此时经历了j轮回血,故增加的代价是`nums1[i]+nums2[i]*j`。 +那么我们该如何将元素进行最优的分割呢?暴力尝试的话需要2^n。有更好的方法吗?其实这可以考虑成01背包问题,我们将所有元素按照nums2升序排序:每个元素有“取”或者“不取”两种决策,求取T个元素时的最小代价。所以我们很容易定义dp[i][j]表示前i个元素里面清零j个元素的最小代价。 +1. 当清零第i个元素时,因为nums2值最大,第i个元素必然是最后一个被清零才合算。说明我们在前i-1个元素依然用了j-1次清零,第j次清零使得nums[i]以0进入代价,同时也让之前的i-1个元素多了一轮“回血”,故增加的代价是nums2[1:i-1]。 +2. 当不清零第i个元素时,说明第i个元素此时经历了j轮回血,故增加的代价是`nums1[i]+nums2[i]*j`。 综上我们可以计算出任意的dp[i][j]. 通过`dp[i][T]<=x`就可以判断能否通过T次清零实现目标。 From 970d0b3e56e0280e4cad9d1bd632def4ca15761a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 16:07:30 -0700 Subject: [PATCH 2008/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d019f67f8..547adee8a 100644 --- a/Readme.md +++ b/Readme.md @@ -702,6 +702,7 @@ [2484.Count-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences) (H-) [2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix) (H-) [2787.Ways-to-Express-an-Integer-as-Sum-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers) (M+) +[2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) @@ -781,7 +782,6 @@ [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) [2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) -[2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From 72238488b5872fb7bebb52baa7300261d0d787d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 16:09:12 -0700 Subject: [PATCH 2009/2729] Create 2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp --- ...m-Seconds-to-Equalize-a-Circular-Array.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp diff --git a/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp b/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp new file mode 100644 index 000000000..1b50322d7 --- /dev/null +++ b/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int minimumSeconds(vector& nums) + { + unordered_map>Map; + for (int i=0; i Date: Sat, 5 Aug 2023 18:36:19 -0700 Subject: [PATCH 2010/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 547adee8a..ac7b3560b 100644 --- a/Readme.md +++ b/Readme.md @@ -1415,6 +1415,7 @@ [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) +[2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) From f5d030ce675be958530c3f1eac20b7041d44d0da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 18:36:37 -0700 Subject: [PATCH 2011/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ac7b3560b..7a227e5d5 100644 --- a/Readme.md +++ b/Readme.md @@ -1415,7 +1415,7 @@ [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) -[2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) +[2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) From 535f52321f7c5b07473b49399e9f698208497001 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 18:40:59 -0700 Subject: [PATCH 2012/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/Readme.md diff --git a/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/Readme.md b/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/Readme.md new file mode 100644 index 000000000..26518789d --- /dev/null +++ b/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/Readme.md @@ -0,0 +1,5 @@ +### 2808.Minimum-Seconds-to-Equalize-a-Circular-Array + +我们想,最终所有的元素会变成谁呢?假如说最后都变成2,那么我们就需要考察原数组里非2的元素需要多少次传播被影响到。比如说,数组里非2元素的分布如下:`X X 2 X X X 2 X X`,很显然我们只要考察相邻两个2之间的最大跨度即可。如果跨度为d,说明相邻两个2中间的那个元素需要d/2次传播才能变成2. + +所以我们只需要记录数组里每种元素数值的index分布,得到该数值的最大跨度(注意首尾相接)。最终答案是取所有最大跨度里最小的那个。 From a9f29a8d3a748b206c4af864bb1b8e72491a1d57 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:23:06 -0700 Subject: [PATCH 2013/2729] Create 2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp --- ...ck-if-it-is-Possible-to-Split-Array_v2.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp diff --git a/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp b/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp new file mode 100644 index 000000000..a07c81f19 --- /dev/null +++ b/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool canSplitArray(vector& nums, int m) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1]+nums[i]; + + vector>dp(n+1, vector(n+1, 1)); + for (int len=3; len<=n; len++) + for (int i=1; i+len-1<=n; i++) + { + int j = i+len-1; + dp[i][j] = (dp[i][j-1]&&(presum[j-1]-presum[i-1]>=m)) || (dp[i+1][j]&&(presum[j]-presum[i]>=m)); + } + + return dp[1][n]; + } +}; From e1c3127dc821a8536c1670ff1cd44a45bddee035 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:24:28 -0700 Subject: [PATCH 2014/2729] Create 2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp --- .../2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp diff --git a/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp b/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp new file mode 100644 index 000000000..cb0db44b6 --- /dev/null +++ b/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool canSplitArray(vector& nums, int m) + { + if (nums.size()<=2) return true; + for (int i=1; i=m) return true; + return false; + } +}; From c2edc4ba70cd854d6e7061ce9a346b6d626fbee6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:24:55 -0700 Subject: [PATCH 2015/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7a227e5d5..ac303d9a8 100644 --- a/Readme.md +++ b/Readme.md @@ -1416,6 +1416,7 @@ [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) +[2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) From 8383730aa8b93f26590b6b42a61c8523f7d0fbb3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:30:00 -0700 Subject: [PATCH 2016/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Others/2811.Check-if-it-is-Possible-to-Split-Array/Readme.md diff --git a/Others/2811.Check-if-it-is-Possible-to-Split-Array/Readme.md b/Others/2811.Check-if-it-is-Possible-to-Split-Array/Readme.md new file mode 100644 index 000000000..592839086 --- /dev/null +++ b/Others/2811.Check-if-it-is-Possible-to-Split-Array/Readme.md @@ -0,0 +1,15 @@ +### 2811.Check-if-it-is-Possible-to-Split-Array + +#### 解法1 +本题的线性解法其实非常简单,只需要检查是否存在两个连续的元素之和大于等于m即可。 + +充分性:假设存在,那么我们在每一步切除的过程中保留上述两个元素,就能使操作不断进行下去。 + +必要性:假设不存在,那么无论用什么方法,当我们切到只剩三个元素的块时,根据题意一定无法继续切下去。 + +#### 解法2 +有动态规划的N^2解法。令dp[i][j]表示区间[i:j]是否可以根据规则切到最后。那么我们就有转移方程: +``` +dp[i][j] = (dp[i+1][j] && sum[i+1:j]>=m) || (dp[i][j-1] && sum[i:j-1]>=m) +``` +我们用二维循环,从小窗口的dp推导出大窗口的dp,最终返回dp[0][n-1]. From 06a9deea91cb3d951c59fcdf73aa9ee3edf59fe7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:38:36 -0700 Subject: [PATCH 2017/2729] Create 2812.Find-the-Safest-Path-in-a-Grid.cpp --- .../2812.Find-the-Safest-Path-in-a-Grid.cpp | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 BFS/2812.Find-the-Safest-Path-in-a-Grid/2812.Find-the-Safest-Path-in-a-Grid.cpp diff --git a/BFS/2812.Find-the-Safest-Path-in-a-Grid/2812.Find-the-Safest-Path-in-a-Grid.cpp b/BFS/2812.Find-the-Safest-Path-in-a-Grid/2812.Find-the-Safest-Path-in-a-Grid.cpp new file mode 100644 index 000000000..d1b8b8dc8 --- /dev/null +++ b/BFS/2812.Find-the-Safest-Path-in-a-Grid/2812.Find-the-Safest-Path-in-a-Grid.cpp @@ -0,0 +1,78 @@ +using PII = pair; +class Solution { +public: + vectordir = {{0,1},{0,-1},{1,0},{-1,0}}; + int maximumSafenessFactor(vector>& grid) + { + int n = grid.size(); + + queueq; + for (int i=0; i=n||j<0||j>=n) continue; + if (grid[i][j]!=0) continue; + grid[i][j] = grid[x][y]+1; + q.push({i,j}); + } + } + } + + int left = 0, right = n; + while (left < right) + { + int mid = right-(right-left)/2; + if (isOK(mid, grid)) + left = mid; + else + right = mid-1; + } + + return left; + } + + bool isOK(int d, vector>& grid) + { + int n = grid.size(); + vector>visited(n, vector(n, 0)); + + if (grid[0][0]<=d) return false; + + queueq; + q.push({0,0}); + visited[0][0] = 1; + + while (!q.empty()) + { + auto [x,y] = q.front(); + q.pop(); + for (int k=0; k<4; k++) + { + int i = x+dir[k].first; + int j = y+dir[k].second; + if (i<0||i>=n||j<0||j>=n) continue; + if (grid[i][j]<=d) continue; + if (visited[i][j]) continue; + + visited[i][j] = 1; + if (i==n-1 && j==n-1) return true; + q.push({i,j}); + } + } + + return false; + } +}; From a044d4c8987ee5fb4e540ba828d83e261c93ddc3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:44:27 -0700 Subject: [PATCH 2018/2729] Create Readme.md --- BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md diff --git a/BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md b/BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md new file mode 100644 index 000000000..e6a9d4540 --- /dev/null +++ b/BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md @@ -0,0 +1,5 @@ +### 2812.Find-the-Safest-Path-in-a-Grid + +我们预先处理grid,通过多源BFS,求出每个格子到离其最近的thief的距离grid[i][j]。为了便于处理grid里已经存在数值为1的格子,在这里我们填充grid[i][j]表示该点"离最近的thief的距离+1". + +然后我们二分搜值这个safety factor。假设是d,那么我们尝试寻找一条从左上到右下的通路,使得该路径不能包含有grid[i][j]<=d的格子,再走一次bfs即可判断。然后根据判断值,不断调整d的大小直至收敛。 From 4fbcba19f18e80d5a5e54802363f55a6be9827ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:46:07 -0700 Subject: [PATCH 2019/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ac303d9a8..99cd91787 100644 --- a/Readme.md +++ b/Readme.md @@ -556,6 +556,7 @@ [2258.Escape-the-Spreading-Fire](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2258.Escape-the-Spreading-Fire) (H+) [2290.Minimum-Obstacle-Removal-to-Reach-Corner](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner) (M+) [2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups) (H-) +[2812.Find-the-Safest-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2812.Find-the-Safest-Path-in-a-Grid) (M+) * ``Multi State`` [847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) [864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) From 26904ab1cbe764c8aa2c696fb6cc76a64e1f4738 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Aug 2023 00:14:34 -0700 Subject: [PATCH 2020/2729] Create 2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp --- ...mum-Elegance-of-a-K-Length-Subsequence.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp diff --git a/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp new file mode 100644 index 000000000..0d8204bd1 --- /dev/null +++ b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp @@ -0,0 +1,49 @@ +using LL = long long; +using PII = pair; +class Solution { +public: + long long findMaximumElegance(vector>& items, int k) + { + sort(items.rbegin(), items.rend()); + + unordered_map>Map; + LL sum = 0; + for (int i=0; i, greater<>>pq; + for (int i=0; i1) + { + sum -= val; + sum += items[i][0]; + t++; + Map[cate].pop_back(); + Map[items[i][1]].push_back(i); + ret = max(ret, sum + t*t); + break; + } + } + } + + return ret; + + } +}; From 655f83b423b162745d8b8eb84495372053d233c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Aug 2023 00:47:28 -0700 Subject: [PATCH 2021/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 99cd91787..802bd3c90 100644 --- a/Readme.md +++ b/Readme.md @@ -1249,6 +1249,7 @@ [2551.Put-Marbles-in-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2551.Put-Marbles-in-Bags) (M+) [2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) +[2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From 428d9f59dc4f1896acf8615e6d1a7bcf22e58849 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Aug 2023 01:13:04 -0700 Subject: [PATCH 2022/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/Readme.md diff --git a/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/Readme.md b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/Readme.md new file mode 100644 index 000000000..12052adb1 --- /dev/null +++ b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/Readme.md @@ -0,0 +1,13 @@ +### 2813.Maximum-Elegance-of-a-K-Length-Subsequence + +一个显然的想法是,能否遍历种类的数目:在固定种类数目的情况下,贪心地选择对应profit最高的k个item。但是即使说我们只考虑t个category,但是这样的t-distinct的category组合也非常多,我们无法穷举。 + +我们继续考虑。如果将所有元素按照profit降序排列,粗暴地取前k个元素,并记此时有t种不同的category,那么我们至少可以claim,当强制选择t个category时,此时的收益一定是最高的。因为我们选取的项目本身就是profit的top K. + +然后我们想,强制选择小于t个category的话,该如何规划呢?本题的突破口就在这里。我们知道,相比于上述`choose profit top K`的决策,其他任何决策都不会在`total_profit`更优;并且如果打算选择的category个数还更小的话,`distinct_categories^2`也不会占优势。故总的elegance肯定不及上面的方案。所以我们可以终止这个方向的探索。 + +然后我们想,强制选择多余t个category的话,该如何规划呢?既然top K个item已经包含了t个category,我们必然会贪心地按照profit的降序考察后续的项目,直至找到一个属于新种类的item,这样就有了t+1个category.注意,此时我们为了保持item总数为k,必然要吐出一个item:这个item必然是profit尽量小,同时它对应的category必须还存在其他的元素(否则将其吐出之后总的category数目就又不够t+1了)。所以我们的做法是将之前的top k item都放入一个小顶堆的PQ,需要弹出时查看当前profit最小的item是否是“单身”,如果是的话就忽略,如果否的话就可以将其“吐出”而将属于新category的item加入。这样我们就得到了t+1个category时的profit top k. + +依次类推,我们可以得到t+2个category时的profit top k,以及t+3个category时的profit top k等等。最终在所有category数目对应的最大elegance里挑选最大值。 + +但是注意,在贪心的过程中,如果我们无法找到一个可以吐出的item时,意味着我们无法构造“t+1个category时的profit top k”,因为这时已经发生了`t+1>k`。 From 088e0a634ff5abd72addcfeff1a42eb3ec1523f0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Aug 2023 02:18:43 -0700 Subject: [PATCH 2023/2729] Update 2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp --- ...mum-Elegance-of-a-K-Length-Subsequence.cpp | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp index 0d8204bd1..76d6f2be6 100644 --- a/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp +++ b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp @@ -1,49 +1,49 @@ using LL = long long; -using PII = pair; +using PII = pair; class Solution { public: long long findMaximumElegance(vector>& items, int k) { sort(items.rbegin(), items.rend()); - - unordered_map>Map; + LL sum = 0; + unordered_mapMap; for (int i=0; i, greater<>>pq; - for (int i=0; i1) - { - sum -= val; + + if (Map[cate] > 1) + { + sum -= profit; sum += items[i][0]; t++; - Map[cate].pop_back(); - Map[items[i][1]].push_back(i); - ret = max(ret, sum + t*t); - break; + Map[cate]--; + Map[items[i][1]]++; + + ret = max(ret, sum + t*t); + break; } - } + } } - + return ret; - } }; From 9e7a146a7b654735c555dc6eacbf271fb56e5d9c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Aug 2023 15:50:22 -0700 Subject: [PATCH 2024/2729] Update QuickPow.cpp --- Template/Math/QuickPow.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Template/Math/QuickPow.cpp b/Template/Math/QuickPow.cpp index e03f18f17..c95068c43 100644 --- a/Template/Math/QuickPow.cpp +++ b/Template/Math/QuickPow.cpp @@ -1,5 +1,14 @@ class Solution { +long long M = 1e9+7; public: + long long quickMul(long long x, long long N) { + if (N == 0) { + return 1; + } + LL y = quickMul(x, N / 2) % M; + return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); + } + double quickMul(double x, long long N) { if (N == 0) { return 1.0; From ff0a9028bb1b986b3d98d10afb58769a3ec0611c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Aug 2023 19:43:22 -0700 Subject: [PATCH 2025/2729] Create 2818.Apply-Operations-to-Maximize-Score.cpp --- ...818.Apply-Operations-to-Maximize-Score.cpp | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Others/2818.Apply-Operations-to-Maximize-Score/2818.Apply-Operations-to-Maximize-Score.cpp diff --git a/Others/2818.Apply-Operations-to-Maximize-Score/2818.Apply-Operations-to-Maximize-Score.cpp b/Others/2818.Apply-Operations-to-Maximize-Score/2818.Apply-Operations-to-Maximize-Score.cpp new file mode 100644 index 000000000..9ce734fb6 --- /dev/null +++ b/Others/2818.Apply-Operations-to-Maximize-Score/2818.Apply-Operations-to-Maximize-Score.cpp @@ -0,0 +1,90 @@ +using LL = long long; +LL M = 1e9+7; +using PII=pair; +class Solution { +public: + LL quickMul(LL x, LL N) { + if (N == 0) { + return 1; + } + LL y = quickMul(x, N / 2) % M; + return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); + } + + vectorEratosthenes(int n) + { + vectorq(n+1,0); + for (int i=2; i<=n; i++) + { + if (q[i]>=1) continue; + q[i] = 1; + int j=i*2; + while (j<=n) + { + q[j]+=1; + j+=i; + } + } + return q; + } + + int maximumScore(vector& nums, int k) + { + LL n = nums.size(); + int MAX = *max_element(nums.begin(), nums.end()); + vectors = Eratosthenes(MAX); + + vectorscores(n); + for (int i=0; iprevLarger(n, -1); + stackStack; + for (int i=0; inextLarger(n, n); + while (!Stack.empty()) Stack.pop(); + for (int i=n-1; i>=0; i--) + { + while (!Stack.empty() && scores[Stack.top()] <= scores[i]) + Stack.pop(); + if (!Stack.empty()) + nextLarger[i] = Stack.top(); + Stack.push(i); + } + + vector temp(n); + for (int i=0; i= t) + { + ret = ret * quickMul(num, t) % M; + k -= t; + } + else + { + ret = ret * quickMul(num, k) % M; + k = 0; + } + if (k==0) break; + } + + return ret; + } +}; From cb788e3896b5eb47e71dd9273900ff23f75e7c02 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Aug 2023 19:43:51 -0700 Subject: [PATCH 2026/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 802bd3c90..ea759800f 100644 --- a/Readme.md +++ b/Readme.md @@ -1439,7 +1439,8 @@ [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) [2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) -[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) +[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) +[2818.Apply-Operations-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2818.Apply-Operations-to-Maximize-Score) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 7646faa3a311fac026838be695032c97e8980a73 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Aug 2023 23:22:35 -0700 Subject: [PATCH 2027/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ea759800f..993ed28ba 100644 --- a/Readme.md +++ b/Readme.md @@ -1439,7 +1439,7 @@ [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) [2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) -[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) +[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) [2818.Apply-Operations-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2818.Apply-Operations-to-Maximize-Score) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) From 329aff6b1a1044bc387bc051499048020041f1fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Aug 2023 23:56:33 -0700 Subject: [PATCH 2028/2729] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Others/2818.Apply-Operations-to-Maximize-Score/Readme.md diff --git a/Others/2818.Apply-Operations-to-Maximize-Score/Readme.md b/Others/2818.Apply-Operations-to-Maximize-Score/Readme.md new file mode 100644 index 000000000..e7274f5dd --- /dev/null +++ b/Others/2818.Apply-Operations-to-Maximize-Score/Readme.md @@ -0,0 +1,17 @@ +### 2818.Apply-Operations-to-Maximize-Score + +这道题是很多套路和知识点的大杂烩。 + +首先,根据题意,我们要在n^2个区间里挑选k个区间。这n^2个区间里,有的x可以很大,有的x会很小。我们不会去遍历所有这n^2个区间、再根据他们的x排序。相比之下,x的取值范围只有n种(即nums里的n个元素),通过遍历x来枚举区间的效率更高。 + +显然,我们必然会贪心地使用“x最大”的那些区间,我们将nums数组里最大元素记做nums[i]。那么有多少区间的`highest prime score`是nums[i]呢?假设每个元素的`prime score`我们都已经提前计算好了,记做scores[i],那么我们寻找i左边第一个大于等于scores[i]的位置left,以及右边第一个大于scores[i]的位置right,那么符合条件的区间的左边界就可以在(left,i)之间任意选取,右边界就可以在(i,right)之间任意选取,任意配对之后总共的区间个数就是`(i-left)*(right-i)`. 也就是说,在最终选取的k个区间里,我们优先选取这`(i-left)*(right-i)`个区间,因为每次都可以让结果乘以nums[i](全局最大的x)。 + +以此类推,我们再贪心地使用“x第二大”的那些区间,记做nums[j]。同理计算出有多少个区间满足scores[j]是最大元素。当k还没选够时,我们就会优先使用这些区间。 + +再找nums第三大元素、第四大元素... 直至把k个区间都用完。 + +以上就是本题的大致思路。其中还有不少小问题。比如 + +1. 怎么预处理得到scores数组?可以用埃氏筛的思路,在根据某个质因数向上筛除合数时,可以顺便给该合数增1,就可以记录下每个数的distinct质因数的个数了。 +2. 如何求`previous larger or equal number`和`next larger number`,这是单调栈的经典应用了。 +3. 假设某个数x对应的区间有P个,那么我们就要`ret *= x^P`,其中P可能很大,所以需要调用快速幂的libary。 From f30176ee0f663c142ede0efb3edd7732ba52653c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 14:13:02 -0700 Subject: [PATCH 2029/2729] Create 2827.Number-of-Beautiful-Integers-in-the-Range.cpp --- ...ber-of-Beautiful-Integers-in-the-Range.cpp | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp diff --git a/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp new file mode 100644 index 000000000..6aea5ebb1 --- /dev/null +++ b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp @@ -0,0 +1,71 @@ +using LL = long long; +class Solution { + int k; +public: + int numberOfBeautifulIntegers(int low, int high, int k) + { + this->k = k; + return helper(high, k) - helper(low-1, k); + } + + int helper(LL num, int k) + { + string Num = to_string(num); + int n = Num.size(); + + int memo[11][2][22][22]; + memset(memo, -1, sizeof(memo)); + + int ret = 0; + for (int len=2; len Date: Sat, 19 Aug 2023 14:41:48 -0700 Subject: [PATCH 2030/2729] Create Readme.md --- .../Readme.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/Readme.md diff --git a/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/Readme.md b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/Readme.md new file mode 100644 index 000000000..20ea0f37c --- /dev/null +++ b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/Readme.md @@ -0,0 +1,31 @@ +### 2827.Number-of-Beautiful-Integers-in-the-Range + +常规的数位计算的套路。开局就是`return helper(large) - helper(low-1)`,其中helper表示符合条件、且小于等于larger的数字的个数。 + +在实现helper时,我们用DFS的思想来逐个填充每个位置上的数字。在填充的过程中我们要监控两个量。第一个是奇数数位与偶数数位的个数之差,我们期望在填充完毕之后是0. 第二个是当前构造的数字对于k的模,我们期望在填充完毕之后也是0. + +我们令`dfs(len, isSame, diff, r)`,表示还有len个数字需要填充(或者说当前需要填充倒数第len个位置),isSame表示之前已填充的数字是否与原数num的前缀贴合,diff表示当前奇数数位与偶数数位的个数之差,r表示已经构造的数字对于k的模。 + +我们考虑当前数字d的填充时,需要分两大类: + +1. isSame是false,那么说明当前d可以从0填到9都没有任何顾虑(不会超过原数),故 +```cpp +for (int d = 0; d <= 9; d++) + ret += dfs(len-1, false, diff+((d%2==0)*2-1), (r*10+d)%k); +``` + +2. isSame是true,那么说明当前d可以从0填到`D = num[n-len]-1`都没有任何顾虑(不会超过原数),即 +```cpp +int D = num[n-len]; +for (int d = 0; d < D; d++) + ret += dfs(len-1, false, diff+((d%2==0)*2-1), (r*10+d)%k); +``` +但是d最大只能取到D,并且在下一个回合的过程中仍将标记`isSame=true`,即 +```cpp +int D = num[n-len]; +ret += dfs(len-1, true, diff+((D%2==0)*2-1), (r*10+D)%k); +``` + +最终边界条件是当len==0时,只有当`diff==0 && r==0`的时候才会返回`1`(因为此时已经将一个具体的数构造出来了),其余的时候我们构造出的是一个不符合条件的数,返回`0`. + +最后我们加上记忆化。我们看到有四个参量`len,isSame,diff,r`,所以就定义memo[11][2][22][22]来存储各个dfs的结果,来避免重复的搜索。 From 452435af08d62fab48419da3b8a37fb2db056d7c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 15:37:47 -0700 Subject: [PATCH 2031/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 993ed28ba..3aa5e7c20 100644 --- a/Readme.md +++ b/Readme.md @@ -1064,7 +1064,8 @@ [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) -[2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) +[2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) +[2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 30ec811d68e7bb56e2c2462a6a04d8951d7300b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 16:31:58 -0700 Subject: [PATCH 2032/2729] Update 2827.Number-of-Beautiful-Integers-in-the-Range.cpp --- ...ber-of-Beautiful-Integers-in-the-Range.cpp | 65 +++++++++---------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp index 6aea5ebb1..600bad9cc 100644 --- a/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp +++ b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp @@ -1,71 +1,70 @@ using LL = long long; -class Solution { +class Solution { int k; public: int numberOfBeautifulIntegers(int low, int high, int k) - { + { this->k = k; return helper(high, k) - helper(low-1, k); } - + int helper(LL num, int k) - { + { + int memo[11][2][22][22]; + memset(memo, -1, sizeof(memo)); + string Num = to_string(num); int n = Num.size(); - int memo[11][2][22][22]; - memset(memo, -1, sizeof(memo)); - int ret = 0; - for (int len=2; len Date: Sat, 19 Aug 2023 16:45:27 -0700 Subject: [PATCH 2033/2729] Create 2826.Sorting-Three-Groups.cpp --- .../2826.Sorting-Three-Groups.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Dynamic_Programming/2826.Sorting-Three-Groups/2826.Sorting-Three-Groups.cpp diff --git a/Dynamic_Programming/2826.Sorting-Three-Groups/2826.Sorting-Three-Groups.cpp b/Dynamic_Programming/2826.Sorting-Three-Groups/2826.Sorting-Three-Groups.cpp new file mode 100644 index 000000000..f3220d39a --- /dev/null +++ b/Dynamic_Programming/2826.Sorting-Three-Groups/2826.Sorting-Three-Groups.cpp @@ -0,0 +1,18 @@ +class Solution { + int dp[105][4]; +public: + int minimumOperations(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + for (int i=1; i<=n; i++) + { + dp[i][1] = dp[i-1][1] + (nums[i]!=1); + dp[i][2] = min(dp[i-1][1], dp[i-1][2]) + (nums[i]!=2); + dp[i][3] = min(min(dp[i-1][1], dp[i-1][2]), dp[i-1][3]) + (nums[i]!=3); + } + + return min(min(dp[n][1], dp[n][2]), dp[n][3]); + + } +}; From 9747461c6bf767be256d3ed81d93d76414badc8f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 16:48:15 -0700 Subject: [PATCH 2034/2729] Create Readme.md --- Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md diff --git a/Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md b/Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md new file mode 100644 index 000000000..f2d07f8f1 --- /dev/null +++ b/Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md @@ -0,0 +1,9 @@ +### 2826.Sorting-Three-Groups + +令dp[i][j]表示截止到第i个元素为止构成j个group的最小代价,其中j=1,2,3. 显然有 +``` +dp[i][1] = dp[i-1][1] + (nums[i]!=1); +dp[i][2] = min(dp[i-1][1], dp[i-1][2]) + (nums[i]!=2); +dp[i][3] = min(min(dp[i-1][1], dp[i-1][2]), dp[i-1][3]) + (nums[i]!=3); +``` +最终返回dp[n][1],dp[n][2],dp[n][3]中的最小值。 From f758ff134707b98dd07ade1457df440add629270 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 16:48:43 -0700 Subject: [PATCH 2035/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3aa5e7c20..424196f22 100644 --- a/Readme.md +++ b/Readme.md @@ -704,6 +704,7 @@ [2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix) (H-) [2787.Ways-to-Express-an-Integer-as-Sum-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers) (M+) [2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) +[2826.Sorting-Three-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2826.Sorting-Three-Groups) (M) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From a14dee16123378a227e9e0c0b0ff0da71b69895d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 17:28:09 -0700 Subject: [PATCH 2036/2729] Create 2801.Count-Stepping-Numbers-in-Range.cpp --- .../2801.Count-Stepping-Numbers-in-Range.cpp | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Recursion/2801.Count-Stepping-Numbers-in-Range/2801.Count-Stepping-Numbers-in-Range.cpp diff --git a/Recursion/2801.Count-Stepping-Numbers-in-Range/2801.Count-Stepping-Numbers-in-Range.cpp b/Recursion/2801.Count-Stepping-Numbers-in-Range/2801.Count-Stepping-Numbers-in-Range.cpp new file mode 100644 index 000000000..1aa77f62c --- /dev/null +++ b/Recursion/2801.Count-Stepping-Numbers-in-Range/2801.Count-Stepping-Numbers-in-Range.cpp @@ -0,0 +1,78 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int countSteppingNumbers(string low, string high) + { + LL ret = helper(high) - helper(low); + ret = (ret + M) % M; + ret = (ret + check(low) + M) % M; + + return ret; + } + + bool check(string s) + { + for (int i=1; i= 0) + ret = (ret + dfs(len-1, prev-1, false, num, memo)) % M; + } + else + { + int D = num[n-len] - '0'; + if (prev+1 < D) + ret += dfs(len-1, prev+1, false, num, memo); + else if (prev+1 == D) + ret += dfs(len-1, prev+1, true, num, memo); + ret %= M; + + if (prev-1 >= 0 && prev-1 < D) + ret += dfs(len-1, prev-1, false, num, memo); + else if (prev-1 >= 0 && prev-1 == D) + ret += dfs(len-1, prev-1, true, num, memo); + ret %= M; + } + + memo[len][prev][isSame] = ret; + return ret; + } +}; From 026fcb7418cca2a1bc1d1da02c03f63a1920efc3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 17:39:32 -0700 Subject: [PATCH 2037/2729] Create Readme.md --- .../2801.Count-Stepping-Numbers-in-Range/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md diff --git a/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md b/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md new file mode 100644 index 000000000..8ec1a5aa2 --- /dev/null +++ b/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md @@ -0,0 +1,13 @@ +### 2801.Count-Stepping-Numbers-in-Range + +首先依据套路转化为前缀之差的形式:`return helper(high) - helper(low) + check(low)`. 其中helper(num)表示求[1,num]区间内符合要求的数的个数。 + +我们用dfs的方法来这个填充每一位。设计`dfs(len, prev, isSame)`,其中len表示还有多少位需要填充,prev表示上一位填充的数字是什么,isSame表示之前填充的所有数字是否与num的前缀贴合。 + +1. 如果isSame==false,那么只要`prev+1<=9`,那么就可以在当前位填充prev+1;只要`prev-1>=0`,那么就可以在当前位填充prev-1. 递归函数里的isSame都是false。 + +2. 如果isSame==true,令当前位置上num的数字是D,那么只要`prev+1=0 && prev-1 Date: Sat, 19 Aug 2023 17:40:23 -0700 Subject: [PATCH 2038/2729] Update Readme.md --- Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md b/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md index 8ec1a5aa2..ce7f3d2d0 100644 --- a/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md +++ b/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md @@ -2,7 +2,7 @@ 首先依据套路转化为前缀之差的形式:`return helper(high) - helper(low) + check(low)`. 其中helper(num)表示求[1,num]区间内符合要求的数的个数。 -我们用dfs的方法来这个填充每一位。设计`dfs(len, prev, isSame)`,其中len表示还有多少位需要填充,prev表示上一位填充的数字是什么,isSame表示之前填充的所有数字是否与num的前缀贴合。 +我们用dfs的方法来这个填充每一位。设计`dfs(len, prev, isSame)`表示在当前“状态”最终会有多少个合法的数字,其中len表示还有多少位需要填充,prev表示上一位填充的数字是什么,isSame表示之前填充的所有数字是否与num的前缀贴合。 1. 如果isSame==false,那么只要`prev+1<=9`,那么就可以在当前位填充prev+1;只要`prev-1>=0`,那么就可以在当前位填充prev-1. 递归函数里的isSame都是false。 From 78685ce95456309d829dede9f9152df1c3e788aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 17:41:01 -0700 Subject: [PATCH 2039/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 424196f22..03269f089 100644 --- a/Readme.md +++ b/Readme.md @@ -1066,6 +1066,7 @@ 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) +[2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) From baeca42e78901c8763aa8a7060f33285fbeb1c52 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:13:37 -0700 Subject: [PATCH 2040/2729] Update Readme.md --- Readme.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Readme.md b/Readme.md index 03269f089..360507bfa 100644 --- a/Readme.md +++ b/Readme.md @@ -736,7 +736,7 @@ [2036.Maximum-Alternating-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum) (M+) [2143.Choose-Numbers-From-Two-Arrays-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range) (H) [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) -[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) +[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) [2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) @@ -756,7 +756,11 @@ [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) [2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) [2464.Minimum-Subarrays-in-a-Valid-Split](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split) (M) -[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) +[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) + * `Interval` + [1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) + [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) + [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) @@ -1342,9 +1346,6 @@ [1272.Remove-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1272.Remove-Interval) (M+) [1288.Remove-Covered-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1288.Remove-Covered-Intervals) (M+) [1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden) (M+) -[1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) -[1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) -[2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) From b872638ee573a3da3ea276f3f8ffc5cc9cbcc443 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:15:59 -0700 Subject: [PATCH 2041/2729] Create 2830.Maximize-the-Profit-as-the-Salesman.cpp --- ...30.Maximize-the-Profit-as-the-Salesman.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/2830.Maximize-the-Profit-as-the-Salesman.cpp diff --git a/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/2830.Maximize-the-Profit-as-the-Salesman.cpp b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/2830.Maximize-the-Profit-as-the-Salesman.cpp new file mode 100644 index 000000000..54286a5f4 --- /dev/null +++ b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/2830.Maximize-the-Profit-as-the-Salesman.cpp @@ -0,0 +1,21 @@ +class Solution { + int dp[100005]; +public: + int maximizeTheProfit(int n, vector>& offers) + { + + unordered_map>>Map; + for (auto& offer:offers) + Map[offer[1]+1].push_back({offer[0]+1, offer[2]}); + + for (int i=1; i<=n; i++) + { + dp[i] = dp[i-1]; + for (auto& [start, val]: Map[i]) + dp[i] = max(dp[i], dp[start-1] + val); + } + + return dp[n]; + + } +}; From af0feca8c0d9e8dfa7f2caa5cd7489004fe4149a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:16:47 -0700 Subject: [PATCH 2042/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 360507bfa..c99941d62 100644 --- a/Readme.md +++ b/Readme.md @@ -761,6 +761,7 @@ [1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) + [2830.Maximize-the-Profit-as-the-Salesman](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman) (M) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) From 062bc7abfefed56b1c48bb7510d8ca6a25c26d45 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:31:03 -0700 Subject: [PATCH 2043/2729] Create Readmd.md --- .../2830.Maximize-the-Profit-as-the-Salesman/Readmd.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md diff --git a/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md new file mode 100644 index 000000000..8718d73d7 --- /dev/null +++ b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md @@ -0,0 +1,7 @@ +### 2830.Maximize-the-Profit-as-the-Salesman + +此题和`2008.Maximum-Earnings-From-Taxi`几乎一样。考虑到`the number of houses`只有1e5级别,最简单的方法就是令dp[i]前i个房子所能得到的最大收益。 + +我们遍历以i结尾的offer,如果该offer的跨度是从[j,i],价值是v,那么我们就有一种转移的方法`dp[i]=dp[j-1]+val`. 除此之外,如果不考虑任何offer,则有`dp[i]=dp[i-1]`. 我们从中选一个最优解作为dp[i]即可。 + +如果本题里houses的数目是1e9级别,我们就需要进行离散化的处理,将所有offer的右边界组成数组T,排序后进行遍历。对于跨度是[t1,t2]的offer,我们需要用二分法在T中找到最后一个小于等于t1的下标,再进行dp的转移。 From e6853c0f3cc34baf25fbe4752b1bcc4a0e22a9fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:31:19 -0700 Subject: [PATCH 2044/2729] Rename Readmd.md to Readme.md --- .../{Readmd.md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/{Readmd.md => Readme.md} (100%) diff --git a/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readme.md similarity index 100% rename from Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md rename to Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readme.md From 944ae080d8bf1af685da11a244f9b60e8be78c9c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 20 Aug 2023 00:01:41 -0700 Subject: [PATCH 2045/2729] Create 2831.Find-the-Longest-Equal-Subarray.cpp --- .../2831.Find-the-Longest-Equal-Subarray.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Two_Pointers/2831.Find-the-Longest-Equal-Subarray/2831.Find-the-Longest-Equal-Subarray.cpp diff --git a/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/2831.Find-the-Longest-Equal-Subarray.cpp b/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/2831.Find-the-Longest-Equal-Subarray.cpp new file mode 100644 index 000000000..7e5e84327 --- /dev/null +++ b/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/2831.Find-the-Longest-Equal-Subarray.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int longestEqualSubarray(vector& nums, int k) + { + unordered_map>Map; + for (int i=0; i Date: Sun, 20 Aug 2023 00:02:11 -0700 Subject: [PATCH 2046/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c99941d62..07c3b8f4f 100644 --- a/Readme.md +++ b/Readme.md @@ -52,6 +52,7 @@ [2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2564.Substring-XOR-Queries) (H-) [2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) +[2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From af6eff796190346ad34b8f366c08559ab72ac4c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 20 Aug 2023 00:21:11 -0700 Subject: [PATCH 2047/2729] Create Readme.md --- .../2831.Find-the-Longest-Equal-Subarray/Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Two_Pointers/2831.Find-the-Longest-Equal-Subarray/Readme.md diff --git a/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/Readme.md b/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/Readme.md new file mode 100644 index 000000000..cafc2de5d --- /dev/null +++ b/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/Readme.md @@ -0,0 +1,12 @@ +### 2831.Find-the-Longest-Equal-Subarray + +我们遍历数组,收集每种不同元素出现的位置。 + +假设对于元素A,它出现的所有的index都放入pos数组里。那么对于以pos[i]为左边界的subarray,我们向右寻找一个最远的pos[j],使得两个位置之间的“非A元素”的数量恰好小于等于k,那么就意味着这个区间可以通过有限的删除操作变成equal A的subarray。数学表达式为: +```cpp +if (pos[j]-pos[i]+1 - (j-i+1) <= k) + ret = max(ret, j-i+1) +``` +显然,随着i的移动,j必然也是单向移动的。所以在pos数组上的快慢指针的移动,可以找出所有符合要求的区间,找到其中A元素最多的一段。 + +同理,处理其他的元素对应的pos数组,返回全局最大的解。 From d7b02bcd3f55186d7a870549f4518919fa37d7e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 12:23:00 -0700 Subject: [PATCH 2048/2729] Create 2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp --- ...ns-to-Form-Subsequence-With-Target-Sum.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp new file mode 100644 index 000000000..675357e8a --- /dev/null +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + int minOperations(vector& nums, int target) + { + vectorcount(32,0); + + for (auto x: nums) + { + int i = 0; + while (x>0) + { + i++; + x/=2; + } + count[i-1] += 1; + } + + vectort; + for (int i=0; i<31; i++) + { + if ((target>>i)&1) + t.push_back(i); + } + + int ret = 0; + + for (int i: t) + { + int j = 0; + while (j < i) + { + count[j+1] += count[j] / 2; + count[j] %= 2; + j++; + } + if (j == i && count[j] > 0) + { + count[j] -= 1; + continue; + } + + while (j<31 && count[j] == 0) + j++; + if (j==31) return -1; + + count[j] -= 1; + for (int t=j-1; t>=i; t--) + count[t]+=1; + ret += j-i; + count[i] -= 1; + } + + return ret; + } +}; From e2bf72374619513706ef4e6842419ad58bbbf452 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:02:20 -0700 Subject: [PATCH 2049/2729] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md new file mode 100644 index 000000000..232b4b803 --- /dev/null +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md @@ -0,0 +1,19 @@ +### 2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum + +显然我们会将nums里的元素做二进制分解,每个二进制位上会有若干个1,我们将其记录在count数组里。count[i]表示第i个bit位上我们有多少个1. + +同理,我们会将target做二进制分解,每个bit位上的1表示我们需要从count里得到的“支持”。比如说,如果target上的每个需要1的二进制位i上,count[i]都大于零的话,那么意味着nums已经可以拼凑出target了。 + +我们从低到高逐个考虑target所需要的二进制位. 假设我们需要第i个bit位上的1,那么我们该如何考察count能否支持呢? + +1. 首先我们考虑比i低的二进制位上,count是否能够通过现有的低位上的“1”的sum来实现第i位上的1. 我们可以将所有低位的1都加起来,通过逐次进位的形式,看看能否传播到第i位。比如说count[0]=5,i=2, 那么我们可以对count做如下变化 +``` +step 1: count[0]=1, count[1]=2 +step 2: count[0]=1, count[1]=0, count[2]=1 +``` + +基本思想就是:能进位则进位。最终每个count[]上不是0就是1. 上面的例子里,count[0]=5 确实可以给target的第i位提供1的支持。 + +2. 其次,如果以上方法不能实现,那么就意味着我们需要将高位上的1进行“拆解”以满足第i位上的1。显然,我们会贪心地在count里找到最接近i且count>0的位置j,将其拆解j-i次,就可以将第j位上的1传播到j-1,j-2,...i各个位上。这样我们就满足了taget在第i位上的需求。 + +通过以上方法,就是实现本题的最优方案。 From 3a27fc7019b4b68c1f0e779a8bf356029a9867fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:02:40 -0700 Subject: [PATCH 2050/2729] Update 2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp --- ...35.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp index 675357e8a..a4a1d8316 100644 --- a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp @@ -47,7 +47,6 @@ class Solution { for (int t=j-1; t>=i; t--) count[t]+=1; ret += j-i; - count[i] -= 1; } return ret; From ebcfbf68011d646774d51a79f304bf839228cf97 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:11:06 -0700 Subject: [PATCH 2051/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 07c3b8f4f..81588d954 100644 --- a/Readme.md +++ b/Readme.md @@ -1259,6 +1259,7 @@ [2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) +[2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From d706f2bcc2b2e3d03603f63589255c489cab538f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:38:06 -0700 Subject: [PATCH 2052/2729] Update 2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp --- ...ns-to-Form-Subsequence-With-Target-Sum.cpp | 35 +++++++++---------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp index a4a1d8316..524315fb7 100644 --- a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp @@ -2,53 +2,50 @@ class Solution { public: int minOperations(vector& nums, int target) { - vectorcount(32,0); - - for (auto x: nums) + vectorcount(31, 0); + for (int x: nums) { int i = 0; while (x>0) - { - i++; + { x/=2; + i++; } count[i-1] += 1; } - + vectort; for (int i=0; i<31; i++) { if ((target>>i)&1) t.push_back(i); } - + int ret = 0; - for (int i: t) { int j = 0; - while (j < i) + while (j 0) + if (j==i && count[i]>0) { - count[j] -= 1; + count[i] -= 1; continue; - } - - while (j<31 && count[j] == 0) + } + + while (j<31 && count[j]==0) j++; if (j==31) return -1; - count[j] -= 1; - for (int t=j-1; t>=i; t--) - count[t]+=1; + for (int k=j-1; k>=i; k--) + count[k]+=1; ret += j-i; } - - return ret; + + return ret; } }; From 01751efa843673eafe30803e8fe2903c6b71c82b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:39:08 -0700 Subject: [PATCH 2053/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md index 232b4b803..d2f2b9364 100644 --- a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md @@ -6,7 +6,7 @@ 我们从低到高逐个考虑target所需要的二进制位. 假设我们需要第i个bit位上的1,那么我们该如何考察count能否支持呢? -1. 首先我们考虑比i低的二进制位上,count是否能够通过现有的低位上的“1”的sum来实现第i位上的1. 我们可以将所有低位的1都加起来,通过逐次进位的形式,看看能否传播到第i位。比如说count[0]=5,i=2, 那么我们可以对count做如下变化 +1. 首先我们考虑比i低的二进制位上,count是否能够通过现有的低位上的“1”的sum来实现第i位上的1(注意,因为nums里每个元素只有一个bit 1,所以低位上1的sum必然对应着nums里某些元素的sum). 我们可以将所有低位的1都加起来,通过逐次进位的形式,看看能否传播到第i位。比如说count[0]=5,i=2, 那么我们可以对count做如下变化 ``` step 1: count[0]=1, count[1]=2 step 2: count[0]=1, count[1]=0, count[2]=1 From 7da44421eb7f4424932b87d0924cbc3e8a1628c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 21:19:45 -0700 Subject: [PATCH 2054/2729] Create 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp --- ...lue-of-Function-in-a-Ball-Passing-Game.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp new file mode 100644 index 000000000..5fc76d000 --- /dev/null +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp @@ -0,0 +1,55 @@ +using LL = long long; +class Solution { + int pos[100005][35]; + LL dp[100005][35]; +public: + long long getMaxFunctionValue(vector& receiver, long long k) + { + int n = receiver.size(); + int M = 0; + LL K = k; + while (K>0) + { + M++; + K/=2; + } + + for (int i=0; ibits; + for (int i=0; i>i)&1) + bits.push_back(i); + } + + LL ret = 0; + for (int i=0; i Date: Sun, 27 Aug 2023 21:21:45 -0700 Subject: [PATCH 2055/2729] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index 81588d954..ae5e8853d 100644 --- a/Readme.md +++ b/Readme.md @@ -93,9 +93,9 @@ [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) -* ``Binary Processing`` -[1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) -[1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) +* ``Binary Lifting`` +[1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) +[2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) @@ -1125,6 +1125,7 @@ [1680.Concatenation-of-Consecutive-Binary-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Math/1680.Concatenation-of-Consecutive-Binary-Numbers) (M) [1739.Building-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/Math/1739.Building-Boxes) (H-) [1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Math/1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation) (H) +[1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) [1969.Minimum-Non-Zero-Product-of-the-Array-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/1969.Minimum-Non-Zero-Product-of-the-Array-Elements) (M+) [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) From f3d38bbe9e40ceb0ab9780a4cb0dec938eae578e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 28 Aug 2023 01:01:22 -0700 Subject: [PATCH 2056/2729] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md new file mode 100644 index 000000000..5b835e9a7 --- /dev/null +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md @@ -0,0 +1,17 @@ +### 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game + +如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?我们取一段序列prev[i],i,recevier[i]进行观察。这三个位置在跳转顺序上是从前往后连续的。 + +假设想求以节点i为结尾的、长度为k的序列的最大值,那么我们必然想知道以节点prev[i]为结尾的、长度为k-1的序列的最大值,这样在其基础上加上i就是期望的value. 可见,对于任何一个节点,我们不仅要考虑它为k-size序列终点时的最大value,也要考虑它作为k-1 size序列终点的最大value,以此类推。这样就有转移方程`dp[i][d] = max{dp[prev[i]] + i}`,其中dp[i][d]表示以i为结尾的、长度为d的序列的value最大值,其中`d=1,2,...,k`。 + +但在此题中,d的范围是`1e10`,这样的二维数组无法存下。此时有一个技巧叫做binary lifting,第二个维度只需要存储对数个信息。 + +具体地,我们令dp[i][j]表示从i开始走2^j步所能得到的最大value。同时辅助pos[i][j]表示从i开始走2^j步所到达的位置。我们用二分来进行状态转移,即找到中点2^(j-1)步后的位置pos[i][j-1],然后从这里再走2^(j-1)步,故转移方程就有 +```cpp +pos[i][j] = pos[pos[i][j-1]][j-1]; +dp[i][j] = dp[i][j-1] + dp[pos[i][j-1]][j-1]; +``` + +因为我们最多走1e10步,相当于2^34,状态变量里的第二个维度最多34. 我们将j从1到34从小到大进行遍历,根据上面的式子即可顺利填充所有的dp[i][j]和pos[i][j]. + +最终我们需要考察所有的位置i,看它走k步所能得到的最大value,然后全局取最大值。注意,如果k不是2的次幂的话,我们就没有现成的dp[i][j]作为答案。但是没关系,我们将k进行二进制分解为`2^j0+2^j1+2^j2+...`后,相当于从i开始先走2^j0步,再走2^j1步,再走2^j2步... 于是我们只需要依次找到这些中继点i,i1,i2,...,将每一段跨度的value累加起来即可,即`sum[i] = dp[i][j0] + dp[i1][j1] + dp[i2][j2] + ... `. 其中`i1=pos[i][j1]`,其他的跳转点以此类推。 From c9c054bcde75d5ed5f488eb0001b368f0716bdba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 10:59:24 -0700 Subject: [PATCH 2057/2729] Create 2845.Count-of-Interesting-Subarrays.cpp --- .../2845.Count-of-Interesting-Subarrays.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Hash/2845.Count-of-Interesting-Subarrays/2845.Count-of-Interesting-Subarrays.cpp diff --git a/Hash/2845.Count-of-Interesting-Subarrays/2845.Count-of-Interesting-Subarrays.cpp b/Hash/2845.Count-of-Interesting-Subarrays/2845.Count-of-Interesting-Subarrays.cpp new file mode 100644 index 000000000..cdfd3f712 --- /dev/null +++ b/Hash/2845.Count-of-Interesting-Subarrays/2845.Count-of-Interesting-Subarrays.cpp @@ -0,0 +1,24 @@ +using LL = long long; +class Solution { +public: + long long countInterestingSubarrays(vector& nums, int modulo, int k) + { + int n = nums.size(); + int count = 0; + unordered_mapMap; + Map[0]+=1; + LL ret = 0; + + for (int i=0; i Date: Sun, 3 Sep 2023 10:59:59 -0700 Subject: [PATCH 2058/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ae5e8853d..91641f68f 100644 --- a/Readme.md +++ b/Readme.md @@ -189,6 +189,7 @@ [2488.Count-Subarrays-With-Median-K](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2488.Count-Subarrays-With-Median-K) (H-) [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) [2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) +[2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From 6343eab1829adb94da80885eabc388e90bc834c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 11:05:16 -0700 Subject: [PATCH 2059/2729] Create Readme.md --- Hash/2845.Count-of-Interesting-Subarrays/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hash/2845.Count-of-Interesting-Subarrays/Readme.md diff --git a/Hash/2845.Count-of-Interesting-Subarrays/Readme.md b/Hash/2845.Count-of-Interesting-Subarrays/Readme.md new file mode 100644 index 000000000..ba20a79f1 --- /dev/null +++ b/Hash/2845.Count-of-Interesting-Subarrays/Readme.md @@ -0,0 +1,9 @@ +### 2845.Count-of-Interesting-Subarrays + +看到subarray就想到前缀数组之差。 + +``` +[X X X X X] l X X r +``` + +对于以r为结尾的前缀数组,假设其cnt对于M的取模是kk,那么想要得到以r为结尾、且`cnt%M=k`的subarray,我们只需要查看在r之前有多少前缀数组里的`cnt%M=k-kk`。每一个这样的前缀数组,都对应了一个l与r能够组成符合条件的subarray。 From 76a32ea7685f02a77f1dd3a5199dcb782d434e31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 11:16:23 -0700 Subject: [PATCH 2060/2729] Create 2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp --- ...uences-of-a-String-With-Maximum-Beauty.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp diff --git a/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp new file mode 100644 index 000000000..88c46b8f1 --- /dev/null +++ b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp @@ -0,0 +1,48 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + int k; + int beauty = 0; + LL global = 0; +public: + void dfs(int curPos, int picked, int curBeauty, LL ret, vector&count) + { + if (curBeauty > beauty) return; + if (picked > k) return ; + + if (curBeauty == beauty && picked == k) + { + global = (global+ret)%M; + return; + } + + if (curBeauty + accumulate(count.begin()+curPos, count.end(), 0) < beauty) return; + + for (int i=curPos; ik = k; + unordered_mapMap; + for (auto ch: s) + Map[ch]+=1; + + vectorcount; + for (auto [k,v]: Map) + count.push_back(v); + + sort(count.rbegin(), count.rend()); + if (count.size() Date: Sun, 3 Sep 2023 11:29:02 -0700 Subject: [PATCH 2061/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md diff --git a/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md new file mode 100644 index 000000000..214a3d1f4 --- /dev/null +++ b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md @@ -0,0 +1,9 @@ +### 2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty + +特别注意本题中的k-subsequence要求里面的字符各不相同。所以我们就将26个字符的各自美丽值计算出来,目的是从中取出k个,使得美丽值之和最大。这可以用DFS。 + +另外,其实我们提前将“最大美丽值”计算出来,那必然是将26个美丽值的最大的k个相加。但是我们为什么还要搜索所有的组合呢,因为其中可能有并列的情况。 + +DFS过程中的优化策略: +1. 将count从大到小排列,尽早排除美丽值溢出的情况。 +2. 当已取字母超过k个时即可停止。 From f66585da44b06369452b95f3dccca281b37768de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 11:30:52 -0700 Subject: [PATCH 2062/2729] Update Readme.md --- .../Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md index 214a3d1f4..1ea8de141 100644 --- a/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md +++ b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md @@ -7,3 +7,5 @@ DFS过程中的优化策略: 1. 将count从大到小排列,尽早排除美丽值溢出的情况。 2. 当已取字母超过k个时即可停止。 + +DFS的过程中,每取一个字符,那么subsequence的组合数就乘以该字符的出现次数T(即美丽值),即在这么多相同的字符里选择一个,就有T种选法。 From 237b6fe8d285afd6a6542a6bd0d4ca29fb224d51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 12:23:16 -0700 Subject: [PATCH 2063/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 91641f68f..34b5da8b5 100644 --- a/Readme.md +++ b/Readme.md @@ -513,6 +513,7 @@ [1723.Find-Minimum-Time-to-Finish-All-Jobs](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1723.Find-Minimum-Time-to-Finish-All-Jobs) (H-) [2305.Fair-Distribution-of-Cookies](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2305.Fair-Distribution-of-Cookies) (H-) [2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (M+) +[2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty) (M+) * ``memorization`` [329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix) (M) [2328.Number-of-Increasing-Paths-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2328.Number-of-Increasing-Paths-in-a-Grid) (M) From f13fcd952189585207e4b925756d9d80edc34d4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 16:16:10 -0700 Subject: [PATCH 2064/2729] Update Readme.md --- .../Readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md index 5b835e9a7..5968648b6 100644 --- a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md @@ -1,8 +1,6 @@ ### 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game -如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?我们取一段序列prev[i],i,recevier[i]进行观察。这三个位置在跳转顺序上是从前往后连续的。 - -假设想求以节点i为结尾的、长度为k的序列的最大值,那么我们必然想知道以节点prev[i]为结尾的、长度为k-1的序列的最大值,这样在其基础上加上i就是期望的value. 可见,对于任何一个节点,我们不仅要考虑它为k-size序列终点时的最大value,也要考虑它作为k-1 size序列终点的最大value,以此类推。这样就有转移方程`dp[i][d] = max{dp[prev[i]] + i}`,其中dp[i][d]表示以i为结尾的、长度为d的序列的value最大值,其中`d=1,2,...,k`。 +如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?假设dp[i][d]表示以i为起点的、长度为d的序列的value最大值,其中`d=1,2,...,k`。那么它就依赖于以receiver[i]为起点的、长度为d-1的序列的最大值。依次类推,对于每个位置i,我们需要按d从小到大依次计算它的dp[i][d]. 但在此题中,d的范围是`1e10`,这样的二维数组无法存下。此时有一个技巧叫做binary lifting,第二个维度只需要存储对数个信息。 From c888069fdbeb900be55d7a376c8bee48b3831eb3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 16:17:00 -0700 Subject: [PATCH 2065/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md index 5968648b6..49270c0e3 100644 --- a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md @@ -1,6 +1,6 @@ ### 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game -如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?假设dp[i][d]表示以i为起点的、长度为d的序列的value最大值,其中`d=1,2,...,k`。那么它就依赖于以receiver[i]为起点的、长度为d-1的序列的最大值。依次类推,对于每个位置i,我们需要按d从小到大依次计算它的dp[i][d]. +如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?假设dp[i][d]表示以i为起点的、长度为d的序列的value最大值,其中`d=1,2,...,k`。那么它就依赖于以receiver[i]为起点的、长度为d-1的序列的最大值。继而,依赖于以receiver[receiver[i]]为起点、长度为d-2的序列的最大值。依次类推,对于每个位置i,我们需要按d从小到大依次计算它的dp[i][d]. 但在此题中,d的范围是`1e10`,这样的二维数组无法存下。此时有一个技巧叫做binary lifting,第二个维度只需要存储对数个信息。 From 6bd4260ca9c1e8563ac07d9790ec4dabe848d16d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 22:40:45 -0700 Subject: [PATCH 2066/2729] Create 2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp --- ...eight-Equilibrium-Queries-in-a-Tree_v1.cpp | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp diff --git a/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp new file mode 100644 index 000000000..c4d1e3ad3 --- /dev/null +++ b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp @@ -0,0 +1,91 @@ +class Solution { + vector> next[10005]; + int count[10005][27]; + int parent[10005]; + int level[10005]; +public: + vector minOperationsQueries(int n, vector>& edges, vector>& queries) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], c = edge[2]; + next[a].push_back({b,c}); + next[b].push_back({a,c}); + } + + vectortemp(27); + dfs(0, 0, -1, temp); + parent[0] = -1; + + vectorrets; + for (auto query: queries) + { + int a = query[0], b = query[1]; + int lca = getLCA(0,a,b); + + vectortemp(27); + for (int i=1; i<=26; i++) + { + temp[i] += count[a][i]; + temp[i] += count[b][i]; + temp[i] -= 2*count[lca][i]; + } + + int sum = 0; + int mx = 0; + for (int i=1; i<=26; i++) + { + sum += temp[i]; + mx = max(mx, temp[i]); + } + + rets.push_back(sum - mx); + } + + return rets; + } + + void dfs(int cur, int l, int p, vector&temp) + { + for (auto& child: next[cur]) + { + if (child.first==p) continue; + int w = child.second; + + temp[w]+=1; + for (int i=1; i<=26; i++) + count[child.first][i] = temp[i]; + + parent[child.first] = cur; + level[child.first] = l+1; + + dfs(child.first, l+1, cur, temp); + temp[w]-=1; + } + } + + int getLCA(int node, int p, int q) + { + while (1) + { + if (level[p]>level[q]) + { + p = parent[p]; + } + else if (level[p] Date: Sun, 3 Sep 2023 22:42:06 -0700 Subject: [PATCH 2067/2729] Create 2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp --- ...eight-Equilibrium-Queries-in-a-Tree_v2.cpp | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp diff --git a/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp new file mode 100644 index 000000000..e65543c75 --- /dev/null +++ b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp @@ -0,0 +1,108 @@ +class Solution { + vector> next[10005]; + int count[10005][27]; + int parent[10005]; + int level[10005]; + int ancestor[10005][18]; +public: + vector minOperationsQueries(int n, vector>& edges, vector>& queries) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], c = edge[2]; + next[a].push_back({b,c}); + next[b].push_back({a,c}); + } + + vectortemp(27); + dfs(0, 0, -1, temp); + parent[0] = -1; + + for (int i=0; irets; + for (auto query: queries) + { + int a = query[0], b = query[1]; + // int lca = getLCA(0,a,b); + int lca = getLCA(a,b); + + vectortemp(27); + for (int i=1; i<=26; i++) + { + temp[i] += count[a][i]; + temp[i] += count[b][i]; + temp[i] -= 2*count[lca][i]; + } + + int sum = 0; + int mx = 0; + for (int i=1; i<=26; i++) + { + sum += temp[i]; + mx = max(mx, temp[i]); + } + + rets.push_back(sum - mx); + } + + return rets; + } + + void dfs(int cur, int l, int p, vector&temp) + { + for (auto& child: next[cur]) + { + if (child.first==p) continue; + int w = child.second; + + temp[w]+=1; + for (int i=1; i<=26; i++) + count[child.first][i] = temp[i]; + + parent[child.first] = cur; + level[child.first] = l+1; + + dfs(child.first, l+1, cur, temp); + temp[w]-=1; + } + } + + int getKthAncestor(int i, int k) + { + int cur = i; + for (int j=0; j<=17; j++) + { + if ((k>>j)&1) + cur = ancestor[cur][j]; + } + return cur; + } + + int getLCA(int a, int b) + { + while (level[a]!=level[b]) + { + if (level[a] Date: Sun, 3 Sep 2023 22:42:32 -0700 Subject: [PATCH 2068/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 34b5da8b5..c70223ec2 100644 --- a/Readme.md +++ b/Readme.md @@ -96,6 +96,7 @@ * ``Binary Lifting`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) +[2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree) (H) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From be4232dbd527f61f3cf5ef41c0167cb1858640ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 23:02:05 -0700 Subject: [PATCH 2069/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/Readme.md diff --git a/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/Readme.md b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/Readme.md new file mode 100644 index 000000000..54f8facfd --- /dev/null +++ b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/Readme.md @@ -0,0 +1,9 @@ +### 2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree + +我们以任意节点作为根(比如说0号节点),将整张图看成一棵从上往下有向的树。因为边权的种类只有26个,我们可以用一遍DFS,记录下根到每个节点的路径所包含了的边权种类及其数目。我们记做count[i][j],表示根到节点i的路径中,第j种边权出现了多少次。 + +对于query里的两个节点p、q,我们如果能找到他们的最小公共节点lca,那么就可以得到p->q路径上的每种边权数目,即`count[p][j]+count[q][j]-2*count[lca][j]`,我们遍历一下j,就可以知道路径长度以及出现最多次的边权个数,两者之差就是query的答案。 + +那么如何求lca呢?我们需要在DFS的过程中,顺便知道每个节点的深度level[i]以及它的父节点parent[i].这样,我们先将p,q两点中较深的那个上溯到与另一个相同的深度,然后两者再一层一层共同向上追溯直至它们汇合,这个节点就是它们的LCA。这理论上是o(N)的算法。 + +有一个log(N)的LCA算法,就是利用binary lifting. 我们先利用parent的信息,预先计算出ancestor[i][j],表示节点i向上数第2^j层的祖先。这样我们就可以写出时间复杂度是log(n)的getKthAncestor的函数。对于任意的p与q,我们先计算出它们的深度差,用getKthAncestor将较深的那个节点拉至与另一个节点相同。然后用二分搜值,寻找最小的k,使得p与q的getKthAncestor相同,那么这个相同的节点就是它们的LCA。总的时间复杂度仍然是log(n). From bd1d0f2110c2ff82518b883579e9933bd14d43a6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Sep 2023 17:15:55 -0700 Subject: [PATCH 2070/2729] Update 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp --- ...lue-of-Function-in-a-Ball-Passing-Game.cpp | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp index 5fc76d000..21896fd70 100644 --- a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp @@ -1,18 +1,12 @@ using LL = long long; class Solution { - int pos[100005][35]; LL dp[100005][35]; + int pos[100005][35]; public: long long getMaxFunctionValue(vector& receiver, long long k) { int n = receiver.size(); - int M = 0; - LL K = k; - while (K>0) - { - M++; - K/=2; - } + int M = ceil(log(k)/log(2)); for (int i=0; ibits; - for (int i=0; i>i)&1) bits.push_back(i); } - + LL ret = 0; for (int i=0; i Date: Wed, 6 Sep 2023 17:21:08 -0700 Subject: [PATCH 2071/2729] Update 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp --- ...2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp index 21896fd70..bd15bd280 100644 --- a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp @@ -1,12 +1,12 @@ using LL = long long; class Solution { - LL dp[100005][35]; - int pos[100005][35]; public: long long getMaxFunctionValue(vector& receiver, long long k) { int n = receiver.size(); int M = ceil(log(k)/log(2)); + vector>dp(n+1, vector(M+1)); + vector>pos(n+1, vector(M+1)); for (int i=0; i Date: Sat, 16 Sep 2023 16:59:59 -0700 Subject: [PATCH 2072/2729] Create 2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp --- ...e-Reversals-So-Every-Node-Is-Reachable.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp diff --git a/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp b/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp new file mode 100644 index 000000000..04a9aeeb6 --- /dev/null +++ b/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp @@ -0,0 +1,53 @@ +class Solution { + vector> next[100005]; + vectorrets; +public: + vector minEdgeReversals(int n, vector>& edges) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back({b, 1}); + next[b].push_back({a, -1}); + } + + int count = dfs1(0, -1); + + rets.resize(n); + + dfs2(0, -1, count); + + return rets; + } + + int dfs1(int cur, int parent) + { + int ret = 0; + for (auto& [nxt, dir]: next[cur]) + { + if (nxt==parent) continue; + if (dir==1) + ret += dfs1(nxt, cur); + else + { + ret += dfs1(nxt, cur) + 1; + } + } + return ret; + } + + void dfs2(int cur, int parent, int count) + { + rets[cur] = count; + for (auto& [nxt, dir]: next[cur]) + { + if (nxt==parent) continue; + if (dir == 1) + dfs2(nxt, cur, count+1); + else + dfs2(nxt, cur, count-1); + } + } + + +}; From 0872af0d8662270813f4308526dcfc2ef6de93d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 17:00:26 -0700 Subject: [PATCH 2073/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c70223ec2..fb59edab0 100644 --- a/Readme.md +++ b/Readme.md @@ -306,7 +306,8 @@ [1516.Move-Sub-Tree-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1516.Move-Sub-Tree-of-N-Ary-Tree) (H-) * ``Re-Root`` [834.Sum-of-Distances-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/834.Sum-of-Distances-in-Tree) (H) -[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) +[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) +[2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable) (H-) * ``似树非树`` [823](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/823.Binary-Trees-With-Factors), [1902](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order), From b992e75a33a318ca61e77679fcd196cf67bd19ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 17:14:12 -0700 Subject: [PATCH 2074/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index fb59edab0..e060d2d56 100644 --- a/Readme.md +++ b/Readme.md @@ -306,7 +306,7 @@ [1516.Move-Sub-Tree-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1516.Move-Sub-Tree-of-N-Ary-Tree) (H-) * ``Re-Root`` [834.Sum-of-Distances-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/834.Sum-of-Distances-in-Tree) (H) -[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) +[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) [2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable) (H-) * ``似树非树`` [823](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/823.Binary-Trees-With-Factors), From f8994ac21fc402b2b28526d4234694895d888bcb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 17:18:36 -0700 Subject: [PATCH 2075/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/Readme.md diff --git a/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/Readme.md b/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/Readme.md new file mode 100644 index 000000000..ac266b68d --- /dev/null +++ b/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/Readme.md @@ -0,0 +1,7 @@ +### 2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable + +典型的移根技巧。 + +先用一遍DFS,以node 0为根遍历全树,计算node的reversal edge的数目count. + +然后第二遍DFS,从node 0开始。当dfs从节点i转移至邻接的节点j时,以节点i为根的树的reversal edge count,与节点j为根的树的reversal edge count,其实只相差了"i->j"这条边而已。如果这条边对于i而言是顺边,那么对于j而言就是逆边。反之亦然。所以他们之间的结果只是相差+1/-1而已。 From a3536a4828b60841ad60f5d77a7564b8e3901a2e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 20:42:41 -0700 Subject: [PATCH 2076/2729] Create 2857.Count-Pairs-of-Points-With-Distance-k.cpp --- ....Count-Pairs-of-Points-With-Distance-k.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp diff --git a/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp b/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp new file mode 100644 index 000000000..47584c1c2 --- /dev/null +++ b/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { +public: + int countPairs(vector>& coordinates, int k) + { + int n = coordinates.size(); + + int ret = 0; + for (int a = 0; a<=k; a++) + { + unordered_mapMap; + + for (int i=0; i Date: Sat, 16 Sep 2023 20:43:10 -0700 Subject: [PATCH 2077/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e060d2d56..b865a7ddb 100644 --- a/Readme.md +++ b/Readme.md @@ -1431,6 +1431,7 @@ [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) +[2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) From 3efe1d2e69622849c63f4f356aa02d8d9ae25ca7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 20:46:05 -0700 Subject: [PATCH 2078/2729] Create Readme.md --- Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md diff --git a/Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md b/Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md new file mode 100644 index 000000000..c6818ad82 --- /dev/null +++ b/Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md @@ -0,0 +1,3 @@ +### 2857.Count-Pairs-of-Points-With-Distance-k + +本题的关键点在于k<=100. 因为`(x1 XOR x2) + (y1 XOR y2)`的两个分量都是非负数,所以我们可以穷举`k=a+b`的拆解。已知a,b,通过枚举(x1,y1),我们就可以知道对应的x2,y2. 只需要用Hash查看(x2,y2)是否存在即可。 From e48bdb181ecc08cf4d8946baa88cf9921d8ee4ac Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 22:58:48 -0700 Subject: [PATCH 2079/2729] Create 2860.Happy-Students.cpp --- .../2860.Happy-Students.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Thinking/2860.Happy-Students/2860.Happy-Students.cpp diff --git a/Thinking/2860.Happy-Students/2860.Happy-Students.cpp b/Thinking/2860.Happy-Students/2860.Happy-Students.cpp new file mode 100644 index 000000000..f69cd1bbe --- /dev/null +++ b/Thinking/2860.Happy-Students/2860.Happy-Students.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int countWays(vector& nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + + int ret = 0; + for (int i=0; i+1 nums[i]) && (i+1 < nums[i+1])) + ret++; + } + + if (0 < nums[0]) + ret++; + if (n > nums[n-1]) + ret++; + + return ret; + } +}; From f23c06495d05f50fbb3da1223e650d30a89defba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:04:04 -0700 Subject: [PATCH 2080/2729] Create Readme.md --- Thinking/2860.Happy-Students/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Thinking/2860.Happy-Students/Readme.md diff --git a/Thinking/2860.Happy-Students/Readme.md b/Thinking/2860.Happy-Students/Readme.md new file mode 100644 index 000000000..9c9f9d793 --- /dev/null +++ b/Thinking/2860.Happy-Students/Readme.md @@ -0,0 +1,9 @@ +### 2860.Happy-Students + +我们发现,将nums按照从小到大排序后,如果第i个同学选中并且happy,那么比他小的同学必须选中才能happy。如果第j个同学没选中并且happy,那么比他大的同学也一定要不被选中才能happy。 + +因为所有的同学都happy,这就告诉我们,所有选中的同学必然是相邻的,所有没有选中的同学必然是相邻的。所以我们需要找到这个分界点。只需要遍历所有的间隔位置,判断如果左边选中、右边不选中,是否能够满足让他们两个happy(其他人自然自动满足)。 + +注意这样的分界点没有连续性,它可能离散地出现在任何位置。 + +此外注意全部选中和全部不选两种特殊情况。 From 90cfbafec5c08c0bd5b232bcf9a54326906f6320 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:06:02 -0700 Subject: [PATCH 2081/2729] Update Readme.md --- Readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Readme.md b/Readme.md index b865a7ddb..3db494229 100644 --- a/Readme.md +++ b/Readme.md @@ -1519,6 +1519,10 @@ [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) +#### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   +[2860.Happy-Students](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2860.Happy-Students) (M+) + + #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) [LCP24.数字游戏](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP24.%E6%95%B0%E5%AD%97%E6%B8%B8%E6%88%8F) From c2080543750cb9d9653969a6ea86d1085098e150 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:39:55 -0700 Subject: [PATCH 2082/2729] Create 2861.Maximum-Number-of-Alloys.cpp --- .../2861.Maximum-Number-of-Alloys.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Binary_Search/2861.Maximum-Number-of-Alloys/2861.Maximum-Number-of-Alloys.cpp diff --git a/Binary_Search/2861.Maximum-Number-of-Alloys/2861.Maximum-Number-of-Alloys.cpp b/Binary_Search/2861.Maximum-Number-of-Alloys/2861.Maximum-Number-of-Alloys.cpp new file mode 100644 index 000000000..127a3378d --- /dev/null +++ b/Binary_Search/2861.Maximum-Number-of-Alloys/2861.Maximum-Number-of-Alloys.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { +public: + int maxNumberOfAlloys(int n, int k, int budget, vector>& composition, vector& stock, vector& cost) + { + int ret = 0; + for (auto& comp : composition) + { + int left = 0, right = INT_MAX/2; + while (left < right) + { + int mid = right-(right-left)/2; + if (isOK(mid, n, budget, comp, stock, cost)) + left = mid; + else + right = mid-1; + } + ret = max(ret, left); + } + + return ret; + } + + bool isOK(int t, int n, int budget, vector&comp, vector& stock, vector& cost) + { + LL total = 0; + for (int i=0; i budget) + return false; + } + return true; + } +}; From 1bcaf7367c439c99f08891bf30757b5af34f6ad1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:40:30 -0700 Subject: [PATCH 2083/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3db494229..c0cd79935 100644 --- a/Readme.md +++ b/Readme.md @@ -132,7 +132,8 @@ [2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) [2604.Minimum-Time-to-Eat-All-Grains](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains) (H-) [2616.Minimize-the-Maximum-Difference-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs) (H-) -[2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) +[2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) +[2861.Maximum-Number-of-Alloys](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2861.Maximum-Number-of-Alloys) (M+) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From ffecaa8e6c345bf0f7bf455a3df34cd75bd9491d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:50:12 -0700 Subject: [PATCH 2084/2729] Create Readme.md --- Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md diff --git a/Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md b/Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md new file mode 100644 index 000000000..1ff0524db --- /dev/null +++ b/Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md @@ -0,0 +1,3 @@ +### 2861.Maximum-Number-of-Alloys + +注意:All alloys must be created with the same machine. 对于每个machine,我们用二分搜值来确定在不超过budget的约束下、最多能生产alloy的个数。最后对所有机器取最大值。 From 05f2d9f81160a54a38e9d13f183d8ab3c748b848 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 00:33:45 -0700 Subject: [PATCH 2085/2729] Create 2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp --- ...nt-Sum-of-a-Complete-Subset-of-Indices.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp diff --git a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp new file mode 100644 index 000000000..bbf2597ac --- /dev/null +++ b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp @@ -0,0 +1,20 @@ +using LL = long long; +class Solution { +public: + long long maximumSum(vector& nums) + { + int n = nums.size(); + int k = 1; + LL ret = *max_element(nums.begin(), nums.end()); + while (k Date: Sun, 17 Sep 2023 00:34:08 -0700 Subject: [PATCH 2086/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c0cd79935..15ae02c36 100644 --- a/Readme.md +++ b/Readme.md @@ -1522,6 +1522,7 @@ #### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   [2860.Happy-Students](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2860.Happy-Students) (M+) +[2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) From 2e1d29ec95575cc2e133dacda140317657217fb4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 00:47:01 -0700 Subject: [PATCH 2087/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md diff --git a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md new file mode 100644 index 000000000..ea43a7eed --- /dev/null +++ b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md @@ -0,0 +1,15 @@ +### 2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices + +我们分析一下“任意两个下标i与j的乘积是完全平方数”的含义。我们将i分解为`i=a*x^2`,其中x^2是i里包含的最大平方因子。同理,分解`j=b*y^2`。为了使得```i*j```依然是平方数,那么必然要求`a==b`. 同理,与{i,j}属于同一个集合里的其他下标元素,必然也必须能分解为`a*z^2`的形式。 + +所以为了最大化这个集合(不仅指数目,也指element-sum),集合元素里的那些“最大平方因子”必然是`1^2, 2^2, 3^3, 4^2 ... `直至n。然后我们再穷举`a=1,2,3...`. 就可以构造出所有可能的最优集合,即 + +```1*1, 1*4,1*9, 1*16, ...``` + +```2*1, 2*4,2*9, 2*16, ...``` + +```3*1, 3*4,3*9, 3*16, ...``` + +直至集合最小元素的上限是n。 + +那么我们穷举这些元素的时间复杂度是多少呢?对于`*1`而言,我们穷举了n次。对于`*4`而言,我们穷举了n/4次。对于`*9`而言,我们穷举了n/9次。所以总的穷举数目为`n/1 + n/4 + n/9 + ...`,它是和小于2n的序列。故总的时间复杂度是o(N). From a2bdc3945a0d332eb79c341b1028dfd02d9c51f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 00:48:20 -0700 Subject: [PATCH 2088/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md index ea43a7eed..00d2b3b4e 100644 --- a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md +++ b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md @@ -2,7 +2,7 @@ 我们分析一下“任意两个下标i与j的乘积是完全平方数”的含义。我们将i分解为`i=a*x^2`,其中x^2是i里包含的最大平方因子。同理,分解`j=b*y^2`。为了使得```i*j```依然是平方数,那么必然要求`a==b`. 同理,与{i,j}属于同一个集合里的其他下标元素,必然也必须能分解为`a*z^2`的形式。 -所以为了最大化这个集合(不仅指数目,也指element-sum),集合元素里的那些“最大平方因子”必然是`1^2, 2^2, 3^3, 4^2 ... `直至n。然后我们再穷举`a=1,2,3...`. 就可以构造出所有可能的最优集合,即 +所以为了最大化这个集合(不仅指集合元素的数目,也指element-sum),集合元素里的那些“最大平方因子”必然是`1^2, 2^2, 3^3, 4^2 ... `直至n。然后我们再穷举`a=1,2,3...`. 就可以构造出所有可能的最优集合,即 ```1*1, 1*4,1*9, 1*16, ...``` From da12168078d6ed660f0e02a08e9acf7d05970306 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 11:37:21 -0700 Subject: [PATCH 2089/2729] Update 2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp --- ...-Element-Sum-of-a-Complete-Subset-of-Indices.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp index bbf2597ac..e46a3de45 100644 --- a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp +++ b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp @@ -4,17 +4,18 @@ class Solution { long long maximumSum(vector& nums) { int n = nums.size(); + int k = 1; - LL ret = *max_element(nums.begin(), nums.end()); - while (k Date: Sun, 17 Sep 2023 12:14:29 -0700 Subject: [PATCH 2090/2729] Update 152.Maximum-Product-Subarray_DP.cpp --- .../152.Maximum-Product-Subarray_DP.cpp | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray_DP.cpp b/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray_DP.cpp index 7e456a761..c9ac125f5 100644 --- a/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray_DP.cpp +++ b/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray_DP.cpp @@ -1,20 +1,27 @@ +using LL = long long; class Solution { public: int maxProduct(vector& nums) - { - int n = nums.size(); - vectordp1(n); - vectordp2(n); + { + int n = nums.size(); + vectordp1(n); // the max prod subarray ending at i + vectordp2(n); // the min prod subarray ending at i dp1[0] = nums[0]; dp2[0] = nums[0]; - long ret = nums[0]; + LL ret = nums[0]; for (int i=1; i Date: Sun, 17 Sep 2023 12:17:39 -0700 Subject: [PATCH 2091/2729] Delete Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp --- .../152.Maximum-Product-Subarray.cpp | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp diff --git a/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp b/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp deleted file mode 100644 index 7364334fd..000000000 --- a/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int maxProduct(vector& nums) - { - long MAX = 1; - long MIN = 1; - long ret = INT_MIN; - - for (int i=0; i Date: Sun, 17 Sep 2023 15:06:32 -0700 Subject: [PATCH 2092/2729] Update 2746.Decremental-String-Concatenation.cpp --- .../2746.Decremental-String-Concatenation.cpp | 41 +++++++++++-------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp b/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp index b527768e3..502c2e4b1 100644 --- a/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp +++ b/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp @@ -2,31 +2,40 @@ class Solution { int memo[1005][26][26]; public: int minimizeConcatenatedLength(vector& words) - { + { return words[0].size() + dfs(1, words[0][0]-'a', words[0].back()-'a', words); } - - // The minimum letters to be added if we construct the first i words with start & end. - int dfs(int i, int start, int end, vector& words) - { + + // the minimum length to be added if we construct the first i words with start & end + int dfs(int i, int start, int end, vector& words) + { if (i==words.size()) return 0; - if (memo[i][start][end]!=0) return memo[i][start][end]; - - int ret = INT_MAX/2; + int a = words[i][0]-'a', b = words[i].back()-'a'; int len = words[i].size(); + int ret = INT_MAX/2; - if (end==a) - ret = min(ret, len-1 + dfs(i+1, start, b, words)); + if (start==a && end==b) + { + // it does not matter we put words[i] at the beginning or at the end; + ret = len - (a==b) + dfs(i+1, start, end, words); + } else - ret = min(ret, len + dfs(i+1, start, b, words)); + { + // place words[i] at the end + if (end==a) + ret = min(ret, len-1 + dfs(i+1, start, b, words)); + else + ret = min(ret, len + dfs(i+1, start, b, words)); + + // place words[i] at the beginning + if (start==b) + ret = min(ret, len-1 + dfs(i+1, a, end, words)); + else + ret = min(ret, len + dfs(i+1, a, end, words)); + } - if (start==b) - ret = min(ret, len-1 + dfs(i+1, a, end, words)); - else - ret = min(ret, len + dfs(i+1, a, end, words)); - memo[i][start][end] = ret; return ret; } From 514cf30c012fda0f44af3c5c284eea01baff7c4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:36:35 -0700 Subject: [PATCH 2093/2729] Update Readme.md --- DFS/2746.Decremental-String-Concatenation/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/DFS/2746.Decremental-String-Concatenation/Readme.md b/DFS/2746.Decremental-String-Concatenation/Readme.md index a9fc78ce9..7c9a8e64b 100644 --- a/DFS/2746.Decremental-String-Concatenation/Readme.md +++ b/DFS/2746.Decremental-String-Concatenation/Readme.md @@ -20,3 +20,12 @@ else 最终的答案就是初始调用的`words[0].size() + dfs(1, words[0][0], words[0].back())`,因为对于words[0]我们只有唯一的构造形式。 另外,我们必然要用记忆化来避免相同参数的dfs重复调用。 + +更新:为了过更严格的case,需要再加一个优化的技巧 +```cpp +if (start==a && end==b) +{ + // it does not matter we put words[i] at the beginning or at the end; + ret = len - (a==b) + dfs(i+1, start, end, words); +} +``` From 739a200208d7b4b250b594dd173a1ade2efa6ba9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:40:23 -0700 Subject: [PATCH 2094/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 15ae02c36..4ea6f6d33 100644 --- a/Readme.md +++ b/Readme.md @@ -1197,7 +1197,6 @@ [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) -[229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [659.Split-Array-into-Consecutive-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/659.Split-Array-into-Consecutive-Subsequences) (H) [386.Lexicographical-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/386.Lexicographical-Numbers) (H) 624.Maximum-Distance-in-Arrays (M) @@ -1266,6 +1265,8 @@ [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) +* ``Boyer-Moore Majority Voting +[229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From 54b6caf9c2c8399c51a34153a6c571f787519484 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:40:57 -0700 Subject: [PATCH 2095/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 4ea6f6d33..9bc0dce7e 100644 --- a/Readme.md +++ b/Readme.md @@ -1265,7 +1265,7 @@ [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) -* ``Boyer-Moore Majority Voting +* Boyer-Moore Majority Voting [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) From dec25819d6d2c7df2236434ed1f54a16e9959ef3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:41:52 -0700 Subject: [PATCH 2096/2729] Create 2856.Minimum-Array-Length-After-Pair-Removals.cpp --- ...nimum-Array-Length-After-Pair-Removals.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Greedy/2856.Minimum-Array-Length-After-Pair-Removals/2856.Minimum-Array-Length-After-Pair-Removals.cpp diff --git a/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/2856.Minimum-Array-Length-After-Pair-Removals.cpp b/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/2856.Minimum-Array-Length-After-Pair-Removals.cpp new file mode 100644 index 000000000..facb827a9 --- /dev/null +++ b/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/2856.Minimum-Array-Length-After-Pair-Removals.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int minLengthAfterRemovals(vector& nums) + { + int n = nums.size(); + unordered_mapMap; + for (int i=0; i n/2) + return n - (n-mx)*2; + else + return (n%2); + + } +}; From 2e18b4c78002fd044bdd42de3ec9f9d228719e38 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:42:18 -0700 Subject: [PATCH 2097/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9bc0dce7e..975e8b42b 100644 --- a/Readme.md +++ b/Readme.md @@ -1266,7 +1266,8 @@ [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) * Boyer-Moore Majority Voting -[229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) +[229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) +[2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From 83ba92258b906082cbf558a75c2d9235a8f3a919 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 18:49:31 -0700 Subject: [PATCH 2098/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2856.Minimum-Array-Length-After-Pair-Removals/Readme.md diff --git a/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/Readme.md b/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/Readme.md new file mode 100644 index 000000000..109179d8a --- /dev/null +++ b/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/Readme.md @@ -0,0 +1,7 @@ +### 2856.Minimum-Array-Length-After-Pair-Removals + +本题的本质就是Boyer-Moore Majority Voting Algorithm的实现。当存在一个超过半数的majority时,显然其他所有元素“联合”起来不能使它“消除”。反过来的结论也是成立的。 + +所以,当存在一个超过半数的majority时,记它的频次是f。那么剩余元素的频次是n-f。每个其他元素消灭一个多数元素,剩下的就是`n-(n-f)*2`. + +当不存在超过半数的majority时,理论上是能够最终彼此消灭的,但是别忘了n的奇偶性。当n是奇数时一定会有一个元素留下来。 From 9338cabb49e8240f16db706b6f7e85814cce8646 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 21:46:13 -0700 Subject: [PATCH 2099/2729] Create 2802.Find-The-K-th-Lucky-Number.cpp --- .../2802.Find-The-K-th-Lucky-Number.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/2802.Find-The-K-th-Lucky-Number.cpp diff --git a/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/2802.Find-The-K-th-Lucky-Number.cpp b/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/2802.Find-The-K-th-Lucky-Number.cpp new file mode 100644 index 000000000..ed3460187 --- /dev/null +++ b/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/2802.Find-The-K-th-Lucky-Number.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string kthLuckyNumber(int k) + { + int x = 2+k-1; + string ret; + while (x>0) + { + if (x%2==0) + ret.push_back('4'); + else + ret.push_back('7'); + x/=2; + } + ret.pop_back(); + reverse(ret.begin(), ret.end()); + return ret; + } +}; From 3b20f8e2f634f951be98a1424c7ca85e2acbeb90 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 21:46:38 -0700 Subject: [PATCH 2100/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 975e8b42b..86464938d 100644 --- a/Readme.md +++ b/Readme.md @@ -910,6 +910,7 @@ [1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) [2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) [2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) +[2802.Find-The-K-th-Lucky-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From b0811a366d824d2dee307d5309c7477c9e171c40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 21:51:18 -0700 Subject: [PATCH 2101/2729] Create Readme.md --- .../2802.Find-The-K-th-Lucky-Number/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/Readme.md diff --git a/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/Readme.md b/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/Readme.md new file mode 100644 index 000000000..93eb946a7 --- /dev/null +++ b/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/Readme.md @@ -0,0 +1,13 @@ +### 2802.Find-The-K-th-Lucky-Number + +这是一个常见的技巧。Lucky Number仅由两个digit组成,所以它是"4"与"7",还是“0”与“1”,没有本质区别。我们索性就利用二进制数来构造第k大的01序列。 + +因为任何二进制数都没有先导零,第一位总是1。所以我们排除所有二进制数的第一个bit 1,剩余的bit位恰好就构成了递增的01序列。举例如下: +``` +2: 10 -> 0 +3: 11 -> 1 +4: 100 -> 00 +5: 101 -> 01 +6: 110 -> 10 +``` +我们从2开始枚举自然数,得到其二进制表达式,去掉先导1,剩余的部分就是递增的01序列。我们将其替换为“4”“7”序列即可。 From bd61e4f13d8878ee2c9cbf5d0ebcdb2f3259d32a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Sep 2023 00:03:13 -0700 Subject: [PATCH 2102/2729] Create 2851.String-Transformation.cpp --- .../2851.String-Transformation.cpp | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Dynamic_Programming/2851.String-Transformation/2851.String-Transformation.cpp diff --git a/Dynamic_Programming/2851.String-Transformation/2851.String-Transformation.cpp b/Dynamic_Programming/2851.String-Transformation/2851.String-Transformation.cpp new file mode 100644 index 000000000..11bf0bf25 --- /dev/null +++ b/Dynamic_Programming/2851.String-Transformation/2851.String-Transformation.cpp @@ -0,0 +1,82 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int numberOfWays(string s, string t, long long k) + { + string ss = s+s; + ss.pop_back(); + int p = strStr(ss,t); + + int n = s.size(); + vector T = {n-p-1, n-p, p, p-1}; + vector Tk = quickMul(T, k); + + if (s==t) + return Tk[3]; // Tk * (0, 1)' + else + return Tk[2]; // Tk * (1, 0)' + } + + vector multiply(vectormat1, vectormat2) + { + // a1 b1 a2 b2 + // c1 d1 c2 d2 + LL a1 = mat1[0], b1 = mat1[1], c1 = mat1[2], d1 = mat1[3]; + LL a2 = mat2[0], b2 = mat2[1], c2 = mat2[2], d2 = mat2[3]; + return {(a1*a2+b1*c2)%M, (a1*b2+b1*d2)%M, (c1*a2+d1*c2)%M, (c1*b2+d1*d2)%M}; + } + + vector quickMul(vectormat, LL N) { + if (N == 0) { + return {1,0,0,1}; + } + vector mat2 = quickMul(mat, N/2); + if (N%2==0) + return multiply(mat2, mat2); + else + return multiply(multiply(mat2, mat2), mat); + } + + int strStr(string haystack, string needle) + { + int count = 0; + + int n = haystack.size(); + int m = needle.size(); + + vector suf = preprocess(needle); + + vectordp(n,0); + dp[0] = (haystack[0]==needle[0]); + if (m==1 && dp[0]==1) + count++; + + for (int i=1; i0 && haystack[i]!=needle[j]) + j = suf[j-1]; + dp[i] = j + (haystack[i]==needle[j]); + if (dp[i]==needle.size()) + count++; + } + return count; + } + + vector preprocess(string s) + { + int n = s.size(); + vectordp(n,0); + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + return dp; + } +}; From 5ac3a412cdd447938ee03614cf362402d8bca661 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Sep 2023 00:04:09 -0700 Subject: [PATCH 2103/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 86464938d..af48e68c5 100644 --- a/Readme.md +++ b/Readme.md @@ -711,6 +711,7 @@ [2787.Ways-to-Express-an-Integer-as-Sum-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers) (M+) [2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) [2826.Sorting-Three-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2826.Sorting-Three-Groups) (M) +[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) @@ -986,6 +987,7 @@ 1397.Find All Good Strings (TBD) [1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array) (H) [2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/String/2301.Match-Substring-After-Replacement) (H-) +[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From a368c03543b78d0f57c5ceba68978c9a7f4a31ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Sep 2023 00:24:08 -0700 Subject: [PATCH 2104/2729] Create Readme.md --- .../2851.String-Transformation/Readme.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dynamic_Programming/2851.String-Transformation/Readme.md diff --git a/Dynamic_Programming/2851.String-Transformation/Readme.md b/Dynamic_Programming/2851.String-Transformation/Readme.md new file mode 100644 index 000000000..7cc77c00f --- /dev/null +++ b/Dynamic_Programming/2851.String-Transformation/Readme.md @@ -0,0 +1,26 @@ +### 2851.String-Transformation + +首先,本题中的操作相当于切牌。无论一次切最后k张牌,都等效于切k次最后一张牌。最终得到的序列依然是原序列的shift而已。我们记s(i)表示以将字符串s调整后、变成以原来第i个元素为首的一个shift、 + +显然,只有对应部分的i,可以使得`s(i)=t`。我们可以先用KMP算法,算出t在`s+s`中能匹配几次。我们就可以记录有p种shift使得`s(i)=t`,其中`p<=n`. + +对于每次操作,我们有n-1次选择(对应不同的shift),那么经过k次操作之后,s(i)的分布是什么呢?我们特别关心上述的p种shift,因为它们对应着我们想要的答案。 + +我们令f[j]表示经过t次操作后不是想要的shift(我们称为未匹配)的操作数目(也就是字串数目),令g[j]表示经过t次操作后恰是想要的shift(称为匹配)的操作数(也就是字串数目)。我们有动态转移方程: +``` +f[j] = (n-p-1)*f[j-1] + (n-p)*g[j-1] +g[j] = p*f[j-1] + (p-1)*g[j-1] +``` +第一行的解释:对于j-1轮不匹配的字串,下一轮有n-p-1种操作依然得到不匹配的字串(因为不能shift成自己)。对于j-1轮已经匹配的字串,下一轮有n-p种操作变成不匹配的字串。同理第二行的解释:对于j-1轮不匹配的字串,下一轮有p种操作变成匹配的字串。对于j-1轮已经匹配的字串,下一轮有p-1种操作依然变成匹配的字串(因为不能shift成自己)。 + +所以我们有状态转移 (f,g)'(j) = T * (f,g)'(j-1),其中转移矩阵 +``` +T = [n-p-1, n-p + p, p-1 ] +``` +所以第k轮操作之后,(f,g)'(k) = T^k * (f,g)'(0). 注意,T^k依然是一个2x2的矩阵。 + +其中如果初始时s==t,那么(f,g)(0) = {0, 1},否则 (f,g)(0) = {1, 0}。 另外`T^k`可以用快速幂的思想,用log(k)的时间计算。最后记得再与初始状态`(f,g)'(0)`相乘。 + +由此我们计算出 (f,g)(k),得到第k轮时变成未匹配字串的数目,以及变成匹配字串的数目(答案)。 + From db1cb64ca9635c7aa342b3f67ee6442fe679bf1d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Sep 2023 05:33:50 -0700 Subject: [PATCH 2105/2729] Update Readme.md --- Dynamic_Programming/2851.String-Transformation/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2851.String-Transformation/Readme.md b/Dynamic_Programming/2851.String-Transformation/Readme.md index 7cc77c00f..73463292b 100644 --- a/Dynamic_Programming/2851.String-Transformation/Readme.md +++ b/Dynamic_Programming/2851.String-Transformation/Readme.md @@ -6,7 +6,7 @@ 对于每次操作,我们有n-1次选择(对应不同的shift),那么经过k次操作之后,s(i)的分布是什么呢?我们特别关心上述的p种shift,因为它们对应着我们想要的答案。 -我们令f[j]表示经过t次操作后不是想要的shift(我们称为未匹配)的操作数目(也就是字串数目),令g[j]表示经过t次操作后恰是想要的shift(称为匹配)的操作数(也就是字串数目)。我们有动态转移方程: +我们令f[j]表示经过j次操作后不是想要的shift(我们称为未匹配)的操作数目(也就是字串数目),令g[j]表示经过j次操作后恰是想要的shift(称为匹配)的操作数(也就是字串数目)。我们有动态转移方程: ``` f[j] = (n-p-1)*f[j-1] + (n-p)*g[j-1] g[j] = p*f[j-1] + (p-1)*g[j-1] From ca159413a85ce2b0bbaf87a3c371667b4b7099ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 10:08:25 -0700 Subject: [PATCH 2106/2729] Create 2867.Count-Valid-Paths-in-a-Tree.cpp --- .../2867.Count-Valid-Paths-in-a-Tree.cpp | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Union_Find/2867.Count-Valid-Paths-in-a-Tree/2867.Count-Valid-Paths-in-a-Tree.cpp diff --git a/Union_Find/2867.Count-Valid-Paths-in-a-Tree/2867.Count-Valid-Paths-in-a-Tree.cpp b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/2867.Count-Valid-Paths-in-a-Tree.cpp new file mode 100644 index 000000000..5dd25e266 --- /dev/null +++ b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/2867.Count-Valid-Paths-in-a-Tree.cpp @@ -0,0 +1,91 @@ +using LL = long long; +class Solution { + int Father[100005]; + vector next[100005]; + unordered_setprimes; + LL global = 0; +public: + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (xEratosthenes(int n) + { + vectorq(n+1,0); + unordered_setprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.insert(i); + } + return primes; + } + + bool isPrime(int x) + { + return primes.find(x)!=primes.end(); + } + + long long countPaths(int n, vector>& edges) + { + primes = Eratosthenes(n); + + for (int i=1; i<=n; i++) + Father[i] = i; + + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + if (!isPrime(a) && !isPrime(b)) + { + if (FindFather(a)!=FindFather(b)) + Union(a,b); + } + } + + unordered_mapMap; + for (int i=1; i<=n; i++) + Map[FindFather(i)]+=1; + + for (int p: primes) + { + vectorarr; + for (int nxt: next[p]) + { + if (!isPrime(nxt)) + arr.push_back(Map[FindFather(nxt)]); + } + LL total = accumulate(arr.begin(), arr.end(), 0LL); + LL sum = 0; + for (LL x: arr) + sum += x*(total-x); + global += sum/2 + total; + } + + return global; + } + +}; From 44b4e5a838018ca3c0b2c60f1adbd6c523b5f5ae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 10:08:57 -0700 Subject: [PATCH 2107/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index af48e68c5..54ffd4a0f 100644 --- a/Readme.md +++ b/Readme.md @@ -1020,6 +1020,7 @@ [2092.Find-All-People-With-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2092.Find-All-People-With-Secret) (H-) [2157.Groups-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2157.Groups-of-Strings) (H) [2492.Minimum-Score-of-a-Path-Between-Two-Cities](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities) (M) +[2867.Count-Valid-Paths-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2867.Count-Valid-Paths-in-a-Tree) (M+) * ``Union in an order`` [803.Bricks-Falling-When-Hit](https://github.com/wisdompeak/LeetCode/tree/master/DFS/803.Bricks-Falling-When-Hit) (H) [1970.Last-Day-Where-You-Can-Still-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1970.Last-Day-Where-You-Can-Still-Cross) (H-) From fa0e832ad125ceb4df66ff1a8bf574277ae97548 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 10:20:39 -0700 Subject: [PATCH 2108/2729] Create Readme.md --- .../2867.Count-Valid-Paths-in-a-Tree/Readme.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md diff --git a/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md new file mode 100644 index 000000000..fbbf41d92 --- /dev/null +++ b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md @@ -0,0 +1,16 @@ +### 2867.Count-Valid-Paths-in-a-Tree + +很显然,因为需要计数的path只有一个prime,我们必然count paths by prime. + +我们考虑每个是质数的节点P,考虑经过它的有效路径。显然,一个最显著的pattern就是:从P某个联通的合数节点(不需要紧邻但是不能被其他质数隔开)开始,经过P,再到P的另一个联通的合数。 + +假设A有M个紧邻的合数节点(显然不会关注紧邻的质数节点),这些合数节点又各自分别于若干个合数节点联通,记这些联通区域里分别有m1,m2,m3...个联通的合数节点。显然,从m1里的任何一个节点,到除m1里的任意节点,都是合法路径。令`m1+m2+m3+...=total`,则有 +```cpp +for (int i=1; i<=M; i++) + count += m_i * (total - mi); +``` +但是注意,以上的count对于起点、终点互换的路径是重复计算了,所以最终有效的是count/2条路径。 + +另外,有效路径的第二个pattern,就是以P为起点,终点是任意与P联通的合数节点,这样的路径恰好就是total条。 + +最终的答案就是对于每个P,累加`count/2+total`. From 29d1abeba79dd7f8cff709c4ca74f9b9d9f15202 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 10:20:54 -0700 Subject: [PATCH 2109/2729] Update Readme.md --- Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md index fbbf41d92..4ea6c5780 100644 --- a/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md +++ b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md @@ -7,7 +7,7 @@ 假设A有M个紧邻的合数节点(显然不会关注紧邻的质数节点),这些合数节点又各自分别于若干个合数节点联通,记这些联通区域里分别有m1,m2,m3...个联通的合数节点。显然,从m1里的任何一个节点,到除m1里的任意节点,都是合法路径。令`m1+m2+m3+...=total`,则有 ```cpp for (int i=1; i<=M; i++) - count += m_i * (total - mi); + count += m_i * (total - m_i); ``` 但是注意,以上的count对于起点、终点互换的路径是重复计算了,所以最终有效的是count/2条路径。 From cc5efd907f59fdde80b555d977b243eeb0b1c21f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 11:46:59 -0700 Subject: [PATCH 2110/2729] Create 2866.Beautiful-Towers-II.cpp --- .../2866.Beautiful-Towers-II.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Stack/2866.Beautiful-Towers-II/2866.Beautiful-Towers-II.cpp diff --git a/Stack/2866.Beautiful-Towers-II/2866.Beautiful-Towers-II.cpp b/Stack/2866.Beautiful-Towers-II/2866.Beautiful-Towers-II.cpp new file mode 100644 index 000000000..299b4d379 --- /dev/null +++ b/Stack/2866.Beautiful-Towers-II/2866.Beautiful-Towers-II.cpp @@ -0,0 +1,52 @@ +using LL = long long; +class Solution { +public: + long long maximumSumOfHeights(vector& maxHeights) + { + maxHeights.insert(maxHeights.begin(), 0); + maxHeights.push_back(0); + + vectorleft = helper(maxHeights); + + reverse(maxHeights.begin(), maxHeights.end()); + vectorright = helper(maxHeights); + reverse(right.begin(), right.end()); + + reverse(maxHeights.begin(), maxHeights.end()); + + LL ret = 0; + + for (int i=0; ihelper(vectormaxHeights) + { + int n = maxHeights.size(); + stackstk; + vectorarr(n); + LL sum = 0; + stk.push(0); + arr[i] = 0; + for (int i=1; i Date: Sun, 24 Sep 2023 12:20:20 -0700 Subject: [PATCH 2111/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 54ffd4a0f..3d58e527a 100644 --- a/Readme.md +++ b/Readme.md @@ -376,6 +376,7 @@ [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) [2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) [2764.is-Array-a-Preorder-of-Some-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree) (M+) +[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) From 74e8f19d0201d5dae10cbb26dd238586146f9504 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 12:24:31 -0700 Subject: [PATCH 2112/2729] Update Readme.md --- Readme.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Readme.md b/Readme.md index 3d58e527a..7b2ed951d 100644 --- a/Readme.md +++ b/Readme.md @@ -376,16 +376,12 @@ [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) [2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) [2764.is-Array-a-Preorder-of-Some-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree) (M+) -[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) -[084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) -[085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [255.Verify-Preorder-Sequence-in-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/255.Verify-Preorder-Sequence-in-Binary-Search-Tree) (H) [496.Next-Greater-Element-I](https://github.com/wisdompeak/LeetCode/tree/master/Stack/496.Next-Greater-Element-I) (H-) [503.Next-Greater-Element-II](https://github.com/wisdompeak/LeetCode/blob/master/Stack/503.Next-Greater-Element-II) (H-) -[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [654.Maximum-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/654.Maximum-Binary-Tree) (H) [739.Daily-Temperatures](https://github.com/wisdompeak/LeetCode/tree/master/Stack/739.Daily-Temperatures) (H-) [768.Max-Chunks-To-Make-Sorted-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/768.Max-Chunks-To-Make-Sorted-II) (H-) @@ -399,14 +395,18 @@ [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) -[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) -* ``monotonic stack: other usages`` +[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) +* ``monotonic stack: other usages`` +[084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) +[085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) +[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) -[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) +[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) +[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) [1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) From cee2b2068af386cd6b08f744d0b99183faa493df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 12:25:49 -0700 Subject: [PATCH 2113/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 7b2ed951d..ff012335f 100644 --- a/Readme.md +++ b/Readme.md @@ -396,7 +396,7 @@ [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) [2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) -* ``monotonic stack: other usages`` +* ``monotonic stack: other usages`` [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) @@ -405,7 +405,7 @@ [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) -[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) +[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) [2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) From 160aa29493f7bbf880a9e522e357f51d18cabcd5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 12:41:38 -0700 Subject: [PATCH 2114/2729] Create Readme.md --- Stack/2866.Beautiful-Towers-II/Readme.md | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Stack/2866.Beautiful-Towers-II/Readme.md diff --git a/Stack/2866.Beautiful-Towers-II/Readme.md b/Stack/2866.Beautiful-Towers-II/Readme.md new file mode 100644 index 000000000..12d0a3b76 --- /dev/null +++ b/Stack/2866.Beautiful-Towers-II/Readme.md @@ -0,0 +1,30 @@ +### 2866.Beautiful-Towers-II + +我们很容易想到,遍历每个位置p,假想它作为peak(自然设置为maxHeights[p]),那么我们可以得到的最大面积是多少。 + +如果p是peak,那么它左边必然是一个单调递增的序列。我们逐个来扫描这些位置。 +1. 如果maxHeights[i]始终是递增的,那么我们每次只需增加mexHeights[i]即可。 +2. 如果maxHeights[i]比之前的位置矮,那么i之前的位置受到新的制约,必须退回之前所盖的高度,转而盖成与maxHeights[i]平齐的高度。显然,这样的“回退”可能不止一次。 + +这些思考都让我们联想到单调栈。我们应该试图在stk里存放单调递增的高度(实际上是对应的位置)。当前述的情形2发生时,即`maxHeights[stk.top()] > maxHeights[i]`时,我们令 +```cpp +p1 = stk.top(); +stk.pop(); +p2 = stk.top(); +``` +我们对栈顶元素p1退栈时,要“回退”的面积其实是`(p1-p2)*maxHeights[p1]`,也就是说,之前[p2+1, p1]这一段最理想的状态是都与maxHeights[p1]平齐,这样既不超过p1的约束,也最大化了总面积。 + +同理,退完p1之后,如果发现`maxHeights[p2] > maxHeights[i]`时,我们依然要继续退栈,同上,退出一段与maxHeights[p2]平齐的高度。 + +当所有的回退完成之后,我们保证了maxHeights[i]高于当前的栈顶元素(假设为pp),那么意味着从[pp+1,i]这段区间我们都可以最大化设置为maxHeights[i]。 + +此时的总面积就是从左往右截止到i位置,为了保持递增关系,能够得到的最大面积,记做left[i]. + +同理,我们将上面的过程反过来,从右往左做一遍,得到从右往左截止到i位置,为了保持递增关系,能够得到的最大面积,记做right[i]. + +那么以i为peak的最大总面积就是`area[i] = left[i]+right[i]-maxHeights[i]`. + +我们在所有的area[i]取全局最大值即可。 + +此题的解法和`084.Largest-Rectangle-in-Histogram`非常类似。 + From 43795d67e1924b5a23de62eb0c8ba0cb2ccaebaa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:11:52 -0700 Subject: [PATCH 2115/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index ff012335f..f8dfb1cce 100644 --- a/Readme.md +++ b/Readme.md @@ -378,7 +378,6 @@ [2764.is-Array-a-Preorder-of-Some-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree) (M+) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) -[2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [255.Verify-Preorder-Sequence-in-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/255.Verify-Preorder-Sequence-in-Binary-Search-Tree) (H) [496.Next-Greater-Element-I](https://github.com/wisdompeak/LeetCode/tree/master/Stack/496.Next-Greater-Element-I) (H-) [503.Next-Greater-Element-II](https://github.com/wisdompeak/LeetCode/blob/master/Stack/503.Next-Greater-Element-II) (H-) @@ -397,7 +396,8 @@ [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) [2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) * ``monotonic stack: other usages`` -[084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) +[084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) +[2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) From e52bc313921e7c1de43f6a9baef584dcf438da32 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:12:55 -0700 Subject: [PATCH 2116/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index f8dfb1cce..33c9c0a27 100644 --- a/Readme.md +++ b/Readme.md @@ -385,7 +385,8 @@ [739.Daily-Temperatures](https://github.com/wisdompeak/LeetCode/tree/master/Stack/739.Daily-Temperatures) (H-) [768.Max-Chunks-To-Make-Sorted-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/768.Max-Chunks-To-Make-Sorted-II) (H-) [901.Online-Stock-Span](https://github.com/wisdompeak/LeetCode/tree/master/Stack/901.Online-Stock-Span) (H-) -[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) +[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) +[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1856.Maximum-Subarray-Min-Product](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1856.Maximum-Subarray-Min-Product) (M+) [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [1019.Next-Greater-Node-In-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1019.Next-Greater-Node-In-Linked-List) (M) @@ -400,7 +401,6 @@ [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) -[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) From 63937036a85ba8f613f8049a17d88135bc9b6496 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:15:23 -0700 Subject: [PATCH 2117/2729] Update Readme.md --- Readme.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index 33c9c0a27..45857ff03 100644 --- a/Readme.md +++ b/Readme.md @@ -386,12 +386,12 @@ [768.Max-Chunks-To-Make-Sorted-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/768.Max-Chunks-To-Make-Sorted-II) (H-) [901.Online-Stock-Span](https://github.com/wisdompeak/LeetCode/tree/master/Stack/901.Online-Stock-Span) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) -[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1856.Maximum-Subarray-Min-Product](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1856.Maximum-Subarray-Min-Product) (M+) [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [1019.Next-Greater-Node-In-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1019.Next-Greater-Node-In-Linked-List) (M) [1063.Number-of-Valid-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1063.Number-of-Valid-Subarrays) (M+) -[1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) +[1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) +[1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) @@ -400,8 +400,8 @@ [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) -[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) -[1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) +[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) +[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) From ded283b7e1f3bc7e34cc2ac47126c4c07629c3da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:29:18 -0700 Subject: [PATCH 2118/2729] Create 2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp --- ...nimum-Moves-to-Spread-Stones-Over-Grid.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp diff --git a/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp new file mode 100644 index 000000000..f267baafa --- /dev/null +++ b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp @@ -0,0 +1,33 @@ +class Solution { + int global = INT_MAX; +public: + int minimumMoves(vector>& grid) + { + dfs(0, 0, grid); + return global; + } + + void dfs(int cur, int total, vector>& grid) + { + if (total >= global) return; + + int i = cur/3; + int j = cur%3; + if (grid[i][j]!=0) + { + dfs(cur+1, total, grid); + return; + } + + for (int x=0; x<3; x++) + for (int y=0; y<3; y++) + { + if (grid[x][y]<=1) continue; + grid[x][y]-=1; + grid[i][j]+=1; + dfs(cur+1, total+abs(x-i)+abs(y-j), grid); + grid[x][y]+=1; + grid[i][j]-=1; + } + } +}; From 91a37564b2194fbada70ad07f09cc6665cfb521e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:32:25 -0700 Subject: [PATCH 2119/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/Readme.md diff --git a/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/Readme.md b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/Readme.md new file mode 100644 index 000000000..282e71043 --- /dev/null +++ b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/Readme.md @@ -0,0 +1,13 @@ +### 2850.Minimum-Moves-to-Spread-Stones-Over-Grid + +本题的关键点在于判断出时间复杂度,可以用DFS无脑搜索。 + +假设只有一个空格,需要从其他八个格子转移一个过去,那么就有8^1种可能。 + +假设有两个空格,需要从其他七个格子分别转移一个过去,那么就有7^2种可能。 + +假设有三个空格,需要从其他六个格子分别转移一个过去,那么就有6^3种可能。 + +以此类推,5^4, 4^5, 3^6, 2^7, 1^8,其实数值都不大。 + +所以无脑搜索每个空格的转移策略即可。 From 105736ac52ba7b9d3d7bc9fcce7c64dba502cb99 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:34:17 -0700 Subject: [PATCH 2120/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 45857ff03..433b60071 100644 --- a/Readme.md +++ b/Readme.md @@ -504,6 +504,7 @@ [2014.Longest-Subsequence-Repeated-k-Times](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2014.Longest-Subsequence-Repeated-k-Times) (H) [2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) [2065.Maximum-Path-Quality-of-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2065.Maximum-Path-Quality-of-a-Graph) (M) +[2850.Minimum-Moves-to-Spread-Stones-Over-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid) (M) * ``search in an array`` [090.Subsets-II](https://github.com/wisdompeak/LeetCode/tree/master/DFS/090.Subsets-II) (M+) [301.Remove-Invalid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/DFS/301.Remove-Invalid-Parentheses) (H) From 8588b3290a8efac97494d772e902af6a3b5dab58 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:47:34 -0700 Subject: [PATCH 2121/2729] Update 2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp --- ...nimum-Moves-to-Spread-Stones-Over-Grid.cpp | 34 +++++++++++-------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp index f267baafa..77f2f0a44 100644 --- a/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp +++ b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp @@ -3,31 +3,37 @@ class Solution { public: int minimumMoves(vector>& grid) { - dfs(0, 0, grid); - return global; + dfs(0, 0, grid); + return global; } - - void dfs(int cur, int total, vector>& grid) + + void dfs(int cur, int moves, vector>& grid) { - if (total >= global) return; + if (moves >= global) return; + + if (cur==9) + { + global = min(global, moves); + return; + } int i = cur/3; int j = cur%3; if (grid[i][j]!=0) { - dfs(cur+1, total, grid); + dfs(cur+1, moves, grid); return; - } + } for (int x=0; x<3; x++) for (int y=0; y<3; y++) { - if (grid[x][y]<=1) continue; - grid[x][y]-=1; - grid[i][j]+=1; - dfs(cur+1, total+abs(x-i)+abs(y-j), grid); - grid[x][y]+=1; - grid[i][j]-=1; - } + if (grid[x][y]<=1) continue; + grid[x][y] -= 1; + grid[i][j] += 1; + dfs(cur+1, moves+abs(x-i)+abs(y-j), grid); + grid[x][y] += 1; + grid[i][j] -= 1; + } } }; From 9797b2b8a3bf6157942406c26d6131e0f0837fcd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 15:05:38 -0700 Subject: [PATCH 2122/2729] Update 2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp --- ....is-Array-a-Preorder-of-Some-Binary-Tree.cpp | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp index 50572036e..75e83b1bf 100644 --- a/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp +++ b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp @@ -3,17 +3,14 @@ class Solution { bool isPreorder(vector>& nodes) { stackstk; - for (auto& node: nodes) + stk.push(nodes[0][0]); + for (int i=1; i Date: Mon, 25 Sep 2023 00:05:43 -0700 Subject: [PATCH 2123/2729] Create 2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp --- ...-Relative-Loss-After-Buying-Chocolates.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp diff --git a/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp new file mode 100644 index 000000000..52195fcfa --- /dev/null +++ b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp @@ -0,0 +1,46 @@ +using LL = long long; +class Solution { + LL presum[100005]; +public: + vector minimumRelativeLosses(vector& prices, vector>& queries) + { + int n = prices.size(); + sort(prices.begin(), prices.end()); + + presum[0] = prices[0]; + for (int i=1; irets; + for (auto& arr: queries) + { + LL k = arr[0], m = arr[1]; + int left = 0, right = m; + while (left < right) + { + int mid = right - (right-left)/2; + if (mid==0 || mid==m) break; + if (prices[mid-1] < 2*k - prices[n-(m-mid)]) + left = mid; + else + right = mid-1; + } + int p = left; + LL ans1 = rangeSum(0, p-1) + 2*k*(m-p) - rangeSum(n-(m-p), n-1); + p++; + LL ans2 = rangeSum(0, p-1) + 2*k*(m-p) - rangeSum(n-(m-p), n-1); + rets.push_back(min(ans1, ans2)); + } + + return rets; + } + + LL rangeSum(int a, int b) + { + if (a>b) return 0LL; + if (a==0) + return presum[b]; + else + return presum[b]-presum[a-1]; + } +}; From 737f2be79338fb58cf14ce5b35b9de0391b6d9ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Sep 2023 00:06:18 -0700 Subject: [PATCH 2124/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 433b60071..c49f7ccf0 100644 --- a/Readme.md +++ b/Readme.md @@ -92,7 +92,8 @@ [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) -[2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) +[2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) +[2819.Minimum-Relative-Loss-After-Buying-Chocolates](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates) (H) * ``Binary Lifting`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) From 234f559ad534742f3501ad5a35c8a95cbf2092b2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Sep 2023 00:06:57 -0700 Subject: [PATCH 2125/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c49f7ccf0..0ffeddeec 100644 --- a/Readme.md +++ b/Readme.md @@ -98,6 +98,7 @@ [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) [2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree) (H) +[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From 161dfe088b83d2bcc1eab13ae1ab91c46f3d16d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Sep 2023 00:25:21 -0700 Subject: [PATCH 2126/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md diff --git a/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md new file mode 100644 index 000000000..6cb1703f3 --- /dev/null +++ b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md @@ -0,0 +1,5 @@ +### 2819.Minimum-Relative-Loss-After-Buying-Chocolates + +首先可以得出大致的策略,对于bob而言,要么选价格最便宜的(当价格pk时,代价函数是2k-p). 所以,选择的m件商品,必然在价格轴上一部分选在最左边,另一部分选在最右边。 + +假设我们选t件最便宜的,剩下m-t件是最贵的,那么该如何确定p的个数呢?我们希望选择商品的代价尽量远离峰值(p=k处),所以希望`price[t-1]`与`2k-price[n-(m-t)]`数值上尽量接近。否则因为t对两者影响的此消彼长,一方变低的话,另一方必然更高。所以我们尝试寻找最大的T,使得恰好`price[T-1] < 2k-price[n-(m-T)]`. 接下来,我们尝试T和T+1两个候选值,寻找两者之中能使总代价最优的解。总代价就是t件最便宜的代价`prices[0:t-1]`加上m-t件最贵的代价`2k*(m-t) - prices[n-(m-t): n-1]`. From 27ec45e86b8bc34ed20d1d6d2dcadafd170e3a8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Sep 2023 00:25:52 -0700 Subject: [PATCH 2127/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md index 6cb1703f3..0ff68f4ea 100644 --- a/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md +++ b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md @@ -2,4 +2,4 @@ 首先可以得出大致的策略,对于bob而言,要么选价格最便宜的(当价格pk时,代价函数是2k-p). 所以,选择的m件商品,必然在价格轴上一部分选在最左边,另一部分选在最右边。 -假设我们选t件最便宜的,剩下m-t件是最贵的,那么该如何确定p的个数呢?我们希望选择商品的代价尽量远离峰值(p=k处),所以希望`price[t-1]`与`2k-price[n-(m-t)]`数值上尽量接近。否则因为t对两者影响的此消彼长,一方变低的话,另一方必然更高。所以我们尝试寻找最大的T,使得恰好`price[T-1] < 2k-price[n-(m-T)]`. 接下来,我们尝试T和T+1两个候选值,寻找两者之中能使总代价最优的解。总代价就是t件最便宜的代价`prices[0:t-1]`加上m-t件最贵的代价`2k*(m-t) - prices[n-(m-t): n-1]`. +假设我们选t件最便宜的,剩下m-t件是最贵的,那么该如何确定t的个数呢?我们希望选择商品的代价尽量远离峰值(p=k处),所以希望`price[t-1]`与`2k-price[n-(m-t)]`数值上尽量接近。否则因为t对两者影响的此消彼长,一方变低的话,另一方必然更高。所以我们尝试寻找最大的T,使得恰好`price[T-1] < 2k-price[n-(m-T)]`. 接下来,我们尝试T和T+1两个候选值,寻找两者之中能使总代价最优的解。总代价就是t件最便宜的代价`prices[0:t-1]`加上m-t件最贵的代价`2k*(m-t) - prices[n-(m-t): n-1]`. From d5ebb9c71d12f1fe240208f9b7105dcf8e6e172c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Sep 2023 13:01:32 -0700 Subject: [PATCH 2128/2729] Update 1504.Count-Submatrices-With-All-Ones.cpp --- .../1504.Count-Submatrices-With-All-Ones.cpp | 46 ++++++++----------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp index 00c5f3f93..7146fa16d 100644 --- a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp @@ -2,36 +2,30 @@ class Solution { public: int numSubmat(vector>& mat) { - int M=mat.size(); - if (M==0) return 0; - int N=mat[0].size(); - int ret = 0; - for (int i=0; inums(n+1, 0); + int ret = 0; + for (int i=0; i(N,0); - for (int k=i; kstk; + stk.push(0); + int sum = 0; + for (int j=1; j<=n; j++) { - for (int j=0; j nums[j]) { - if (mat[k][j]==0) - q[j]=0; - else - q[j]=q[j]+1; + int p1 = stk.top(); + stk.pop(); + int p2 = stk.top(); + sum -= (p1-p2) * (nums[p1] - nums[j]); } - int h = k-i+1; - for (int a = 0; a Date: Sat, 30 Sep 2023 08:59:39 -0700 Subject: [PATCH 2129/2729] Update Readme.md --- .../1504.Count-Submatrices-With-All-Ones/Readme.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md b/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md index 708818d87..95f8c2de8 100644 --- a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md @@ -1,7 +1,15 @@ ### 1504.Count-Submatrices-With-All-Ones -此题的数据量非常小,o(MMN)即可解决。 +此题的数据量非常小,可以o(MMN)暴力解决。但是有更巧妙的o(MN)做法。 -和84、85相同的技巧,我们用两重循环遍历submatric的上边界和下边界(比如第i行和第k行,即高度是```h=k-i+1```),再横向扫一遍,得到这两个行边界之间的每一列的histogram(即以第k行为底,往上有多少个连续的1). 如果我们发现histogram数列里连续任意L列的高度都是h,那么说明就有```(1+L)*L/2```个高度为h的submatric其元素都是1(通过随意设置左端点和右端点). +和85相同的技巧,我们逐行处理,更新以第i行为底座的histogram。然后逐列处理histogram里面的柱子,我们试图用单调栈来判定:以第j根柱子为右边界的矩形有多少个。 -这样我们就不重不漏地遍历了所有不同高度位置、不同宽度位置的全1矩阵。 +我们想象,如果histogram里面的柱子都是递增的。假设以第j-1根柱子为右边界的矩形有count[j-1]个,并且第j根柱子比第j-1根的高,那么将这些count[j-1]个矩形向右延伸靠到第j根柱子上的话,都会变成有效的count[j]。此外,我们只需要再计数仅包括第j根柱子本身的矩形,故`count[j] = count[j-1] + nums[j]`. + +当我们如果遇到第j根柱子矮于第j-1根柱子呢?那么并不是所有count[j-1]个矩形都可以继承并延伸成为j的一部分。我们需要退回那些“超高”的部分,即高度差为`nums[j]-nums[j-1]`的这部分矩形我们要吐出去,剩余的矩形才能继承成为j的一部分。此外,我们发现,如果nums[j-2]也高于nums[j]的话,这样的回吐过程还要继续进行下去。 + +于是这一切都提示我们用单调栈。 + +使用单调栈时特别要注意,假设栈顶元素的index是p1,次栈顶元素的index是p2,p1与p2不一定连着的。这是因为之前p1将(p2,p1)之间的元素都逼出栈了。但这并不是说中间没有柱子了,而是意味着,(p2,p1)之间存在着与p1等高的柱子。所以p1退栈的时候,需要退出的矩形数目其实是`(p1-p2)*(nums[p1]-nums[j])`. + +退栈之后记得别忘了算上nums[j](也就是仅包含第j根柱子的矩形),并将j压入栈顶。 From e6e8c1400d5b78be35e27f3aaa33c6849fc68068 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 09:00:38 -0700 Subject: [PATCH 2130/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 0ffeddeec..d098a3093 100644 --- a/Readme.md +++ b/Readme.md @@ -402,13 +402,14 @@ [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) +[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) +[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1504.Count-Submatrices-With-All-Ones) (H) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) [2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) -[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) [1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) @@ -1229,7 +1230,6 @@ [1253.Reconstruct-a-2-Row-Binary-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1253.Reconstruct-a-2-Row-Binary-Matrix) (M) [1354.Construct-Target-Array-With-Multiple-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1354.Construct-Target-Array-With-Multiple-Sums) (H-) [1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K) (M+) -[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1504.Count-Submatrices-With-All-Ones) (M) [1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits) (H) [1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1535.Find-the-Winner-of-an-Array-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1535.Find-the-Winner-of-an-Array-Game) (M+) From 8b6a81aa24d792bb82fae91a9c3cfcf3ddb68768 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 11:19:20 -0700 Subject: [PATCH 2131/2729] Update 1504.Count-Submatrices-With-All-Ones.cpp --- .../1504.Count-Submatrices-With-All-Ones.cpp | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp index 7146fa16d..f4a7699bb 100644 --- a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp @@ -3,29 +3,33 @@ class Solution { int numSubmat(vector>& mat) { int m = mat.size(), n = mat[0].size(); - vectornums(n+1, 0); - int ret = 0; + vectorh(n+1, 0); + + int ret = 0; + for (int i=0; istk; - stk.push(0); - int sum = 0; + h[j+1] = (mat[i][j] == 1? (h[j+1]+1):0); + + stackstk; + stk.push(0); + int c = 0; for (int j=1; j<=n; j++) { - while (!stk.empty() && nums[stk.top()] > nums[j]) + while (!stk.empty() && h[stk.top()] > h[j]) { int p1 = stk.top(); stk.pop(); int p2 = stk.top(); - sum -= (p1-p2) * (nums[p1] - nums[j]); + c = c - (p1-p2)*(h[p1]-h[j]); } + c += h[j]; + ret += c; stk.push(j); - sum += nums[j]; - ret += sum; - } + } } + return ret; } }; From 6a8826a36ef368af825a5c8d53618b0121878e84 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:29:42 -0700 Subject: [PATCH 2132/2729] Rename Readme.md to Readme.md --- {Greedy => Stack}/1504.Count-Submatrices-With-All-Ones/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Stack}/1504.Count-Submatrices-With-All-Ones/Readme.md (100%) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md b/Stack/1504.Count-Submatrices-With-All-Ones/Readme.md similarity index 100% rename from Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md rename to Stack/1504.Count-Submatrices-With-All-Ones/Readme.md From a0fe8995af63e6304df3fe5329e3a94a563fcb4f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:30:26 -0700 Subject: [PATCH 2133/2729] Rename 1504.Count-Submatrices-With-All-Ones.cpp to 1504.Count-Submatrices-With-All-Ones.cpp --- .../1504.Count-Submatrices-With-All-Ones.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Stack}/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp (100%) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp b/Stack/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp similarity index 100% rename from Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp rename to Stack/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp From 8d1a856e5872b5b5cc77a70a0417d151296e3aab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:30:45 -0700 Subject: [PATCH 2134/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d098a3093..3f2ab22f4 100644 --- a/Readme.md +++ b/Readme.md @@ -403,7 +403,7 @@ [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) -[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1504.Count-Submatrices-With-All-Ones) (H) +[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1504.Count-Submatrices-With-All-Ones) (H) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) From 2f5b2a44a716d577a7de87dee6179dbc4c2977a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:34:38 -0700 Subject: [PATCH 2135/2729] Create 2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp --- ...Array-Into-Maximum-Number-of-Subarrays.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp diff --git a/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp b/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp new file mode 100644 index 000000000..bb271a326 --- /dev/null +++ b/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxSubarrays(vector& nums) + { + int n = nums.size(); + int ret = 0; + for (int i=0; i Date: Sat, 30 Sep 2023 16:35:08 -0700 Subject: [PATCH 2136/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3f2ab22f4..d525aafca 100644 --- a/Readme.md +++ b/Readme.md @@ -1273,6 +1273,7 @@ [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) +[2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) * Boyer-Moore Majority Voting [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) From 2140585640f3c26ba99129062f4a6d3787abca1a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:41:32 -0700 Subject: [PATCH 2137/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/Readme.md diff --git a/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/Readme.md b/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/Readme.md new file mode 100644 index 000000000..32f4eb212 --- /dev/null +++ b/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/Readme.md @@ -0,0 +1,7 @@ +### 2871.Split-Array-Into-Maximum-Number-of-Subarrays + + 先考察所有元素的“与和”。如果它不为零,那么我们就不分组,这样能保证“与和”最小,并且“组数”只有一个,必然总和最小。 + + 如果所有元素的“与和”恰为零(已然最小了),为了保证总和不变大,我们只能将任务变为拆分为若干个“与和”为0的subarray。我们贪心地从前往后尝试每个元素,一旦凑齐“与和”为0,即划分为一组即可。 + + From 7e1d7790a76cfb214d15b5a376ea1c824f6a6676 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 00:17:30 -0700 Subject: [PATCH 2138/2729] Create 2875.Minimum-Size-Subarray-in-Infinite-Array.cpp --- ...inimum-Size-Subarray-in-Infinite-Array.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp diff --git a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp new file mode 100644 index 000000000..bc50e7d8f --- /dev/null +++ b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { +public: + int minSizeSubarray(vector& nums, int target) + { + LL total = accumulate(nums.begin(), nums.end(), 0LL); + int n = nums.size(); + + for (int i=0; ipresum(2*n, 0); + presum[0] = nums[0]; + for (int i=1; i<2*n; i++) + presum[i] = presum[i-1] + nums[i]; + + LL ret = INT_MAX/2; + + unordered_mapMap; + Map[0] = -1; + + for (int i=0; i<2*n; i++) + { + LL r = ((target-presum[i])%total+total)%total; + if (r!=0) r = total - r; + + if (Map.find(r)!=Map.end()) + { + int p = Map[r]; + LL k = ((p==-1?0:presum[p]) - presum[i] + target) / total; + ret = min(ret, i-p+k*n); + } + + Map[presum[i]] = i; + } + + if (ret == INT_MAX/2) return -1; + else return ret; + } +}; From 08a512a3059bcadd3a050e6da64bdc6d83ccd44d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 00:18:02 -0700 Subject: [PATCH 2139/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d525aafca..9be2c5892 100644 --- a/Readme.md +++ b/Readme.md @@ -194,6 +194,7 @@ [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) [2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) [2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) +[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From 4f1f0c62927168f5ed385cf2d81cc6a1f65d57a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 00:36:19 -0700 Subject: [PATCH 2140/2729] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/Readme.md diff --git a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/Readme.md b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/Readme.md new file mode 100644 index 000000000..5ad313659 --- /dev/null +++ b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/Readme.md @@ -0,0 +1,12 @@ +### 2875.Minimum-Size-Subarray-in-Infinite-Array + +很显然,任何一个subarray,都可以表示成“nums的某个后缀 + 若干个重复的nums + nums的某个前缀”。 + +我们将nums重复一遍(长度变成2n)之后,上述的subarray sum就是:`nums[i:j] + k * total`. 其中total是nums[0:n-1]之和。[i:j]是在[0:2n-1]上的一个子区间。k是某个整数(可以是0). + +当我们遍历j的位置,考察某个j时,期望 `presum[j]-presum[i-1]+k*total = target`,转换一下就是`presum[i-1] = presum[j] - target + k*total`。显然,为了使这个式子有解,充要条件就是`presum[i-1]`和`presum[j] - target`关于total同余,并且需要i Date: Sun, 1 Oct 2023 00:36:41 -0700 Subject: [PATCH 2141/2729] Update 2875.Minimum-Size-Subarray-in-Infinite-Array.cpp --- .../2875.Minimum-Size-Subarray-in-Infinite-Array.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp index bc50e7d8f..97d61daf7 100644 --- a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp +++ b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp @@ -21,8 +21,7 @@ class Solution { for (int i=0; i<2*n; i++) { - LL r = ((target-presum[i])%total+total)%total; - if (r!=0) r = total - r; + LL r = ((presum[i] - target)%total+total)%total; if (Map.find(r)!=Map.end()) { From 9881bab509b35615d09963a256b3eb2b3d21d304 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 10:56:02 -0700 Subject: [PATCH 2142/2729] Update 2875.Minimum-Size-Subarray-in-Infinite-Array.cpp --- ...inimum-Size-Subarray-in-Infinite-Array.cpp | 35 +++++++++---------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp index 97d61daf7..e1f03e2e3 100644 --- a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp +++ b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp @@ -3,37 +3,36 @@ class Solution { public: int minSizeSubarray(vector& nums, int target) { - LL total = accumulate(nums.begin(), nums.end(), 0LL); + LL total = accumulate(nums.begin(), nums.end(), 0LL); + int n = nums.size(); - for (int i=0; ipresum(2*n, 0); presum[0] = nums[0]; for (int i=1; i<2*n; i++) - presum[i] = presum[i-1] + nums[i]; - + presum[i] = presum[i-1] + nums[i]; + LL ret = INT_MAX/2; - - unordered_mapMap; + + unordered_mapMap; // presum module, index Map[0] = -1; - for (int i=0; i<2*n; i++) - { - LL r = ((presum[i] - target)%total+total)%total; - + { + LL r = ((presum[i] - target) % total + total) % total; + if (Map.find(r)!=Map.end()) { - int p = Map[r]; - LL k = ((p==-1?0:presum[p]) - presum[i] + target) / total; - ret = min(ret, i-p+k*n); + int j = Map[r]; + LL k = ((j==-1? 0: presum[j]) - presum[i] + target) / total; + ret = min(ret, i-j+k*n); } - - Map[presum[i]] = i; + + Map[presum[i]%total] = i; } - + if (ret == INT_MAX/2) return -1; - else return ret; + else return ret; } }; From 4b500cdb43f8a9707d298fe5cd74029c92de756c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 15:40:11 -0700 Subject: [PATCH 2143/2729] Create 2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp --- ...ount-Visited-Nodes-in-a-Directed-Graph.cpp | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp diff --git a/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp b/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp new file mode 100644 index 000000000..9f2f5cfaa --- /dev/null +++ b/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp @@ -0,0 +1,75 @@ +class Solution { + int next[100005]; + int indegree[100005]; +public: + vector countVisitedNodes(vector& edges) + { + int n = edges.size(); + vectorrets(n); + + for (int i=0; iq; + for (int i=0; i&rets) + { + if (rets[cur]!=0) + return rets[cur]; + + rets[cur] = dfs(next[cur], rets) + 1; + return rets[cur]; + } +}; From 705c706b3327f5418b498afb147aa2e9f03ffb96 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 15:40:50 -0700 Subject: [PATCH 2144/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9be2c5892..485665845 100644 --- a/Readme.md +++ b/Readme.md @@ -1106,6 +1106,7 @@ [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) +[2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From 9dec0feb3604bca414b19b3f625db072c92f81fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 15:46:18 -0700 Subject: [PATCH 2145/2729] Create Readme.md --- .../2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md diff --git a/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md b/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md new file mode 100644 index 000000000..ed8ebc279 --- /dev/null +++ b/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md @@ -0,0 +1,7 @@ +### 2876.Count-Visited-Nodes-in-a-Directed-Graph + +对于任何有向图而言,顺着边的方向走向去,只有两种归宿:要么进入死胡同,要么进入循环圈。所以你可以把有向图简单地认为就是若干个单链并入一个环。 + +我们先找出入度为零的节点,然后用拓扑排序的方法将所有单链上的节点排除掉。剩下的就是环上的节点。从环的任意节点出发,可以遍历整个环得到环的长度(也就是对于这些节点的答案)。 + +最后再遍历单链节点,dfs直至遇到环的入口,这段距离加上环的长度,就是对于这些节点的答案。 From 5edceae851a20d06c7df787527721f161dd88c58 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 18:26:36 -0700 Subject: [PATCH 2146/2729] Update Readme.md --- Stack/962.Maximum-Width-Ramp/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Stack/962.Maximum-Width-Ramp/Readme.md b/Stack/962.Maximum-Width-Ramp/Readme.md index badfd8ada..35c823a92 100644 --- a/Stack/962.Maximum-Width-Ramp/Readme.md +++ b/Stack/962.Maximum-Width-Ramp/Readme.md @@ -20,5 +20,7 @@ ``` 绝妙的下一步是:从后往前依次考察A,对于每个A[i],我们从栈尾依次弹出元素直至遇到一个恰好小于等于A[i]的索引j,那么(j,i)就是关乎A[i]我们能得到的最宽的配对。至于那些已经弹出栈的元素,其实丢了就丢了,并不会对答案有更多的贡献。比如说,j+1和i-1即使配对成功,也不能超越(j,i)的宽度。这样将A从后往前扫一遍,就能找到最宽的配对。 +类似的题有 `2863. Maximum Length of Semi-Decreasing Subarrays` -[Leetcode Link](https://leetcode.com/problems/maximum-width-ramp) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/maximum-width-ramp) From db0688a214f11159c307a3dfc80c8d311dd2b239 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 18:28:02 -0700 Subject: [PATCH 2147/2729] Create 2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp --- ...Length-of-Semi-Decreasing-Subarrays_v1.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp new file mode 100644 index 000000000..ee0f45ecf --- /dev/null +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxSubarrayLength(vector& nums) + { + int n = nums.size(); + vector>arr; + int ret = 0; + for (int i=0; isecond; + ret = max(ret, i-k+1); + } + if (arr.empty() || nums[i]>arr.back().first) + arr.push_back({nums[i], i}); + } + return ret; + } +}; From 00fd8a5ff79fba768f0bf53d644d8b8ff543258a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 18:28:29 -0700 Subject: [PATCH 2148/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 485665845..834fefd1e 100644 --- a/Readme.md +++ b/Readme.md @@ -406,7 +406,8 @@ [2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) [1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1504.Count-Submatrices-With-All-Ones) (H) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) -[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) +[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) +[2863.Maximum-Length-of-Semi-Decreasing-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) From 62573c101380978d766ebba761374c63505e4fc9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 18:37:17 -0700 Subject: [PATCH 2149/2729] Create Readme.md --- .../Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md new file mode 100644 index 000000000..e7812958d --- /dev/null +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md @@ -0,0 +1,8 @@ +### 2863.Maximum-Length-of-Semi-Decreasing-Subarrays + +此题和 `962.Maximum-Width-Ramp` 一模一样。 + +#### 解法1 +我们维护一个递增的“数组”arr(注意不是单调栈)。对于新元素nums[i],我们用二分法在arr里找到第一个大于nums[i]的元素nums[j],于是对于i而言,它的最大跨度就是`i-j+1`. + +如果nums[i]大于数组的尾元素,就加入arr。反之,那么我们就再不用考虑i,这是因为它“又小又晚”,不会为后续的元素带来更大的跨度。 From 529d7769e05e5322888f4f27ec877fe5ffc03540 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 20:37:01 -0700 Subject: [PATCH 2150/2729] Create 2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp --- ...Length-of-Semi-Decreasing-Subarrays_v2.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp new file mode 100644 index 000000000..af933ae09 --- /dev/null +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int maxSubarrayLength(vector& nums) + { + int n = nums.size(); + stackstk; + for (int i=0; inums[stk.top()]) + stk.push(i); + } + + int ret = 0; + for (int i=n-1; i>=0; i--) + { + while (!stk.empty() && nums[stk.top()] > nums[i]) + { + ret = max(ret, i-stk.top()+1); + stk.pop(); + } + } + return ret; + } +}; From 6735654012863f1d7d1228d058284368a8be4a4b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 20:40:58 -0700 Subject: [PATCH 2151/2729] Update Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md index e7812958d..b96632e15 100644 --- a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md @@ -6,3 +6,16 @@ 我们维护一个递增的“数组”arr(注意不是单调栈)。对于新元素nums[i],我们用二分法在arr里找到第一个大于nums[i]的元素nums[j],于是对于i而言,它的最大跨度就是`i-j+1`. 如果nums[i]大于数组的尾元素,就加入arr。反之,那么我们就再不用考虑i,这是因为它“又小又晚”,不会为后续的元素带来更大的跨度。 + +#### 解法2 +我们先构造一个单调递增的栈,注意我们从不退栈。方法如下: +```cpp +for (int i=0; inums[stk.top()]) + stk.push(i); +} +``` +这样的做法是我们希望尽量收录更早且更高的元素。任何更晚出现的、更小的元素,都不可能成为最优配对(i,j)中的i。 + +然后我们从后往前遍历nums[i],我们持续退栈直至找到恰好比nums[i]大的元素j。退掉的元素不可惜,因为如果j与i是一个合法配对,那么任何大于j的元素都不会与小于i的元素组成更好的配对。 From fbc179c5d4f85dd1fb9b6d2f5d52222cce955614 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 20:41:53 -0700 Subject: [PATCH 2152/2729] Update Readme.md --- .../2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md index b96632e15..63ad38d50 100644 --- a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md @@ -3,7 +3,7 @@ 此题和 `962.Maximum-Width-Ramp` 一模一样。 #### 解法1 -我们维护一个递增的“数组”arr(注意不是单调栈)。对于新元素nums[i],我们用二分法在arr里找到第一个大于nums[i]的元素nums[j],于是对于i而言,它的最大跨度就是`i-j+1`. +我们维护一个递增的“数组”arr,这是为了方便二分。对于新元素nums[i],我们用二分法在arr里找到第一个大于nums[i]的元素nums[j],于是对于i而言,它的最大跨度就是`i-j+1`. 如果nums[i]大于数组的尾元素,就加入arr。反之,那么我们就再不用考虑i,这是因为它“又小又晚”,不会为后续的元素带来更大的跨度。 From e25dd2a8ed8a68bf4e9a85a3c5e56829b6b12152 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:28:45 -0700 Subject: [PATCH 2153/2729] Create 2539.Count-the-Number-of-Good-Subsequences.cpp --- ....Count-the-Number-of-Good-Subsequences.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Math/2539.Count-the-Number-of-Good-Subsequences/2539.Count-the-Number-of-Good-Subsequences.cpp diff --git a/Math/2539.Count-the-Number-of-Good-Subsequences/2539.Count-the-Number-of-Good-Subsequences.cpp b/Math/2539.Count-the-Number-of-Good-Subsequences/2539.Count-the-Number-of-Good-Subsequences.cpp new file mode 100644 index 000000000..05dbc519c --- /dev/null +++ b/Math/2539.Count-the-Number-of-Good-Subsequences/2539.Count-the-Number-of-Good-Subsequences.cpp @@ -0,0 +1,57 @@ +using LL = long long; +class Solution { + LL M = 1e9+7; + vector factorial; +public: + vector GetFactorial(LL N) + { + vectorrets(N+1); + rets[0] = 1; + for (int i=1; i<=N; i++) + rets[i] = rets[i-1] * i % M; + return rets; + } + + long long quickPow(long long x, long long N) { + if (N == 0) { + return 1; + } + LL y = quickPow(x, N / 2) % M; + return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); + } + + LL comb(LL m, LL n) + { + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % M; + LL inv_b = quickPow(b, (M-2)); + + return a * inv_b % M; + } + + int countGoodSubsequences(string s) + { + unordered_mapMap; + for (auto ch: s) + Map[ch] += 1; + + vectorcount; + for (auto [k,v]: Map) + count.push_back(v); + + int n = *max_element(count.begin(), count.end()); + + factorial = GetFactorial(n); + + LL ret = 0; + for (int f=1; f<=n; f++) + { + LL temp = 1; + for (int c: count) + temp = temp * (comb(c, f)+1) % M; + ret = (ret + temp -1) % M; + } + return ret; + } +}; From 31fab5eef2b95da3adc3274e4f14990686ab1e62 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:29:19 -0700 Subject: [PATCH 2154/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 834fefd1e..a341350d6 100644 --- a/Readme.md +++ b/Readme.md @@ -1193,7 +1193,8 @@ [1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony](https://github.com/wisdompeak/LeetCode/tree/master/Math/1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony) (H) [2221.Find-Triangular-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Math/2221.Find-Triangular-Sum-of-an-Array) (M) [2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps) (M+) -[2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) +[2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) +[2539.Count-the-Number-of-Good-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2539.Count-the-Number-of-Good-Subsequences) (H-) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From 5869add785a1f282659502f89dabb4dac13c9a88 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:33:15 -0700 Subject: [PATCH 2155/2729] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 43 ++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index 534f6b472..840df8caf 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -1,7 +1,7 @@ using LL = long long; main() { - // compute all C(n,m) saved in comb + // Version 1: compute all C(n,m) saved in comb long long comb[1000][1000]; for (int i = 0; i <= n; ++i) { @@ -14,7 +14,7 @@ main() } } -// Compute C(n,m) on demand +// Version 2: Compute C(n,m) on demand based on definition long long help(int n, int m) { long long cnt = 1; @@ -25,3 +25,42 @@ long long help(int n, int m) } return cnt; } + +// Version 3: Compute C(m,n) on demand with module M +using LL = long long; +LL M = 1e9+7; +vector factorial; + +vector GetFactorial(LL N) +{ + vectorrets(N+1); + rets[0] = 1; + for (int i=1; i<=N; i++) + rets[i] = rets[i-1] * i % M; + return rets; +} + +long long quickPow(long long x, long long N) { + if (N == 0) { + return 1; + } + LL y = quickPow(x, N / 2) % M; + return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); +} + +LL comb(LL m, LL n) +{ + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % M; + LL inv_b = quickPow(b, (M-2)); + + return a * inv_b % M; +} + +int ComputeComb(LL m, LL n) +{ + factorial = GetFactorial(n); + return comb(m, n); +} + From f4786cb57c7985f3a83760832972d703a9abad92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:33:40 -0700 Subject: [PATCH 2156/2729] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index 840df8caf..f0f0bf418 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -57,10 +57,3 @@ LL comb(LL m, LL n) return a * inv_b % M; } - -int ComputeComb(LL m, LL n) -{ - factorial = GetFactorial(n); - return comb(m, n); -} - From 0f8ea808744a36034e98477da2b84dc0b3cd3034 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:40:46 -0700 Subject: [PATCH 2157/2729] Create Readme.md --- .../Readme.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Math/2539.Count-the-Number-of-Good-Subsequences/Readme.md diff --git a/Math/2539.Count-the-Number-of-Good-Subsequences/Readme.md b/Math/2539.Count-the-Number-of-Good-Subsequences/Readme.md new file mode 100644 index 000000000..5b41d7238 --- /dev/null +++ b/Math/2539.Count-the-Number-of-Good-Subsequences/Readme.md @@ -0,0 +1,25 @@ +### 2539.Count-the-Number-of-Good-Subsequences + +我们遍历频次f从1到n(其中n是所有字母里最高的频次)。对于固定的频次f,我们考察26个字母中,每个字母取f个的组合数comb(c,f),以及不取的决策(即+1),这样就可以保证所取的子序列里每个字母的频次都一致。 +```cpp +for (int f=1; f<=n; f++) +{ + LL temp = 1; + for (int c: count) + temp = temp * (comb(c, f)+1) % M; + ret = (ret + temp -1) % M; +} +``` +注意,对于频次f,我们其实都包括了“全不取”的策略,这相当于空串是不合法的,所以对于每个temp我们都要减一。 + +关于计算组合数,应为要对M取模,我们可以直接用组合数定义和费马小定理来硬算,即 +```cpp +LL comb(LL m, LL n) +{ + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % M; + LL inv_b = quickPow(b, (M-2)); + return a * inv_b % M; +} +``` From 46e2b0b88d3507854d1eae4168f8d5ddf822b956 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 02:46:14 -0700 Subject: [PATCH 2158/2729] Create 2868.The-Wording-Game.cpp --- .../2868.The-Wording-Game.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Greedy/2868.The-Wording-Game/2868.The-Wording-Game.cpp diff --git a/Greedy/2868.The-Wording-Game/2868.The-Wording-Game.cpp b/Greedy/2868.The-Wording-Game/2868.The-Wording-Game.cpp new file mode 100644 index 000000000..ba81b73ce --- /dev/null +++ b/Greedy/2868.The-Wording-Game/2868.The-Wording-Game.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + bool canAliceWin(vector& a, vector& b) + { + int m = a.size(), n = b.size(); + int i = 0, j = 0; + + while (1) + { + while (j a[i][0]+1) + return true; + + while (i b[j][0]+1) + return false; + } + + return false; + } +}; From ae697aa7f99858f08487f353a7c4ae93d0c5ccb9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 02:46:49 -0700 Subject: [PATCH 2159/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a341350d6..2036cc09e 100644 --- a/Readme.md +++ b/Readme.md @@ -1278,6 +1278,7 @@ [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) [2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) +[2868.The-Wording-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2868.The-Wording-Game) (M) * Boyer-Moore Majority Voting [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) From ca1b4254d85a32010d7f479a4c2e9295981bc78e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 02:51:50 -0700 Subject: [PATCH 2160/2729] Create Readme.md --- Greedy/2868.The-Wording-Game/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2868.The-Wording-Game/Readme.md diff --git a/Greedy/2868.The-Wording-Game/Readme.md b/Greedy/2868.The-Wording-Game/Readme.md new file mode 100644 index 000000000..186f3fe66 --- /dev/null +++ b/Greedy/2868.The-Wording-Game/Readme.md @@ -0,0 +1,5 @@ +### 2868.The-Wording-Game + +本题看上去是很复杂的决策,但本质上就是简单的贪心。类似于打扑克,自己尽量出能恰好压过对手的牌,保留更大的牌后发制人,使得自己可以支撑更多的回合。 + +注意,本题里集合a与b之间都没有任何相同的字符串。这说明不必顾虑“对手出了某张牌导致自己有相同的牌无法打出”的情况。谁手里的牌大、牌多就是能赢的硬道理。 From 02e58ba1763d041605c268b7441d053ffb3f41b5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 13:32:51 -0700 Subject: [PATCH 2161/2729] Create 2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp --- ...y-Operations-to-Make-Two-Strings-Equal.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp new file mode 100644 index 000000000..2f9a8e6ff --- /dev/null +++ b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minOperations(string s1, string s2, int x) + { + int ret = 0; + + vectornums; + for (int i=0; i>dp(n+1, vector(n+1, INT_MAX/2)); + dp[0][0] = 0; + + for (int i=1; i<=n; i++) + for (int j=0; j<=1; j++) + { + if (i-2>=0) + dp[i][j] = min(dp[i][j], dp[i-2][j] + (nums[i]-nums[i-1])); + + if (j-1>=0 && j-1<=i-1) + dp[i][j] = min(dp[i][j], dp[i-1][j-1] + x); + + if (j+1<=i-1) + dp[i][j] = min(dp[i][j], dp[i-1][j+1]); + } + + + return dp[n][0]; + } +}; From 6c8be56a950aef63cab9481172e9101edd022ab5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 13:33:19 -0700 Subject: [PATCH 2162/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 2036cc09e..1ce06b79a 100644 --- a/Readme.md +++ b/Readme.md @@ -719,6 +719,7 @@ [2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) [2826.Sorting-Three-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2826.Sorting-Three-Groups) (M) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) +[2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From a82b55ed75ad6ca648a472c8568bb560b70339f1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 13:46:57 -0700 Subject: [PATCH 2163/2729] Create Readme.md --- .../Readme.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md new file mode 100644 index 000000000..35a77f888 --- /dev/null +++ b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md @@ -0,0 +1,28 @@ +### 2896.Apply-Operations-to-Make-Two-Strings-Equal + +注意到,如果从i开始的、将连续k对相邻的两个元素flip(每次代价为1),本质上就是将i和i+k距离k的两个元素flip,代价就是k。 + +所以,我们直接将s1和s2里面元素不同的index拿出来放在nums数组里。于是任务就是:每次在nums里挑两个(未访问过的)元素,代价是|nums[j]-nums[i]|或者x。问最少花多少代价能将nums全部访问。 + +对于这个问题,首先要明确并没有任何贪心的方法。每次如何挑选两个元素,并没有特定的规律,最优解会随着数据的不同有各种不同的表现。我们只能用DP或者搜索的方式来解。 + +### 解法1:o(n^3) +最容易想到的是一个o(N^3)的区间DP。我们想得到区间的最优解dp[i][j],只有两种拆解的方式: +1. 遍历一个中间的分界点k,我们先将[i:k]处理完,再将[k+1:j]处理完,那么dp[i][j]就是这两部分最优代价的和。 +2. 最后一个访问的pair是(i,j),所以dp[i][j] = dp[i+1][j-1] + cost(i,j). + +最终取最优的解作为dp[i][j]. 大致的代价如下 +```cpp +for (int d = 1; d<=n; d++) { + for (int i=0; i+d-1 Date: Sun, 8 Oct 2023 15:38:48 -0700 Subject: [PATCH 2164/2729] Update Readme.md --- .../Readme.md | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md index 35a77f888..72e39e00a 100644 --- a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md +++ b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md @@ -1,10 +1,12 @@ ### 2896.Apply-Operations-to-Make-Two-Strings-Equal -注意到,如果从i开始的、将连续k对相邻的两个元素flip(每次代价为1),本质上就是将i和i+k距离k的两个元素flip,代价就是k。 +注意到,如果从i开始的、连续操作k次相邻元素的flip(每次代价为1),本质上就是将i和i+k距离k的两个元素flip,其他元素保持不变,代价就是k。 -所以,我们直接将s1和s2里面元素不同的index拿出来放在nums数组里。于是任务就是:每次在nums里挑两个(未访问过的)元素,代价是|nums[j]-nums[i]|或者x。问最少花多少代价能将nums全部访问。 +所以,我们直接将s1和s2里面元素不同的index拿出来放在nums数组里。于是任务就是:每次在nums里挑两个(未访问过的)元素i与j,代价是nums[j]-nums[i],或者x。问最少花多少代价能将nums全部访问。当然,nums的元素个数必须是偶数,否则无解。 -对于这个问题,首先要明确并没有任何贪心的方法。每次如何挑选两个元素,并没有特定的规律,最优解会随着数据的不同有各种不同的表现。我们只能用DP或者搜索的方式来解。 +我们特别注意到,对于第一种操作,只会发生在nums里的两个相邻元素之间。为什么呢?假设有4个元素`p,...,k,j,i`,其中`k,j,i`是相邻的。如果我们将k与i按照第一种操作配对,代价是nums[i]-nums[k];而将j与[k,i]之外的某个p配对,代价是c(p,j)。我们发现,`nums[i]-nums[k] >= nums[i]-nums[j]`,且`cost(p,j) >= cost(p,k)`,所以有`nums[i]-nums[k]+cost(p,j) >= nums[i]-nums[j]+ cost(p,k)`,也就是说不如将“i与j配对,k与p配对”来的更优。 + +接下来思考整个问题。首先要明确并没有任何贪心的方法。每次如何挑选两个元素,并没有特定的规律,最优解会随着数据的不同有各种不同的表现。我们只能用DP或者搜索的方式来解。 ### 解法1:o(n^3) 最容易想到的是一个o(N^3)的区间DP。我们想得到区间的最优解dp[i][j],只有两种拆解的方式: @@ -26,3 +28,20 @@ return dp[0][n-1]; ``` ### 解法2:o(n^2) +对于每个元素nums[i],它被访问的配对无非这么几种情况: +1. 与前一个相邻的元素配对,代价是nums[i]-nums[i-1]。前面已经证明过使用操作1的话,只能是与相邻元素配对。 +2. 与之前某一个未配对的元素配对,代价是x,但是这个x算在了之前的那个元素上。 +3. 与之后某一个未配对的元素配对,代价是x,并算在nums[i]上。 + +于是我们设计dp[i][j]表示:前i个元素里,我们留了j个操作未配对元素(但是已经计入了代价x),此时的最小总代价。分别对应三种策略是: +1. dp[i][j] = dp[i-2][j] + (nums[i]-nums[i-1]); +2. dp[i][j] = dp[i-1][j+1]; +3. dp[i][j] = dp[i-1][j-1] + x; + +三种策略里取最优的dp[i][j]。两层循环结束后,最终返回的是dp[n-1][0]. + +### 解法3:o(n) +上面的解法里第一层循环是o(N),第二层循环也是o(N).但事实上,关于“未配对元素”的个数,我们只需要考虑0或者1即可。 + +考虑nums序列如```k O O O j O O i```,其中k与j表示两个未配对的元素。如果尝试i与j配对,那么k只能与i之后的某个元素x配对。这个方案肯定不如“k与j配对、i与x配对”。同理,尝试i与k配对,那么j只能与i之后的某个元素x配对。这个方案也肯定不如“k与j配对、i与x配对”。所以在序列的遍历过程中,存留有两个或者两个以上未配对的方案肯定不是最优的。所以dp[i][j]的第二个下标只需要考察0和1即可。 + From 516970cf7b40fde0a315814f995778b7f9096a2f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 15:46:14 -0700 Subject: [PATCH 2165/2729] Create 2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp --- ...ns-on-Array-to-Maximize-Sum-of-Squares.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp diff --git a/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp new file mode 100644 index 000000000..6be5f52c0 --- /dev/null +++ b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp @@ -0,0 +1,38 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int maxSum(vector& nums, int k) + { + vectorcount(32); + + for (int x: nums) + { + for (int i=0; i<32; i++) + { + if ((x>>i)&1) + count[i] += 1; + } + } + + LL ret = 0; + + for (int t=0; t=0; i--) + { + if (count[i]>0) + { + x += (1LL< Date: Sun, 8 Oct 2023 15:46:59 -0700 Subject: [PATCH 2166/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1ce06b79a..c2ced654e 100644 --- a/Readme.md +++ b/Readme.md @@ -1280,7 +1280,8 @@ [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) [2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) [2868.The-Wording-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2868.The-Wording-Game) (M) -* Boyer-Moore Majority Voting +[2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) +* ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) * ``Lexicographical Sequence`` From ffc70e06a6a35bcaa1d1b95da8ade6e3099867ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 16:02:08 -0700 Subject: [PATCH 2167/2729] Create Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md diff --git a/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md new file mode 100644 index 000000000..779b6f34c --- /dev/null +++ b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md @@ -0,0 +1,18 @@ +### 2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares + +我们遍历一下bit位的操作后果: +``` +X Y AND OR +1, 1 => 1 1 +1, 0 => 0 1 +0, 1 => 0 1 +0, 0 => 0 0 +``` +我们发现OR的效果其实是在每个bit位上“收集”1,而AND的效果其实就是“送出”1. 一进一出,不难发现`X+Y= AND+OR`。也就是说每次操作X和Y的一对数,我们在“零和”的前提下,拉大了“贫富差距”。这是我们想要的吗?是的,因为这能增大平方和。简单的证明,当`x>=y`且`d>0`时 +``` +(x+d)^2 + (y-d)^2 = x^2 + y^2 + 2d*(x-y) + 2d^2 > x^2 + y^2 +``` + +因为可以无限次操作,所以不断通过OR来“吸取”其他元素里各bit位上的1,构造出尽量大的元素。 + +代码中,我们统计每个bit上,nums里总共提供多少个1. 构造大数时,只需从最高位到最低位尽量填充1即可,如果没有库存了,就填充0. 最终取前k个大数,算一下平方和即可。 From ce52bdb1c2ffe620e7249512b233366abfc31781 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 16:03:37 -0700 Subject: [PATCH 2168/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md index 779b6f34c..035f0667e 100644 --- a/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md +++ b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md @@ -13,6 +13,6 @@ X Y AND OR (x+d)^2 + (y-d)^2 = x^2 + y^2 + 2d*(x-y) + 2d^2 > x^2 + y^2 ``` -因为可以无限次操作,所以不断通过OR来“吸取”其他元素里各bit位上的1,构造出尽量大的元素。 +因为可以无限次操作,所以可以任意从某个元素出发,通过不断OR来“吸取”其他元素里各bit位上的1,直至构造出尽量大的元素。 代码中,我们统计每个bit上,nums里总共提供多少个1. 构造大数时,只需从最高位到最低位尽量填充1即可,如果没有库存了,就填充0. 最终取前k个大数,算一下平方和即可。 From dac68a0f74a1c40b3e28d2a1cfa55fd1c795b7dc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 17:55:06 -0700 Subject: [PATCH 2169/2729] Create 2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp --- ...perations-to-Make-Two-Strings-Equal_v1.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp new file mode 100644 index 000000000..0829893d3 --- /dev/null +++ b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minOperations(string s1, string s2, int x) + { + int ret = 0; + + vectornums; + for (int i=0; i>dp(n, vector(n, INT_MAX/2)); + for (int i=0; i+1 Date: Sun, 8 Oct 2023 17:55:18 -0700 Subject: [PATCH 2170/2729] Rename 2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp to 2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp --- ...cpp => 2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/{2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp => 2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp} (100%) diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp similarity index 100% rename from Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp rename to Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp From 3729eec8513736a268270a0313198964eb59534d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 13 Oct 2023 23:08:41 -0700 Subject: [PATCH 2171/2729] Update 1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp --- .../1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp b/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp index ccced7347..dcb7dc116 100644 --- a/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp +++ b/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp @@ -3,7 +3,7 @@ class Solution { int minDays(vector& bloomDay, int m, int k) { int n = bloomDay.size(); - if (n Date: Fri, 13 Oct 2023 23:57:46 -0700 Subject: [PATCH 2172/2729] Create 2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp --- ...s-That-Can-Form-a-Palindrome-in-a-Tree.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp diff --git a/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp b/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp new file mode 100644 index 000000000..a134b04d7 --- /dev/null +++ b/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp @@ -0,0 +1,41 @@ +using LL = long long; +class Solution { + vector>next[100005]; + unordered_mapcount; + LL ret = 0; +public: + long long countPalindromePaths(vector& parent, string s) + { + int n = parent.size(); + for (int i=1; i Date: Fri, 13 Oct 2023 23:58:36 -0700 Subject: [PATCH 2173/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c2ced654e..a5a29792a 100644 --- a/Readme.md +++ b/Readme.md @@ -1108,6 +1108,7 @@ [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) +[2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) From 66afe448ff1b4907ff6382e720164ff45e9aff48 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 Oct 2023 00:28:21 -0700 Subject: [PATCH 2174/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/Readme.md diff --git a/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/Readme.md b/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/Readme.md new file mode 100644 index 000000000..d4bcda79c --- /dev/null +++ b/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/Readme.md @@ -0,0 +1,13 @@ +### 2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree + +首先注意题意,路径上的字符可以"rearranged"。并不是说路径本身是回文串。 + +对于回文串,我们不关心每个字符出现的具体频次,而是只关心频次的奇偶性。所以任何路径其实可以用一个长度为26位的01串编码来表示,通过这个01串我们就可以判断是否是回文(奇数频次的字符不能超过1个)。 + +接下来考虑我们如何能遍历任意两点之间的路径的编码呢?一种常见的遍历方法是对于任意一个节点,想象它是路径的拐点,在它的子节点里寻找路径的左半部分和右半部分。但是这个想法在这里行不通,我们无法穷举所有子节点的01串。 + +本题的关键点在于,任意两点u,v之间路径的01串编码,等于u到根节点r的01串编码,再加上v到根节点r的01串编码。中间会有一段重复两遍(即uv的LCA和Root这段),但是算上它们并不影响u,v之间路径编码里每一位的奇偶性。所以我们其实只需要记录所有节点到根节点的路径的01编码即可。 + +本题的具体做法只需要简单的DFS。对于任何u到r的01编码state,我们用hash表查找是否已经存在其他节点v到r的01编码state2: +1. 如果`state2==state`,那么uv的路径上就所有的字符频次都是偶数,是回文串。 +2. 如果`state2`和`state`只差别1个bit,那么uv的路径上就有一个字符的频次是奇数,也是回文串。 From 915b695b49e9d422f5973f7b7bfae1552f695249 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Oct 2023 00:24:27 -0700 Subject: [PATCH 2175/2729] Create 2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp --- ...ount-of-Sub-Multisets-With-Bounded-Sum.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp diff --git a/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp b/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp new file mode 100644 index 000000000..2f1891962 --- /dev/null +++ b/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp @@ -0,0 +1,50 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + vector>arr; + int count0 = 0; +public: + int countSubMultisets(vector& nums, int l, int r) + { + unordered_mapMap; + for (int x: nums) + { + if (x==0) count0++; + else Map[x]++; + } + + for (auto& p:Map) + arr.push_back(p); + + arr.insert(arr.begin(), {0,0}); + + return (helper(r) - helper(l-1) + M) % M; + } + + int helper(int limit) + { + if (limit<0) return 0; + + int n = arr.size() - 1; + + vector>dp(n+1, vector(limit+1, 0)); + + dp[0][0] = 1; + + for (int i=1; i<=n; i++) + { + auto [v, c] = arr[i]; + for (int j=0; j<=limit; j++) + { + dp[i][j] = (j Date: Sun, 15 Oct 2023 00:25:36 -0700 Subject: [PATCH 2176/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a5a29792a..e1474610c 100644 --- a/Readme.md +++ b/Readme.md @@ -804,6 +804,7 @@ [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) [2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) +[2902.Count-of-Sub-Multisets-With-Bounded-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From 64f8dd4c923bb38c69c746605378911f60bb5d09 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Oct 2023 21:14:05 -0700 Subject: [PATCH 2177/2729] Update 2604.Minimum-Time-to-Eat-All-Grains.cpp --- .../2604.Minimum-Time-to-Eat-All-Grains.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp index d7dbce343..5e1cfd2bf 100644 --- a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp +++ b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp @@ -5,7 +5,7 @@ class Solution { sort(hens.begin(), hens.end()); sort(grains.begin(), grains.end()); - int left = 0, right = INT_MAX/2; + int left = 0, right = INT_MAX; while (left < right) { int mid = left + (right-left)/2; From ba23c29e0ca7867b4d6982878c9779d4eac2e1e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Oct 2023 21:18:07 -0700 Subject: [PATCH 2178/2729] Update 2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp --- ...2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp b/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp index ce7a78ee7..b210ebc83 100644 --- a/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp +++ b/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp @@ -3,6 +3,7 @@ class Solution { public: int maxCount(vector& banned, int n, long long maxSum) { + banned.erase(std::unique(banned.begin(), banned.end()),banned.end()); sort(banned.begin(), banned.end()); presum.resize(banned.size()); From 7b9459b0ecf4de647324c8d5a4eb9781aa48daba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Oct 2023 23:39:10 -0700 Subject: [PATCH 2179/2729] Create Readme.md --- .../Readme.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/Readme.md diff --git a/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/Readme.md b/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/Readme.md new file mode 100644 index 000000000..4626c46bc --- /dev/null +++ b/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/Readme.md @@ -0,0 +1,26 @@ +### 2902.Count-of-Sub-Multisets-With-Bounded-Sum + +本题常规的思路是解一个01背包问题。有n个元素可以选,每个元素有一定的容量vi,求不超过一定总容量C的选择方法有多少种。常规的01背包问题的时间复杂度是o(NC),其中N是元素个数,C是总容量。很明显在这里是会TLE的。 + +如何降低复杂度呢。有一个巧妙的技巧。考虑到n个元素里可能有重复的,如果只考虑互不相同的元素,那么元素的个数m必然是sqrt(C)的数量级(因为`1+2+3+...+m = C`)。于是问题转化为:有m种不同元素,每种元素有一定的容量vi和数量ai,求不超过一定总容量C的选择方法有多少种。 + +我们令dp[i][j]表示前i种元素填装容量j时的方案数目。那么状态转移的关键就是第i种元素我们取几个。可以是0个,1个,2个,直至ai个。于是就有转移方程: +```cpp +dp[i][j] = dp[i-1][j] + dp[i-1][j-vi] + dp[i-1][j-vi*2] + ... + dp[i-1][j-vi*ai] +``` +这个转移方程包括了一个循环,再加上外层两个关于i与j的循环,时间复杂度依然超标。技巧如下。我们分析 +```cpp +dp[i][j-vi] = dp[i-1][j-vi] + dp[i-1][j-vi*2] + dp[i-1][j-vi*3] + ... + dp[i-1][j-vi*(ai+1)] +``` +两式相减 +```cpp +dp[i][j] = dp[i][j-vi] + dp[i-1][j] - dp[i-1][j-vi*(ai+1)] +``` +我们发现dp[i][j]本身的计算并不需要依赖循环!于是本题的dp解法只需要两层循环即可。注意,以上的表达式里要保证数组下标不是负数,即 +```cpp +dp[i][j] = (j Date: Tue, 31 Oct 2023 22:05:34 -0700 Subject: [PATCH 2180/2729] Create 2898.Maximum-Linear-Stock-Score.cpp --- .../2898.Maximum-Linear-Stock-Score.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Others/2898.Maximum-Linear-Stock-Score/2898.Maximum-Linear-Stock-Score.cpp diff --git a/Others/2898.Maximum-Linear-Stock-Score/2898.Maximum-Linear-Stock-Score.cpp b/Others/2898.Maximum-Linear-Stock-Score/2898.Maximum-Linear-Stock-Score.cpp new file mode 100644 index 000000000..658f6d1a3 --- /dev/null +++ b/Others/2898.Maximum-Linear-Stock-Score/2898.Maximum-Linear-Stock-Score.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + long long maxScore(vector& prices) + { + int n = prices.size(); + vectorarr(n); + for (int i=0; iMap; + for (int i=0; i Date: Tue, 31 Oct 2023 22:12:14 -0700 Subject: [PATCH 2181/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e1474610c..8f096ee13 100644 --- a/Readme.md +++ b/Readme.md @@ -1084,9 +1084,9 @@ [1563.Stone-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1563.Stone-Game-V) (H-) [2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) * ``Digit counting & finding`` -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) -[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) +[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) From f26feb362aa62d6e3efce03c4d857fed429c95b3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 Oct 2023 22:15:40 -0700 Subject: [PATCH 2182/2729] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index 8f096ee13..523b3d932 100644 --- a/Readme.md +++ b/Readme.md @@ -1084,7 +1084,7 @@ [1563.Stone-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1563.Stone-Game-V) (H-) [2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) * ``Digit counting & finding`` -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) @@ -1453,6 +1453,8 @@ [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) +* ``公式变形`` +[2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) @@ -1533,11 +1535,10 @@ [347.Top-K-Frequent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/347.Top-K-Frequent-Elements) (M+) [973.K-Closest-Points-to-Origin](https://github.com/wisdompeak/LeetCode/tree/master/Others/973.K-Closest-Points-to-Origin) (M) [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) -* ``数位计算`` +* ``Digit counting`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) -[1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) #### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   From b75e15670c7910a1dee194bd1df5ac27bad9dc7e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 Oct 2023 22:16:00 -0700 Subject: [PATCH 2183/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 523b3d932..d7353df39 100644 --- a/Readme.md +++ b/Readme.md @@ -1453,7 +1453,7 @@ [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) -* ``公式变形`` +* ``公式变形`` [2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) From 7f7fd25df9a9dfeeef8f64accca6456fc318e49d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 Oct 2023 22:20:18 -0700 Subject: [PATCH 2184/2729] Create Readme.md --- Others/2898.Maximum-Linear-Stock-Score/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2898.Maximum-Linear-Stock-Score/Readme.md diff --git a/Others/2898.Maximum-Linear-Stock-Score/Readme.md b/Others/2898.Maximum-Linear-Stock-Score/Readme.md new file mode 100644 index 000000000..6a0c85f38 --- /dev/null +++ b/Others/2898.Maximum-Linear-Stock-Score/Readme.md @@ -0,0 +1,5 @@ +### 2898.Maximum-Linear-Stock-Score + +将`prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]` 变形一下就是`prices[indexes[j]] - indexes[j] == prices[indexes[j - 1]] - indexes[j - 1]`。所以本题就是要找一组索引i,使得`prices[i]-(i+1)`相等。 + +所以我们用Hash将所有`prices[i]-(i+1)`相同的元素prices[i]都汇聚起来算sum,取最大的一个。 From b1513fa6c71b5eee53bef04ab7d3644f8a7e72e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 Oct 2023 22:21:40 -0700 Subject: [PATCH 2185/2729] Update Readme.md --- Others/2898.Maximum-Linear-Stock-Score/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2898.Maximum-Linear-Stock-Score/Readme.md b/Others/2898.Maximum-Linear-Stock-Score/Readme.md index 6a0c85f38..a452b1e13 100644 --- a/Others/2898.Maximum-Linear-Stock-Score/Readme.md +++ b/Others/2898.Maximum-Linear-Stock-Score/Readme.md @@ -1,5 +1,5 @@ ### 2898.Maximum-Linear-Stock-Score -将`prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]` 变形一下就是`prices[indexes[j]] - indexes[j] == prices[indexes[j - 1]] - indexes[j - 1]`。所以本题就是要找一组索引i,使得`prices[i]-(i+1)`相等。 +将`prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]` 变形一下就是`prices[indexes[j]] - indexes[j] == prices[indexes[j - 1]] - indexes[j - 1]`。所以本题要找的indexes,就是一组prices的索引`i`,使得它们的`prices[i]-(i+1)`彼此相等。 所以我们用Hash将所有`prices[i]-(i+1)`相同的元素prices[i]都汇聚起来算sum,取最大的一个。 From a2cd400441cb045950703109160ba767d5ba7260 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 14:48:46 -0800 Subject: [PATCH 2186/2729] Create 2926.Maximum-Balanced-Subsequence-Sum.cpp --- .../2926.Maximum-Balanced-Subsequence-Sum.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp b/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp new file mode 100644 index 000000000..c7c54d59f --- /dev/null +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp @@ -0,0 +1,42 @@ +using LL = long long; +class Solution { +public: + long long maxBalancedSubsequenceSum(vector& nums) + { + int n = nums.size(); + vectorarr(n); + for (int i=0; idp; + LL ret = LLONG_MIN; + + for (int i=0; isecond + nums[i]); + } + else + { + dp[x] = nums[i]; + } + + ret = max(ret, dp[x]); + + iter = dp.find(x); + iter = next(iter); + while (iter!=dp.end() && iter->second <= dp[x]) + { + int y = iter->first; + iter = next(iter); + dp.erase(y); + } + } + + return ret; + } +}; From a1f267c15828bf40e7d5bb698f9b8ec328e1a29a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 14:49:43 -0800 Subject: [PATCH 2187/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d7353df39..2d0e6dbaf 100644 --- a/Readme.md +++ b/Readme.md @@ -221,6 +221,7 @@ [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2736.Maximum-Sum-Queries) (H) +[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) From 5814746ce3c0c6ad7b749c386137a74c77fda24b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 15:01:53 -0800 Subject: [PATCH 2188/2729] Update 2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp --- ...-Original-String-Exists-Given-Two-Encoded-Strings.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp b/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp index e30c6a741..7fadb1251 100644 --- a/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp +++ b/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp @@ -78,9 +78,12 @@ class Solution { return dfs(t1, i+1, 0, t2, j, num2-1); } else - { - visited.insert(hash); - if (t1[i]!=t2[j]) return false; + { + if (t1[i]!=t2[j]) + { + visited.insert(hash); + return false; + } return dfs(t1, i+1, 0, t2, j+1, 0); } } From bd7420af1fba16115e6a4a99d7247ce8680b1ad1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 15:31:20 -0800 Subject: [PATCH 2189/2729] Create Readme. md --- .../Readme. md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md new file mode 100644 index 000000000..dd4e16840 --- /dev/null +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md @@ -0,0 +1,31 @@ +### 2926.Maximum-Balanced-Subsequence-Sum + +很明显,变形一下式子就有```nums[i_j] - i_j >= nums[i_(j-1)] - i_(j-1)```. 我们令新数组`arr[i] = nums[i]-i`,我们就是想要在arr里面找一个递增的subsequence,记做{k},使得这个subsequence对应的 {nums[k]} 的和能够最大。 + +很容易看出可以用o(N^2)的dp来做。令dp[i]表示以i为结尾的递增subsequence的最大nums之和。那么就有 +``` +for (int i=0; i=B,那么对于任何一个新元素arr[i]=x,我们如果可以把x接在b后面构造子序列,那么显然不如我们把x接在a后面构成子序列更优。这样我们就可以把b从dp里弹出去。 + +所以我们将dp按照key和value都递增的顺序排列后,一个最大的好处出现了。对于任何一个新元素arr[i]=x,我们不需要在dp里遍历所有key小于x的元素,只需要知道恰好小于等于x的key(假设是y),那么就有`dp[x]=dp[y]+nums[i]`。任何key比y小的元素,虽然都可以接上x,但是它们的value并没有dp[y]有优势。 + +当我们确定dp[x]的最优值之后,再将x插入dp里面。记得此时要向后依次检查比x大的那些key,看它们的value(也就是dp值)是否小于dp[x],是的话就将他们弹出去。 + +时间复杂度:对于任何的arr[i]=x,我们在dp里面按照key二分查询恰好小于等于x的key,是log(n)。所以总的时间复杂度是o(NlogN). 有人会问,似乎每个回合,都有线性弹出的操作,但其实总共你最多只会弹出N个元素,这个弹出操作的总是也只是o(N),与循环无关。 + + From 703bab5305bae596e7154796a30779aa6977e4a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 15:31:47 -0800 Subject: [PATCH 2190/2729] Update and rename Readme. md to Readme.md --- .../{Readme. md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Heap/2926.Maximum-Balanced-Subsequence-Sum/{Readme. md => Readme.md} (100%) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md similarity index 100% rename from Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md rename to Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md From 051029a8e7a04435ee81d515707c1ec9f2e84b22 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 15:32:02 -0800 Subject: [PATCH 2191/2729] Update Readme.md --- Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md index dd4e16840..96157e53c 100644 --- a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md @@ -3,14 +3,14 @@ 很明显,变形一下式子就有```nums[i_j] - i_j >= nums[i_(j-1)] - i_(j-1)```. 我们令新数组`arr[i] = nums[i]-i`,我们就是想要在arr里面找一个递增的subsequence,记做{k},使得这个subsequence对应的 {nums[k]} 的和能够最大。 很容易看出可以用o(N^2)的dp来做。令dp[i]表示以i为结尾的递增subsequence的最大nums之和。那么就有 -``` +```cpp for (int i=0; i Date: Sun, 5 Nov 2023 22:27:24 -0800 Subject: [PATCH 2192/2729] Update Readme.md --- Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md index 96157e53c..da22acae9 100644 --- a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md @@ -14,7 +14,7 @@ for (int i=0; i Date: Sun, 5 Nov 2023 22:29:32 -0800 Subject: [PATCH 2193/2729] Update Readme.md --- Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md index da22acae9..d8ad9e38f 100644 --- a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md @@ -20,7 +20,7 @@ for (int i=0; i=B,那么对于任何一个新元素arr[i]=x,我们如果可以把x接在b后面构造子序列,那么显然不如我们把x接在a后面构成子序列更优。这样我们就可以把b从dp里弹出去。 +我们知道,dp本质是一个map,是按照key的大小排列的有序容器(其中key就是arr的值)。但是我们还可以给它加一个属性:让其value也保持递增。这个哲学思想就是,对于dp里存在 dp[a]=A, dp[b]=B,且a=B,那么对于任何一个新元素arr[i]=x,我们如果可以把x接在b后面构造子序列,那么显然不如我们把x接在a后面构成子序列更优。这样我们就可以把b从dp里弹出去。 所以我们将dp按照key和value都递增的顺序排列后,一个最大的好处出现了。对于任何一个新元素arr[i]=x,我们不需要在dp里遍历所有key小于x的元素,只需要知道恰好小于等于x的key(假设是y),那么就有`dp[x]=dp[y]+nums[i]`。任何key比y小的元素,虽然都可以接上x,但是它们的value并没有dp[y]有优势。 From 52b4dfe26af25760713bd18d9e2b5a97bfb24435 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 23:12:33 -0800 Subject: [PATCH 2194/2729] Update 2926.Maximum-Balanced-Subsequence-Sum.cpp --- .../2926.Maximum-Balanced-Subsequence-Sum.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp b/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp index c7c54d59f..ca6589165 100644 --- a/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp @@ -30,11 +30,7 @@ class Solution { iter = dp.find(x); iter = next(iter); while (iter!=dp.end() && iter->second <= dp[x]) - { - int y = iter->first; - iter = next(iter); - dp.erase(y); - } + iter = dp.erase(iter); } return ret; From bcb54790681f96645931ddd1940b7fd4bb0d8467 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 23:35:10 -0800 Subject: [PATCH 2195/2729] Create 2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp --- ...re-After-Applying-Operations-on-a-Tree.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp diff --git a/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp b/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp new file mode 100644 index 000000000..39a7c0038 --- /dev/null +++ b/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp @@ -0,0 +1,51 @@ +using LL = long long; +class Solution { + vectornext[20005]; + LL subtree[20005]; + vectorvalues; +public: + long long maximumScoreAfterOperations(vector>& edges, vector& values) + { + this->values = values; + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + + dfs0(0, -1); + return dfs(0, -1); + + } + + LL dfs0(int cur, int parent) + { + LL sum = values[cur]; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + sum += dfs0(nxt, cur); + } + subtree[cur] = sum; + return sum; + } + + + LL dfs(int cur, int parent) + { + if (next[cur].size()==1 && cur!=0) + { + return 0; + } + + LL sum = values[cur]; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + sum += dfs(nxt, cur); + } + + return max(sum, subtree[cur]-values[cur]); + } +}; From 1edc5df4cf9579c7066826bb5e0f08c69815b7bf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 23:39:39 -0800 Subject: [PATCH 2196/2729] Update Readme.md --- Readme.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Readme.md b/Readme.md index 2d0e6dbaf..95ef61d7b 100644 --- a/Readme.md +++ b/Readme.md @@ -266,12 +266,15 @@ [1666.Change-the-Root-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1666.Change-the-Root-of-a-Binary-Tree) (H-) [1932.Merge-BSTs-to-Create-Single-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1932.Merge-BSTs-to-Create-Single-BST) (H) [2003.Smallest-Missing-Genetic-Value-in-Each-Subtree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2003.Smallest-Missing-Genetic-Value-in-Each-Subtree) (H) -[2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H-) -[2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) +[2445.Number-of-Nodes-With-Value-One](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2445.Number-of-Nodes-With-Value-One) (M+) +* ``Regular DFS`` [2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) -[2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) +[2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H-) +[2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) [2467.Most-Profitable-Path-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2467.Most-Profitable-Path-in-a-Tree) (M+) -[2445.Number-of-Nodes-With-Value-One](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2445.Number-of-Nodes-With-Value-One) (M+) +[2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) +[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) +[2925.Maximum-Score-After-Applying-Operations-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree) (M) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) @@ -1054,7 +1057,6 @@ [133.Clone-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/133.Clone-Graph) (M+) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (H-) [337.House-Robber-III](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/337.House-Robber-III) (M+) -[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) [2378.Choose-Edges-to-Maximize-Score-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree) (H-) [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) From b81f90cd8e5d661e22bf8719f186d46a203b9126 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Nov 2023 00:21:27 -0800 Subject: [PATCH 2197/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/Readme.md diff --git a/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/Readme.md b/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/Readme.md new file mode 100644 index 000000000..d3768cfd2 --- /dev/null +++ b/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/Readme.md @@ -0,0 +1,9 @@ +### 2925.Maximum-Score-After-Applying-Operations-on-a-Tree + +我们令dfs(cur)表示以cur为根的子树保持healthy时,能够取得的最高分。 + +我们容易发现,从root一路往下时,只要在某个节点node采取了“不取”的策略,那么之后就没有继续往下走的必要了。因为从root到node再到它的任何一个leaf,这个path sum肯定不会是零。所以我们必然会贪心地将node以下所有节点的value都取走。 + +所以我们在dfs的过程中,如果遍历到了某个节点,其隐含的意思就是从root到node之间的路径都“扫荡”光了。此时如果node依然采用了“取”的策略,那么我们必须保证node的所有子树path都是healthy的才行。于是就是递归处理dfs(nxt)即可。 + +边界条件是对于leaf node,它必须不取,否则连它也取的话,则意味着从root到leaf的path每个节点都取光了,必然不是healthy。 From 583c659a003d7cb3305f52dea21baf195c0db888 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 13 Nov 2023 17:41:22 -0800 Subject: [PATCH 2198/2729] Update 2857.Count-Pairs-of-Points-With-Distance-k.cpp --- ....Count-Pairs-of-Points-With-Distance-k.cpp | 34 ++++++++----------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp b/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp index 47584c1c2..79b1b0eb2 100644 --- a/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp +++ b/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp @@ -1,34 +1,30 @@ -using LL = long long; class Solution { public: int countPairs(vector>& coordinates, int k) { - int n = coordinates.size(); - int ret = 0; - for (int a = 0; a<=k; a++) + unordered_mapMap; + for (int i=0; iMap; - - for (int i=0; i Date: Mon, 13 Nov 2023 18:06:27 -0800 Subject: [PATCH 2199/2729] Update Readme.md --- Others/798.Smallest-Rotation-with-Highest-Score/Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md b/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md index 6ef7ccaad..4dd1af271 100644 --- a/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md +++ b/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md @@ -24,6 +24,7 @@ diff[i+1+N-A[i]] -= 1; 另外,两种情况也可以统一写成 ``` +diff[0]+=1; diff[(i-A[i]+1+N)%N] -= 1; diff[i+1] += 1; ``` From 9bafa4163b7c0bce5d55d60e03db79bfb324279e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 15 Nov 2023 21:30:08 -0800 Subject: [PATCH 2200/2729] Update 798.Smallest-Rotation-with-Highest-Score_v1.cpp --- .../798.Smallest-Rotation-with-Highest-Score_v1.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Others/798.Smallest-Rotation-with-Highest-Score/798.Smallest-Rotation-with-Highest-Score_v1.cpp b/Others/798.Smallest-Rotation-with-Highest-Score/798.Smallest-Rotation-with-Highest-Score_v1.cpp index c844d044c..e33cf2345 100644 --- a/Others/798.Smallest-Rotation-with-Highest-Score/798.Smallest-Rotation-with-Highest-Score_v1.cpp +++ b/Others/798.Smallest-Rotation-with-Highest-Score/798.Smallest-Rotation-with-Highest-Score_v1.cpp @@ -3,20 +3,20 @@ class Solution { int bestRotation(vector& A) { int N = A.size(); - vectordiff(N,0); + vectordiff(N+1,0); for (int i=0; i Date: Wed, 15 Nov 2023 21:52:01 -0800 Subject: [PATCH 2201/2729] Update Readme.md --- Others/798.Smallest-Rotation-with-Highest-Score/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md b/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md index 4dd1af271..dba85368e 100644 --- a/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md +++ b/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md @@ -29,5 +29,7 @@ diff[(i-A[i]+1+N)%N] -= 1; diff[i+1] += 1; ``` +PS:这里取模是没有道理也没有意义的。既然已知移动>=N次会重复之前的结果,我们只需要开长度为N+1的diff数组即可(多留一个是为了在某些情况下设置“下降沿”的时候保证diff不越界,本身diff[N]的数值并不会用到)。至于为什么取模之后能AC,是因为题目问的是最大score所对应的rotation index k,随意乱写任何值的diff[0]都不会改变sum的变化趋势,也就不会影响对最优k的判定。 + [Leetcode Link](https://leetcode.com/problems/smallest-rotation-with-highest-score) From c24cf7d20d40f5acf4636fac4aed3fe159af9608 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 16 Nov 2023 22:17:35 -0800 Subject: [PATCH 2202/2729] Create 2935.Maximum-Strong-Pair-XOR-II.cpp --- .../2935.Maximum-Strong-Pair-XOR-II.cpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Trie/2935.Maximum-Strong-Pair-XOR-II/2935.Maximum-Strong-Pair-XOR-II.cpp diff --git a/Trie/2935.Maximum-Strong-Pair-XOR-II/2935.Maximum-Strong-Pair-XOR-II.cpp b/Trie/2935.Maximum-Strong-Pair-XOR-II/2935.Maximum-Strong-Pair-XOR-II.cpp new file mode 100644 index 000000000..68771f3e6 --- /dev/null +++ b/Trie/2935.Maximum-Strong-Pair-XOR-II/2935.Maximum-Strong-Pair-XOR-II.cpp @@ -0,0 +1,80 @@ +class Solution { + class TrieNode + { + public: + TrieNode* next[2]; + int count = 0; + TrieNode(){ + for (int i=0; i<2; i++) + next[i] = NULL; + } + }; + TrieNode* root; + +public: + int maximumStrongPairXor(vector& nums) + { + root = new TrieNode(); + + sort(nums.begin(), nums.end()); + int j = 0; + int ret = INT_MIN/2; + for (int i=0; i=0; k--) + { + int bit = ((num>>k)&1); + if (node->next[bit]==NULL) + node->next[bit] = new TrieNode(); + node = node->next[bit]; + node->count+=1; + } + } + + void remove(int num) + { + TrieNode* node = root; + for (int k=31; k>=0; k--) + { + int bit = ((num>>k)&1); + node = node->next[bit]; + node->count-=1; + } + } + + int dfs(int num, TrieNode* node, int k) + { + if (k==-1) return 0; + int bit = (num>>k)&1; + if (bit == 0) + { + if (node->next[1] && node->next[1]->count > 0) + return dfs(num, node->next[1], k-1) + (1<next[0] && node->next[0]->count > 0) + return dfs(num, node->next[0], k-1); + } + else + { + if (node->next[0] && node->next[0]->count > 0) + return dfs(num, node->next[0], k-1) + (1<next[1] && node->next[1]->count > 0) + return dfs(num, node->next[1], k-1); + } + + return INT_MIN/2; + } +}; From 9d5fd2a2ba63f3c1fb57982e8a8fd20b0649dccc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 16 Nov 2023 22:18:07 -0800 Subject: [PATCH 2203/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 95ef61d7b..7e861f552 100644 --- a/Readme.md +++ b/Readme.md @@ -651,7 +651,8 @@ [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) [1803.Count-Pairs-With-XOR-in-a-Range](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1803.Count-Pairs-With-XOR-in-a-Range) (H) [1938.Maximum-Genetic-Difference-Query](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1938.Maximum-Genetic-Difference-Query) (H) -[2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees) (H) +[2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees) (H) +[2935.Maximum-Strong-Pair-XOR-II](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2935.Maximum-Strong-Pair-XOR-II) (H) #### [Linked List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List) [061.Rotate-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/061.Rotate-List) (M) From 659cabecb438da86c78de8e4cb1474852fcbda67 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 16 Nov 2023 22:37:09 -0800 Subject: [PATCH 2204/2729] Create Readme.md --- Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md diff --git a/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md b/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md new file mode 100644 index 000000000..923effcf8 --- /dev/null +++ b/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md @@ -0,0 +1,8 @@ +### 2935.Maximum-Strong-Pair-XOR-II + +观察`|x - y| <= min(x, y)`, 假设x是其中较大的那个,很容易推得`x<=2y`。所以我们将nums从小到大排序之后,考察某个y时,可以依次将所有小于等于2y的数字加入一个集合,根据y在这个集合里找能与y异或得到最大值的那个元素。 + +显然这样的“集合”必然是用Trie。将符合y条件的数字加入Trie之后,从高到低遍历y的每个bit位:如果y的bit是1,那么我们就选择在Trie里向下走0的分支(如果存在的话),反之我们就在Trie里向下走1的分支。这样走到底之后,你选择的路径所对应的数字就是能与y异或得到最大的结果。 + +但是我们注意到,符合y条件的数字x,不仅要求`x<=2y`,还要求`x>=y`,这就意味着当y找到它的最优peer之后,要将y从Trie里移出。否则考察下一个y2时,可能会在Trie里找到比y2小的y。在Trie里移除一条路径的技巧是,给每个节点标记一个计数器。加入一条路径时,将沿路的节点的计数器加一;反之删除一个条路径时,将沿路的节点的计数器减一。如果某个节点的计数器为零,意味着该分支已经“虚拟地”从Trie里移出了,就不能再被访问了。 + From 4ca4279f11ad00df211fd1df3f13f6283d782ad0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Nov 2023 22:55:35 -0800 Subject: [PATCH 2205/2729] Create 2931.Maximum-Spending-After-Buying-Items.cpp --- ...31.Maximum-Spending-After-Buying-Items.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Priority_Queue/2931.Maximum-Spending-After-Buying-Items/2931.Maximum-Spending-After-Buying-Items.cpp diff --git a/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/2931.Maximum-Spending-After-Buying-Items.cpp b/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/2931.Maximum-Spending-After-Buying-Items.cpp new file mode 100644 index 000000000..aef3ff4e0 --- /dev/null +++ b/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/2931.Maximum-Spending-After-Buying-Items.cpp @@ -0,0 +1,31 @@ +using PII = pair; +class Solution { +public: + long long maxSpending(vector>& values) + { + int m = values.size(); + int n = values[0].size(); + + priority_queue, greater<>>pq; + vectorp(m, n-1); + for (int i=0; i Date: Fri, 17 Nov 2023 22:56:27 -0800 Subject: [PATCH 2206/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7e861f552..278ca4735 100644 --- a/Readme.md +++ b/Readme.md @@ -461,6 +461,7 @@ [1792.Maximum-Average-Pass-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1792.Maximum-Average-Pass-Ratio) (M+) [2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) [2386.Find-the-K-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2386.Find-the-K-Sum-of-an-Array) (H+) +[2931.Maximum-Spending-After-Buying-Items](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2931.Maximum-Spending-After-Buying-Items) (M) * ``反悔贪心`` [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From 03fc7de742b4d0facfd010ee9cd68dff07aa49c6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Nov 2023 23:00:43 -0800 Subject: [PATCH 2207/2729] Create Readme.md --- .../2931.Maximum-Spending-After-Buying-Items/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Priority_Queue/2931.Maximum-Spending-After-Buying-Items/Readme.md diff --git a/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/Readme.md b/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/Readme.md new file mode 100644 index 000000000..e04e38fcd --- /dev/null +++ b/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/Readme.md @@ -0,0 +1,5 @@ +### 2931.Maximum-Spending-After-Buying-Items + +非常直观地贪心。为了使得总和最大,我们会将尽量小的d与尽量小的value相乘,而相对大的d与相对大的value相乘。证明如下:令a0`. + +所以我们将所有shop里当前available的物品放入一个小顶堆,每次取最小值与当前的d相乘即可。取完一个最小值,就把它对应的shop的下一件available的物品放入PQ。直至取完所有m*n件物品。 From 23b528ff39df211c367aaa8aa1ae12bd07f7df83 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 10:36:55 -0800 Subject: [PATCH 2208/2729] Update Readme.md --- Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md b/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md index 923effcf8..78d055414 100644 --- a/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md +++ b/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md @@ -1,8 +1,8 @@ ### 2935.Maximum-Strong-Pair-XOR-II -观察`|x - y| <= min(x, y)`, 假设x是其中较大的那个,很容易推得`x<=2y`。所以我们将nums从小到大排序之后,考察某个y时,可以依次将所有小于等于2y的数字加入一个集合,根据y在这个集合里找能与y异或得到最大值的那个元素。 +观察`|x - y| <= min(x, y)`, 假设x是其中较大的那个,很容易推得`y<=x<=2y`。所以我们将nums从小到大排序之后,考察某个数作为y时,可以将一段滑窗内的元素[y,2y]加入一个集合,根据y在这个集合里找能与y异或得到最大值的那个元素。并且,我们发现随着y的移动,这个滑窗的移动也是单调的,说明每个式子进入集合与移出集合都只需要操作一次,时间复杂度是o(N). -显然这样的“集合”必然是用Trie。将符合y条件的数字加入Trie之后,从高到低遍历y的每个bit位:如果y的bit是1,那么我们就选择在Trie里向下走0的分支(如果存在的话),反之我们就在Trie里向下走1的分支。这样走到底之后,你选择的路径所对应的数字就是能与y异或得到最大的结果。 +对于求最大XOR pair而言,这样的“集合”必然是用Trie。将符合y条件的数字加入Trie之后,从高到低遍历y的每个bit位:如果y的bit是1,那么我们就选择在Trie里向下走0的分支(如果存在的话),反之我们就在Trie里向下走1的分支。这样走到底之后,你选择的路径所对应的数字就是能与y异或得到最大的结果。 -但是我们注意到,符合y条件的数字x,不仅要求`x<=2y`,还要求`x>=y`,这就意味着当y找到它的最优peer之后,要将y从Trie里移出。否则考察下一个y2时,可能会在Trie里找到比y2小的y。在Trie里移除一条路径的技巧是,给每个节点标记一个计数器。加入一条路径时,将沿路的节点的计数器加一;反之删除一个条路径时,将沿路的节点的计数器减一。如果某个节点的计数器为零,意味着该分支已经“虚拟地”从Trie里移出了,就不能再被访问了。 +PS:在Trie里实时加入一条路径很简单,但是如何移除一条路径呢?显然不能盲目地删除该路径上的所有节点,因为它可能被其他路径共享。技巧是,给每个节点标记一个计数器。加入一条路径时,将沿路的节点的计数器加一;反之删除一个条路径时,将沿路的节点的计数器减一。如果某个节点的计数器为零,意味着该分支已经“虚拟地”从Trie里移出了,就不能再被访问了。 From b8d24363ce65c747b365ab7e6122f9b082c87f41 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 20:19:23 -0800 Subject: [PATCH 2209/2729] Create 2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp --- ...-Building-Where-Alice-and-Bob-Can-Meet.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp new file mode 100644 index 000000000..f1d0f98f3 --- /dev/null +++ b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + vector leftmostBuildingQueries(vector& heights, vector>& queries) + { + int n = heights.size(); + + for (int i=0; i&a, vector&b){ + return a[1]>b[1]; + }); + + vectorrets(queries.size()); + int i = n-1; + mapMap; + for (auto& query: queries) + { + int a = query[0], b = query[1], idx = query[2]; + while (i>=max(a,b)) + { + while (!Map.empty() && heights[i] >= (Map.begin()->first)) + Map.erase(Map.begin()); + Map[heights[i]] = i; + i--; + } + + if (heights[a] < heights[b] || a==b) + { + rets[idx] = b; + continue; + } + + int m = max(heights[a],heights[b]); + auto iter = Map.upper_bound(m); + if (iter!=Map.end()) + rets[idx] = iter->second; + else + rets[idx] = -1; + } + + return rets; + } +}; From 682ff788109855c76d9d68676401661bc05c5cea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 20:20:26 -0800 Subject: [PATCH 2210/2729] Update 2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp --- .../2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp index f1d0f98f3..a3c30e7b2 100644 --- a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp +++ b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp @@ -20,7 +20,7 @@ class Solution { for (auto& query: queries) { int a = query[0], b = query[1], idx = query[2]; - while (i>=max(a,b)) + while (i>=b) { while (!Map.empty() && heights[i] >= (Map.begin()->first)) Map.erase(Map.begin()); From c14eb05cf8fe998e65ea5a760b96be622b3c8de2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 23:14:07 -0800 Subject: [PATCH 2211/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md new file mode 100644 index 000000000..b5a77e515 --- /dev/null +++ b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md @@ -0,0 +1,11 @@ +### 2940.Find-Building-Where-Alice-and-Bob-Can-Meet + +我们考虑一个query所给的两个位置a和b(其中aheights[y],那么事实上y就可以从容器里移除。因为x更靠近左边且更高,任何满足(a,b)->y的query,必然也满足(a,b)->x且x是比y更优的解(更靠近左边)。这就提示我们,如果我们将heights里的元素按照从右往左的顺序加入有序容器的话,那么就可以用上述的性质:新柱子的加入可以弹出所有比它矮的旧柱子。这就导致了这个有序容器里的柱子不仅是按照height递增的,而且他们对应的index也是递增的。也就是说,有序容器里对于任意的heights[x] i`(for i>b),同时更新容器移除陈旧的值(即那些相比于i,更靠右且更矮的柱子)。然后一个upper_bound解决该query。往容器里添加和删除元素的数据量都是线性的。 + +此外,本题需要处理两个小细节。如果heights[a]==heights[b]以及a==b的这两种情况,直接输出答案b即可。 From 5f372c8918dd8531cd46e6a46db3db4ad66d4b9a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 23:14:43 -0800 Subject: [PATCH 2212/2729] Update Readme.md --- Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md index b5a77e515..614774896 100644 --- a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md +++ b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md @@ -1,6 +1,6 @@ ### 2940.Find-Building-Where-Alice-and-Bob-Can-Meet -我们考虑一个query所给的两个位置a和b(其中aheights[y],那么事实上y就可以从容器里移除。因为x更靠近左边且更高,任何满足(a,b)->y的query,必然也满足(a,b)->x且x是比y更优的解(更靠近左边)。这就提示我们,如果我们将heights里的元素按照从右往左的顺序加入有序容器的话,那么就可以用上述的性质:新柱子的加入可以弹出所有比它矮的旧柱子。这就导致了这个有序容器里的柱子不仅是按照height递增的,而且他们对应的index也是递增的。也就是说,有序容器里对于任意的heights[x] Date: Sun, 19 Nov 2023 23:16:40 -0800 Subject: [PATCH 2213/2729] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 278ca4735..aecda47f8 100644 --- a/Readme.md +++ b/Readme.md @@ -194,7 +194,7 @@ [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) [2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) [2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) -[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) +[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) @@ -221,12 +221,14 @@ [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2736.Maximum-Sum-Queries) (H) -[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) [2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) [2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) +* ``Monotonic Heap`` +[2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) +[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From ffd0a2cca7e6557d10124e83f5e7f46a1336cf5e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Nov 2023 23:05:26 -0800 Subject: [PATCH 2214/2729] Create 2939.Maximum-Xor-Product.cpp --- .../2939.Maximum-Xor-Product.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp diff --git a/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp b/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp new file mode 100644 index 000000000..7c8b4c876 --- /dev/null +++ b/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp @@ -0,0 +1,63 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int maximumXorProduct(long long a, long long b, int n) + { + LL A = ((a>>n)<>n)<=0; k--) + { + LL bit1 = ((a>>k)&1LL); + LL bit2 = ((b>>k)&1LL); + if (bit1==bit2) + { + a = a - (bit1<B) + { + for (int k=n-1; k>=0; k--) + { + LL bit1 = ((a>>k)&1LL); + LL bit2 = ((b>>k)&1LL); + if (bit1==bit2) + { + a = a - (bit1< Date: Mon, 20 Nov 2023 23:06:04 -0800 Subject: [PATCH 2215/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index aecda47f8..eb5b98811 100644 --- a/Readme.md +++ b/Readme.md @@ -1551,7 +1551,7 @@ #### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   [2860.Happy-Students](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2860.Happy-Students) (M+) [2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices) (H-) - +[2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From 96a4f5d9cb5fd2d5a657e8e15a3649d7c4c44703 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Nov 2023 23:59:32 -0800 Subject: [PATCH 2216/2729] Create Readme.md --- Thinking/2939.Maximum-Xor-Product/Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Thinking/2939.Maximum-Xor-Product/Readme.md diff --git a/Thinking/2939.Maximum-Xor-Product/Readme.md b/Thinking/2939.Maximum-Xor-Product/Readme.md new file mode 100644 index 000000000..83d037f37 --- /dev/null +++ b/Thinking/2939.Maximum-Xor-Product/Readme.md @@ -0,0 +1,19 @@ +### 2939.Maximum-Xor-Product + +首先考虑XOR只是位操作,bit之间互不影响,所以我们考察一下所有位操作的可能: +``` +a: 0, 0, || 1, 1, || 1, 1, || 0, 0 +b: 1, 1, || 0, 0, || 1, 1, || 0, 0 +x: 0, 1, || 0, 1, || 0, 1, || 0, 1 +----------- +a^x: 0, 1, || 1, 0, || 1, 0, || 0, 1 +b^x: 1, 0, || 0, 1, || 1, 0, || 0, 1 + G G G G G B B G +``` +为了使得每个bit位上的`(a^x)*(b^x)`最大,我们总结出如下规律: +1. 如果a与b的bit值不同(即一个0一个1),不管如何设置x,都会使得a^x与b^x其中一个是0且令一个是1. +2. 如果a与b的bit值相同,那么最优的x是取与其相反的数值,使得a^x与b^x都是1(因为让两者都是0显然不是最优策略). + +对于第二种情况,决策是固定的。对于第一种情况,我们还需要确定,究竟是让a^x是1,还是让b^x是1. 此时我们发现,无论做何选择,`a^x + b^x`总是固定的。我们知道这样一个定理:在sum固定的情况下,想让两个元素的积最大,我们必然希望这两个元素尽量相等。为了实现这个目标,我们就应该给`a^x`和`b^x`在各个(属于情况一的)bit位上交替赋1/0,以此实现最大化的`(a^x)*(b^x)`. + +但是注意,以上的分析要求x能覆盖a与b的所有bit位。事实上x有限制范围,最多只能设置n个比特位。如果a与b的二进制长度大于x,那么以上分析就不适用了。但是,最优的x应该使得`a^x + b^x`不变这个原则依然是成立的。在这种情况下,如果a已经大于b,那么就在第一种情况时,把0都赋给a^x,把1都赋给b^x,这样可以拉近a^x与b^x,得到最大的乘积。反之,如果a已经小于b,那么在第一种情况时,把1都赋给a^x,把0都赋给b^x, From 81060bd8bda9f1817226940257600442b688739e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Nov 2023 23:59:47 -0800 Subject: [PATCH 2217/2729] Update Readme.md --- Thinking/2939.Maximum-Xor-Product/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2939.Maximum-Xor-Product/Readme.md b/Thinking/2939.Maximum-Xor-Product/Readme.md index 83d037f37..17a250e55 100644 --- a/Thinking/2939.Maximum-Xor-Product/Readme.md +++ b/Thinking/2939.Maximum-Xor-Product/Readme.md @@ -16,4 +16,4 @@ b^x: 1, 0, || 0, 1, || 1, 0, || 0, 1 对于第二种情况,决策是固定的。对于第一种情况,我们还需要确定,究竟是让a^x是1,还是让b^x是1. 此时我们发现,无论做何选择,`a^x + b^x`总是固定的。我们知道这样一个定理:在sum固定的情况下,想让两个元素的积最大,我们必然希望这两个元素尽量相等。为了实现这个目标,我们就应该给`a^x`和`b^x`在各个(属于情况一的)bit位上交替赋1/0,以此实现最大化的`(a^x)*(b^x)`. -但是注意,以上的分析要求x能覆盖a与b的所有bit位。事实上x有限制范围,最多只能设置n个比特位。如果a与b的二进制长度大于x,那么以上分析就不适用了。但是,最优的x应该使得`a^x + b^x`不变这个原则依然是成立的。在这种情况下,如果a已经大于b,那么就在第一种情况时,把0都赋给a^x,把1都赋给b^x,这样可以拉近a^x与b^x,得到最大的乘积。反之,如果a已经小于b,那么在第一种情况时,把1都赋给a^x,把0都赋给b^x, +但是注意,以上的分析要求x能覆盖a与b的所有bit位。事实上x有限制范围,最多只能设置n个比特位。如果a与b的二进制长度大于x,那么以上分析就不适用了。但是,最优的x应该使得`a^x + b^x`不变这个原则依然是成立的。在这种情况下,如果a已经大于b,那么就在第一种情况时,把0都赋给a^x,把1都赋给b^x,这样可以拉近a^x与b^x,得到最大的乘积。反之,如果a已经小于b,那么在第一种情况时,把1都赋给a^x,把0都赋给b^x。 From aa25385a925d7822a8129253add60297fc93e5d2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Nov 2023 16:20:46 -0800 Subject: [PATCH 2218/2729] Update 2939.Maximum-Xor-Product.cpp --- Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp b/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp index 7c8b4c876..d1cba2eb6 100644 --- a/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp +++ b/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp @@ -27,7 +27,7 @@ class Solution { { a = a - (bit1< Date: Tue, 21 Nov 2023 16:22:20 -0800 Subject: [PATCH 2219/2729] Update Readme.md --- Thinking/2939.Maximum-Xor-Product/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2939.Maximum-Xor-Product/Readme.md b/Thinking/2939.Maximum-Xor-Product/Readme.md index 17a250e55..6cc061d06 100644 --- a/Thinking/2939.Maximum-Xor-Product/Readme.md +++ b/Thinking/2939.Maximum-Xor-Product/Readme.md @@ -14,6 +14,6 @@ b^x: 1, 0, || 0, 1, || 1, 0, || 0, 1 1. 如果a与b的bit值不同(即一个0一个1),不管如何设置x,都会使得a^x与b^x其中一个是0且令一个是1. 2. 如果a与b的bit值相同,那么最优的x是取与其相反的数值,使得a^x与b^x都是1(因为让两者都是0显然不是最优策略). -对于第二种情况,决策是固定的。对于第一种情况,我们还需要确定,究竟是让a^x是1,还是让b^x是1. 此时我们发现,无论做何选择,`a^x + b^x`总是固定的。我们知道这样一个定理:在sum固定的情况下,想让两个元素的积最大,我们必然希望这两个元素尽量相等。为了实现这个目标,我们就应该给`a^x`和`b^x`在各个(属于情况一的)bit位上交替赋1/0,以此实现最大化的`(a^x)*(b^x)`. +对于第二种情况,决策是固定的。对于第一种情况,我们还需要确定,究竟是让a^x是1,还是让b^x是1. 此时我们发现,无论做何选择,`a^x + b^x`总是固定的。我们知道这样一个定理:在sum固定的情况下,想让两个元素的积最大,我们必然希望这两个元素尽量相等。为了实现这个目标,我们可以在第一次时给`a^x`赋1,之后都给`b^x`赋1,以此实现最大化的`(a^x)*(b^x)`. 但是注意,以上的分析要求x能覆盖a与b的所有bit位。事实上x有限制范围,最多只能设置n个比特位。如果a与b的二进制长度大于x,那么以上分析就不适用了。但是,最优的x应该使得`a^x + b^x`不变这个原则依然是成立的。在这种情况下,如果a已经大于b,那么就在第一种情况时,把0都赋给a^x,把1都赋给b^x,这样可以拉近a^x与b^x,得到最大的乘积。反之,如果a已经小于b,那么在第一种情况时,把1都赋给a^x,把0都赋给b^x。 From a77e5401ddaed4d5bd547621a3d1009d49845f62 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Nov 2023 23:20:35 -0800 Subject: [PATCH 2220/2729] Create 2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp --- ...Can-Be-Rearranged-to-Contain-Substring.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp diff --git a/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp b/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp new file mode 100644 index 000000000..13cbce6f7 --- /dev/null +++ b/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp @@ -0,0 +1,35 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[100005][2][3][2]; +public: + int stringCount(int n) + { + dp[0][0][0][0] = 1; + for (int i=1; i<=n; i++) + for (int a=0; a<2; a++) + for (int b=0; b<3; b++) + for (int c=0; c<2; c++) + { + for (int k=0; k<26; k++) + { + if (k==('l'-'a') && a==1) + dp[i][1][b][c] += dp[i-1][0][b][c]; + else if (k==('e'-'a') && b==1) + dp[i][a][1][c] += dp[i-1][a][0][c]; + else if (k==('e'-'a') && b==2) + dp[i][a][2][c] += dp[i-1][a][1][c]; + else if (k==('t'-'a') && c==1) + dp[i][a][b][1] += dp[i-1][a][b][0]; + else + { + dp[i][a][b][c] += dp[i-1][a][b][c]; + dp[i][a][b][c] %= M; + } + } + } + + return dp[n][1][2][1]; + + } +}; From 9a0117e05015d0a9f39a92435ca87cdd79ead4c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Nov 2023 23:21:18 -0800 Subject: [PATCH 2221/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index eb5b98811..0033aaeb3 100644 --- a/Readme.md +++ b/Readme.md @@ -1205,6 +1205,7 @@ [2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps) (M+) [2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) [2539.Count-the-Number-of-Good-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2539.Count-the-Number-of-Good-Subsequences) (H-) +[2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From 647001e6059757bde0a6f1bb4f898469dc3f6ebd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Nov 2023 23:36:50 -0800 Subject: [PATCH 2222/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/Readme.md diff --git a/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/Readme.md b/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/Readme.md new file mode 100644 index 000000000..9570492be --- /dev/null +++ b/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/Readme.md @@ -0,0 +1,21 @@ +### 2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring + +本题是求长度为n、且包括leet的字符串有多少种。看上去是个组合数学的问题,其实可以转化为基础的动态规划。我们令dp[i][a][b][c]表示前i个字符里至少有a个'l',b个'e',c个't'的种类数目。那么计算dp[i][a][b][c]时考虑第i个字符是什么,以及它对a,b,c的影响: +```cpp +// compute dp[i][1][b][c] +for (int k=0; k<26; k++) +{ + if (k==('l'-'a') && a==1) + dp[i][1][b][c] += dp[i-1][0][b][c]; + else if (k==('e'-'a') && b==1) + dp[i][a][1][c] += dp[i-1][a][0][c]; + else if (k==('e'-'a') && b==2) + dp[i][a][2][c] += dp[i-1][a][1][c]; + else if (k==('t'-'a') && c==1) + dp[i][a][b][1] += dp[i-1][a][b][0]; + else + dp[i][a][b][c] += dp[i-1][a][b][c]; +``` +最终答案就是`dp[n][1][2][1]` + +事实上很多组合数学的本质就是动态规划。比如注明的组合数公式`C(m,n) = C(m-1, n) + C(m-1, n-1)`其实就是动态转移方程。含义就是:从前m个数里取n个,取决于第m个数要不要取?是的话,相当于在前m-1里取n-1个;不是的话,相当于在前m-1个里面取n个。 From d64eb33cd3756a7fc2e7432335278fb6e60954e6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 15:24:24 -0800 Subject: [PATCH 2223/2729] Create 2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp --- ...e-Triplets-With-Increasing-Prices-I_v2.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp new file mode 100644 index 000000000..a5e031b0b --- /dev/null +++ b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp @@ -0,0 +1,62 @@ +class Solution { +public: + int maxProfit(vector& prices, vector& profits) + { + int n = prices.size(); + mapMap; + + vectorleft(n, -1); + for (int i=0; isecond; + } + if (Map.find(prices[i])!=Map.end() && profits[i]<=Map[prices[i]]) + continue; + if (profits[i] <= left[i]) + continue; + Map[prices[i]] = profits[i]; + iter = next(Map.find(prices[i])); + while (iter!=Map.end() && iter->second <= profits[i]) + iter = Map.erase(iter); + } + + Map.clear(); + vectorright(n, -1); + for (int i=n-1; i>=0; i--) + { + auto iter = Map.upper_bound(prices[i]); + if (iter!=Map.end()) + { + right[i] = iter->second; + } + if (Map.find(prices[i])!=Map.end() && profits[i]<=Map[prices[i]]) + continue; + if (profits[i] <= right[i]) + continue; + Map[prices[i]] = profits[i]; + iter = Map.find(prices[i]); + + map::reverse_iterator rit(iter); + // Note rit is actually at a one-position diff before iter. + vectorto_delete; + while (rit!=Map.rend() && rit->second <= profits[i]) + { + int key = rit->first; + rit = next(rit); + to_delete.push_back(key); + } + for (auto key: to_delete) Map.erase(key); + } + + int ret = -1; + for (int i=0; i Date: Wed, 22 Nov 2023 15:34:29 -0800 Subject: [PATCH 2224/2729] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 653f7717e..1710c38de 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -27,8 +27,8 @@ class SegTreeNode SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val { - lazy_tag = 0; - lazy_val = 0; + tag = 0; + info = 0; start = a, end = b; if (a==b) { From 17b8b234ace37e7d99e25701581fece3eaefbd11 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 15:42:30 -0800 Subject: [PATCH 2225/2729] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 1710c38de..1d74c5ce8 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -80,7 +80,7 @@ class SegTreeNode { if (b < start || a > end ) { - return INT_MIN; // check with your own logic + return INT_MIN/2; // check with your own logic } if (a <= start && end <=b) { From 4d43c81245d750ec758181e9113e6a021a64fa09 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 15:49:16 -0800 Subject: [PATCH 2226/2729] Create 2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp --- ...e-Triplets-With-Increasing-Prices-I_v1.cpp | 144 ++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp new file mode 100644 index 000000000..8e57d325c --- /dev/null +++ b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp @@ -0,0 +1,144 @@ +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + info = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MIN/2; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + +class Solution { +public: + int maxProfit(vector& prices, vector& profits) + { + setSet(prices.begin(), prices.end()); + unordered_mapMap; + int m = 0; + for (int x: Set) + { + Map[x] = m; + m++; + } + + SegTreeNode* root1 = new SegTreeNode(0, m-1, -1); // Set the leaf nodes with initVals. + SegTreeNode* root2 = new SegTreeNode(0, m-1, -1); // Set the leaf nodes with initVals. + + int n = prices.size(); + vectorleft(n, -1); + for (int i=0; iqueryRange(0, Map[prices[i]]-1); + if (profits[i] > root1->queryRange(Map[prices[i]], Map[prices[i]])) + root1->updateRange(Map[prices[i]], Map[prices[i]], profits[i]); // set the range [start, end] with val + } + + vectorright(n, -1); + for (int i=n-1; i>=0; i--) + { + right[i] = root2->queryRange(Map[prices[i]]+1, m-1); + if (profits[i] > root2->queryRange(Map[prices[i]], Map[prices[i]])) + root2->updateRange(Map[prices[i]], Map[prices[i]], profits[i]); // set the range [start, end] with val + } + + int ret = -1; + for (int i=0; i Date: Wed, 22 Nov 2023 15:50:48 -0800 Subject: [PATCH 2227/2729] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0033aaeb3..c63007e6d 100644 --- a/Readme.md +++ b/Readme.md @@ -228,7 +228,8 @@ [2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) * ``Monotonic Heap`` [2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) -[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) +[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) +[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) @@ -334,6 +335,7 @@ [2286.Booking-Concert-Tickets-in-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups) (H-) [2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) +[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 2a8e414ac3497dfd12c0cb1f7f4e7d3f11198e08 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 16:06:50 -0800 Subject: [PATCH 2228/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md new file mode 100644 index 000000000..6f4141bb5 --- /dev/null +++ b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md @@ -0,0 +1,11 @@ +### 2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I + +#### 解法1:线段树 +此题可以用线段树无脑解决。先从左往右遍历一遍,逐个将物品放入线段树,leaf表示价格,value表示profit。对于第i件物品,在所有价格小于prices[i]的物品中找出profit最大值,记做left[i]. 再从右往左遍历一遍,逐个将物品放入另一棵线段树,leaf表示价格,value表示profit。对于第i件物品,在所有价格大于prices[i]的物品中找出profit最大值,记做right[i]. 最后,找到全局最大的`left[i]+profits[i]+right[i]`. + +注意,尽管prices不超过1e6,此题仍然需要先离散化减少开辟叶子节点的需求,否则会TLE。 + +#### 解法2:单调的有序容器 +和上面类似的思想,不过在从左往右遍历的过程中,我们维护一个按key递增有序的Map,key是price,value是profit。同时我们额外维护这个Map使得里面的元素在value的意义上也是递增的。这样对于第i件物品,我们用`upper_bound + prev`找到最后一件恰好小于prices[i]的物品,它的profit就是我们想要的left[i],因为Map里面其他价格更小的物品的profit是更小的。然后我们将新的`{prices[i], profits[i]}`加入容器时,有一个特别的操作,在它之后任何价格更高、但利润更低的元素都可以从容器里面删除,以此保证插入新元素之后该容器依然是按照key和value都是递增。 + +类似地,我们再从右往左遍历一遍,同时我们维护这个Map使得里面的元素按照key递增的同时,在value的意义上是递减的。这样对于第i件物品,我们用`upper_bound + prev`找到第一件恰好大于prices[i]的物品,它的profit就是我们想要的right[i],因为Map里面其他价格更大的物品的profit是更小的。然后我们将新的`{prices[i], profits[i]}`加入容器后,有一个特别的操作,在它之前任何价格低、同时利润也更低的元素都可以从容器里面删除,以此保证插入新元素之后该容器依然是按照value都是递减的。注意,这个操作可能需要reverse_iterator. From aeef1c6227945da97163b944f5e86cb33ddf814a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 16:11:27 -0800 Subject: [PATCH 2229/2729] Update 2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp --- ...m-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp index a5e031b0b..65635ee60 100644 --- a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp +++ b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp @@ -18,7 +18,8 @@ class Solution { if (profits[i] <= left[i]) continue; Map[prices[i]] = profits[i]; - iter = next(Map.find(prices[i])); + + iter = Map.upper_bound(prices[i]); while (iter!=Map.end() && iter->second <= profits[i]) iter = Map.erase(iter); } @@ -36,9 +37,9 @@ class Solution { continue; if (profits[i] <= right[i]) continue; - Map[prices[i]] = profits[i]; - iter = Map.find(prices[i]); - + Map[prices[i]] = profits[i]; + + iter = Map.find(prices[i]); map::reverse_iterator rit(iter); // Note rit is actually at a one-position diff before iter. vectorto_delete; From ab739eaf9eabf38ee3e969c095ecc16c357ccd21 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 24 Nov 2023 05:02:00 -0800 Subject: [PATCH 2230/2729] Update 2731.Movement-of-Robots.cpp --- .../2731.Movement-of-Robots.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp b/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp index 10e1ea152..c00939397 100644 --- a/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp +++ b/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp @@ -5,26 +5,25 @@ class Solution { int sumDistance(vector& nums, string s, int d) { int n = nums.size(); - vectorpos; + vectorpos; for (int i=0; i Date: Fri, 24 Nov 2023 23:07:31 -0800 Subject: [PATCH 2231/2729] Create 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp --- ...of-Groups-to-Create-a-Valid-Assignment.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp new file mode 100644 index 000000000..1ff807722 --- /dev/null +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minGroupsForValidAssignment(vector& nums) + { + int n = nums.size(); + int m = 0; + unordered_mapMap; + for (int x: nums) + { + Map[x]++; + m = max(m, Map[x]); + } + + for (int k=m; k>=1; k--) + { + int count = 0; + for (auto [_, x]: Map) + { + if (x % k <= x/k) + { + count += ceil(x*1.0/(k+1)); + } + else + { + count = -1; + break; + } + + } + if (count != -1) return count; + } + + return 0; + } +}; From cb692bb04cf1aef881a58ded2545178bf730237d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 24 Nov 2023 23:08:04 -0800 Subject: [PATCH 2232/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c63007e6d..bfd738030 100644 --- a/Readme.md +++ b/Readme.md @@ -1554,6 +1554,7 @@ #### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   [2860.Happy-Students](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2860.Happy-Students) (M+) [2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices) (H-) +[2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment) (H-) [2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) From ad9d04ce9afd25f72bdc51289ddd6d1a9b62b793 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 24 Nov 2023 23:10:50 -0800 Subject: [PATCH 2233/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index bfd738030..f6db33a7e 100644 --- a/Readme.md +++ b/Readme.md @@ -1462,7 +1462,6 @@ [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) -[2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) * ``公式变形`` [2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` @@ -1530,6 +1529,7 @@ [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) +[2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 79b55aa8d448654365df05546048f176ff114454 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 24 Nov 2023 23:33:32 -0800 Subject: [PATCH 2234/2729] Update 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp --- ...ber-of-Groups-to-Create-a-Valid-Assignment.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp index 1ff807722..2f45563fa 100644 --- a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp @@ -2,14 +2,13 @@ class Solution { public: int minGroupsForValidAssignment(vector& nums) { - int n = nums.size(); - int m = 0; - unordered_mapMap; - for (int x: nums) - { - Map[x]++; - m = max(m, Map[x]); - } + int n = nums.size(); + unordered_mapMap; + for (int x: nums) Map[x]++; + + int m = INT_MAX; + for (auto [_, x]: Map) + m = min(m, x); for (int k=m; k>=1; k--) { From 12bfe5ddb6ff4eadbdb37b6b962e9e8516ec8977 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Nov 2023 00:05:37 -0800 Subject: [PATCH 2235/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md new file mode 100644 index 000000000..61a678284 --- /dev/null +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md @@ -0,0 +1,11 @@ +### 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment + +我们首先将所有元素的频率收集起来放入一个数组arr。本题就是将arr里的每个元素都做拆分,要求最多只能拆分出两种相邻的数字(记做k和k+1)。求最少能拆分出多少个数字来。 + +本题的一个坑就是二分搜索是不成立的。这是说拆分的越多就越容易,这里没有单调性。比如说,[10,20]可以拆分出k=10, 即[10,10,10];但不能拆分出k=9;但是又可以拆分出k=5,即[5,5,5,5,5,5]. + +本题的解法其实就是暴力尝试。假设arr的长度是n,出现最小的频次是m,那么我们就从`k=m,m-1,...,1`逐个尝试,找到最大的k使得所有arr的元素都能成功拆分成若干个k或k+1的和。这样的时间复杂度看上去是0(mn). 事实上mn有制约关系,如果nums的种类各不相同,那么m就是1,n就是1e5;如果nums的种类完全相同,那么m就是1e5,n就是1. 事实上,o(mn)就是1e5数量级。 + +接下来我们考虑,如果给定了k,如何判定某个arr的元素x能成功拆封成若干个k或k+1之和?我们将x尽量拆分出k来,得到`q = x/k`个group,以及余数`r = x%k`. 如果`r<=q`,意味着我们可以将这些余数拆散到每个group去,而那些group的值就是`k+1`了依然符合要求. 这就是判据。 + +最终当我们找到最大的k,使得所有arr的x都能成立时,我们用`ceil(x*1.0/(k+1))`即可计算出总共分成的group的数目。 From fd08ad0d309cfa5b8830203f2c3834f40fbd1ed2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Nov 2023 14:03:56 -0800 Subject: [PATCH 2236/2729] Update 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp --- ...imum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp index 2f45563fa..811db33dc 100644 --- a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp @@ -10,14 +10,16 @@ class Solution { for (auto [_, x]: Map) m = min(m, x); - for (int k=m; k>=1; k--) + for (int k=m+1; k>=1; k--) { int count = 0; for (auto [_, x]: Map) { - if (x % k <= x/k) + int q = x / k; + int r = x % k; + if (r==0 || k-r <= q+1) { - count += ceil(x*1.0/(k+1)); + count += ceil(x*1.0 / k); } else { From 56fe24591ecc16cd3010c17f7b086b369f29b8fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Nov 2023 14:08:26 -0800 Subject: [PATCH 2237/2729] Update Readme.md --- .../Readme.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md index 61a678284..326690df2 100644 --- a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md @@ -1,11 +1,11 @@ ### 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment -我们首先将所有元素的频率收集起来放入一个数组arr。本题就是将arr里的每个元素都做拆分,要求最多只能拆分出两种相邻的数字(记做k和k+1)。求最少能拆分出多少个数字来。 +我们首先将所有元素的频率收集起来放入一个数组arr。本题就是将arr里的每个元素都做拆分,要求最多只能拆分出两种相邻的数字(记做k和k-1)。求最少能拆分出多少个数字来。 本题的一个坑就是二分搜索是不成立的。这是说拆分的越多就越容易,这里没有单调性。比如说,[10,20]可以拆分出k=10, 即[10,10,10];但不能拆分出k=9;但是又可以拆分出k=5,即[5,5,5,5,5,5]. -本题的解法其实就是暴力尝试。假设arr的长度是n,出现最小的频次是m,那么我们就从`k=m,m-1,...,1`逐个尝试,找到最大的k使得所有arr的元素都能成功拆分成若干个k或k+1的和。这样的时间复杂度看上去是0(mn). 事实上mn有制约关系,如果nums的种类各不相同,那么m就是1,n就是1e5;如果nums的种类完全相同,那么m就是1e5,n就是1. 事实上,o(mn)就是1e5数量级。 +本题的解法其实就是暴力尝试。假设arr的长度是n,出现最小的频次是m,那么我们就从`k=m+1,m,...,1`逐个尝试,找到最大的k使得所有arr的元素都能成功拆分成若干个k或k-1的和。这样的时间复杂度看上去是0(mn). 事实上mn有制约关系,如果nums的种类各不相同,那么m就是1,n就是1e5;如果nums的种类完全相同,那么m就是1e5,n就是1. 事实上,o(mn)就是1e5数量级。 -接下来我们考虑,如果给定了k,如何判定某个arr的元素x能成功拆封成若干个k或k+1之和?我们将x尽量拆分出k来,得到`q = x/k`个group,以及余数`r = x%k`. 如果`r<=q`,意味着我们可以将这些余数拆散到每个group去,而那些group的值就是`k+1`了依然符合要求. 这就是判据。 +接下来我们考虑,如果给定了k,如何判定某个arr的元素x能成功拆封成若干个k或k-1之和?我们将x尽量拆分出最多的k来,得到`q = x/k`个group,以及余数`r = x%k`. 此时我们还差`k-r`才能凑出一个k。如果`k-r<=q+1`,意味着我们从之前的这些group里各自都拆借1加到最后一个“落单”的group,而那些变动的group里含有的元素就是`k-1`,依然符合要求. 注意,如果`r==0`时,需要另外处理这个corner case。 -最终当我们找到最大的k,使得所有arr的x都能成立时,我们用`ceil(x*1.0/(k+1))`即可计算出总共分成的group的数目。 +最终当我们找到最大的k,使得所有arr的x都能成立时,我们用`ceil(x*1.0/k)`即可计算出总共分成的group的数目。 From e978cb813256f9b6ca2da53dc3df8fd238947e42 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Nov 2023 21:55:01 -0800 Subject: [PATCH 2238/2729] Create 2945.Find-Maximum-Non-decreasing-Array-Length.cpp --- ...nd-Maximum-Non-decreasing-Array-Length.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp new file mode 100644 index 000000000..0d65ac09a --- /dev/null +++ b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp @@ -0,0 +1,39 @@ +using LL = long long; +class Solution { +public: + int findMaximumLength(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + vectordp(n+1,-1); + vectorlen(n+1,-1); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1] + nums[i]; + + dp[0] = 0; + len[0] = 0; + int ret = 0; + mapMap; + Map[0] = 0; + for (int i=1; i<=n; i++) + { + auto iter = Map.upper_bound(presum[i]); + if (iter!=Map.begin()) + { + int j = prev(iter)->second; + len[i] = len[j]+1; + dp[i] = presum[i] - presum[j]; + } + + while (!Map.empty() && Map.rbegin()->first >= presum[i]+dp[i]) + Map.erase(prev(Map.end())); + + Map[presum[i]+dp[i]] = i; + } + + return len[n]; + + } +}; From 0517b16b010a5d8db28d4e2faa8b36457d262a5f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Nov 2023 21:55:30 -0800 Subject: [PATCH 2239/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f6db33a7e..18e50f45f 100644 --- a/Readme.md +++ b/Readme.md @@ -230,6 +230,7 @@ [2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) [2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) +[2945.Find-Maximum-Non-decreasing-Array-Length](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2945.Find-Maximum-Non-decreasing-Array-Length) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From ff4cf993996352be3d622f9b66b565d3f32488eb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Nov 2023 22:38:01 -0800 Subject: [PATCH 2240/2729] Create Readme.md --- .../Readme.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md new file mode 100644 index 000000000..e1bafa426 --- /dev/null +++ b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md @@ -0,0 +1,25 @@ +### 2945.Find-Maximum-Non-decreasing-Array-Length + +我们考虑,如果以nums[i]为某段subarray的结尾,那么我们在[1:i]前缀里能够得到的符合条件的最长序列。我们记最后这段subarray sum为dp[i]. 显然,我们需要找到一个位置j,使得dp[j]<=dp[i](其中dp[i]=sum[j+1:i])。为了使得序列尽量长,我们自然希望dp[i]能尽量小,故在所有符合条件的j里,我们一定会找最大的j。因此我们可以有这段dp代码: +```cpp +for (int i=1; i<=n; i++) +{ + LL sum = nums[i]; + int j = i-1; + while (j>=0 && sum < dp[j]) + { + sum += nums[j]; + j--; + } + dp[i] = sum; + len[i] = len[j]+1; +} +return len[n]; +``` +但是这个算法的时间复杂度是o(N^2)。 + +我们将关系式`dp[j]<=dp[i]`改写为`dp[j]<=presum[i]-presum[j]`,即`presum[i] >= presum[j]+dp[j]`. 显然,我们将所有已经得到的那些映射`presum[j]+dp[j] -> j`(因为下标小于i,故是已知量),提前放入一个有序容器里,用二分搜索就可以找到对于i而言符合条件的key的范围。那么如何再找到其中最大的j呢?理论上我们需要把这些key都遍历一遍,但我们会想到一个性质:如果保证这个map不仅是按照key递增有序的、同时也是按照value递增有序的,那么我们就只需要一次二分搜索即可定位恰好小于等于presum[i]的key,那个key所对应的value就是我们想要的最大j,而不需要再遍历寻找value的最大值。 + +根据以上的数据结构,我们就可以轻松求出i所对应的j,以及dp[i]和len[i]。接下来我们需要将`presum[i]+dp[i] -> i`放入map里去。注意,我们依然想要保证map按照key和value都是递增有序的。事实上,我们将`presum[i]+dp[i]`作为key插入map之后,map里比其大的key所对应的value(也就是nums里位于i之前的index)都必然小于i,这些元素都可以从map里删去。这是因为它们的key既大(不容易让后续的presum接上),value也小(index也靠前),各方面都不及`presum[i]+dp[i] -> i`,今后注定不会被用到。将他们弹出之后,我们发现,map依然保持了我们想要的双递增的性质。 + +这样的算法时间复杂度就是o(nlogn). From 66e682aafe486538c301e341fc03ebece6367e45 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Nov 2023 22:41:01 -0800 Subject: [PATCH 2241/2729] Update Readme.md --- .../2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md index e1bafa426..18971673c 100644 --- a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md +++ b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md @@ -18,8 +18,8 @@ return len[n]; ``` 但是这个算法的时间复杂度是o(N^2)。 -我们将关系式`dp[j]<=dp[i]`改写为`dp[j]<=presum[i]-presum[j]`,即`presum[i] >= presum[j]+dp[j]`. 显然,我们将所有已经得到的那些映射`presum[j]+dp[j] -> j`(因为下标小于i,故是已知量),提前放入一个有序容器里,用二分搜索就可以找到对于i而言符合条件的key的范围。那么如何再找到其中最大的j呢?理论上我们需要把这些key都遍历一遍,但我们会想到一个性质:如果保证这个map不仅是按照key递增有序的、同时也是按照value递增有序的,那么我们就只需要一次二分搜索即可定位恰好小于等于presum[i]的key,那个key所对应的value就是我们想要的最大j,而不需要再遍历寻找value的最大值。 +我们将关系式`dp[j]<=dp[i]`改写为`dp[j]<=presum[i]-presum[j]`,即`presum[i] >= presum[j]+dp[j]`. 显然,我们将所有已经得到的那些映射`presum[j]+dp[j] -> j`(因为下标小于i,故是已知量),提前放入一个有序map里,用二分搜索就可以找到对于i而言符合条件的key的范围。那么如何再找到其中最大的j呢?理论上我们需要把这些key都遍历一遍,检查他们的value。但我们会想到一个常见的套路:如果保证这个map不仅是按照key递增有序的、同时也是按照value递增有序的,那么我们就只需要一次二分搜索即可定位恰好小于等于presum[i]的key,那个key所对应的value就是我们想要的最大j,而不需要再遍历寻找value的最大值。 -根据以上的数据结构,我们就可以轻松求出i所对应的j,以及dp[i]和len[i]。接下来我们需要将`presum[i]+dp[i] -> i`放入map里去。注意,我们依然想要保证map按照key和value都是递增有序的。事实上,我们将`presum[i]+dp[i]`作为key插入map之后,map里比其大的key所对应的value(也就是nums里位于i之前的index)都必然小于i,这些元素都可以从map里删去。这是因为它们的key既大(不容易让后续的presum接上),value也小(index也靠前),各方面都不及`presum[i]+dp[i] -> i`,今后注定不会被用到。将他们弹出之后,我们发现,map依然保持了我们想要的双递增的性质。 +根据以上的数据结构,我们就可以轻松求出i所对应的j,以及dp[i]和len[i]。接下来我们需要将`presum[i]+dp[i] -> i`放入map里去。注意,我们依然想要保证map按照key和value都是递增有序的。事实上,我们将`presum[i]+dp[i]`作为key插入map之后,map里比其大的key所对应的value都必然小于i(因为它们是nums里位于i之前的index),这些元素都可以从map里删去。这是因为它们的key既大(不容易让后续的presum接上),value也小(index也靠前),各方面都不及`presum[i]+dp[i] -> i`优秀,今后注定不会被用到。将他们弹出之后,我们发现,map依然保持了我们想要的双递增的性质。 -这样的算法时间复杂度就是o(nlogn). +故这样的算法时间复杂度就是o(nlogn). From 4ebe283487c5675fa340f04fcad1cde2cf45fc65 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 30 Nov 2023 23:41:56 -0800 Subject: [PATCH 2242/2729] Create 2949.Count-Beautiful-Substrings-II.cpp --- .../2949.Count-Beautiful-Substrings-II.cpp | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp diff --git a/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp b/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp new file mode 100644 index 000000000..2e3137521 --- /dev/null +++ b/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp @@ -0,0 +1,75 @@ +class Solution { + unordered_setSet = {'a','e','i','o','u' }; + +public: + vectorEratosthenes(int n) + { + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); + } + return primes; + } + + long long beautifulSubstrings(string s, int k) + { + vectorprimes = Eratosthenes(k); + int m = 1; + for (int p:primes) + { + int count = 0; + while (k%p==0) + { + count++; + k/=p; + } + if (count!=0 && count%2==1) + m *= pow(p, (count+1)/2); + else if (count!=0 && count%2==0) + m *= pow(p, count/2); + } + m*=2; + cout<>Map; + Map[0][(-1+m)%m]=1; + + int count = 0; + + for (int i=0; i Date: Thu, 30 Nov 2023 23:44:19 -0800 Subject: [PATCH 2243/2729] Update 2949.Count-Beautiful-Substrings-II.cpp --- .../2949.Count-Beautiful-Substrings-II.cpp | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp b/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp index 2e3137521..05068e0d1 100644 --- a/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp +++ b/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp @@ -42,17 +42,17 @@ class Solution { m *= pow(p, count/2); } m*=2; - cout<>Map; - Map[0][(-1+m)%m]=1; + Map[0][0]=1; int count = 0; - for (int i=0; i Date: Thu, 30 Nov 2023 23:44:52 -0800 Subject: [PATCH 2244/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 18e50f45f..5b7ab22fa 100644 --- a/Readme.md +++ b/Readme.md @@ -194,7 +194,8 @@ [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) [2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) [2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) -[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) +[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) +[2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From bef366e4dc2b2223a69940cd9b4d8b30ecad28ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Dec 2023 00:13:10 -0800 Subject: [PATCH 2245/2729] Create Readme.md --- Hash/2949.Count-Beautiful-Substrings-II/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Hash/2949.Count-Beautiful-Substrings-II/Readme.md diff --git a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md new file mode 100644 index 000000000..66c3d2cf3 --- /dev/null +++ b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md @@ -0,0 +1,11 @@ +### 2949.Count-Beautiful-Substrings-II + +对于求substring的问题,我们很容想到用前缀和之差来解决。显然,对于以i结尾的substring,我们想要找满足条件的起始位置j,需要满足两个条件: +1. [j+1:i]内的元音辅音个数相等 <-> [0:j]的元音辅音个数之差,需要等于[0:i]的元音辅音个数之差。 +2. [j+1:i]内的元音辅音个数乘积能被k整除 <-> `[(i-j)/2]^2 % k ==0` <-> `[(i-j)]^2 % 4k ==0` + +对于第一个条件,我们只要根据[0:i]的元音辅音个数之差(假设为d),在hash表中查找之前有多少个前缀串的元音辅音个数之差也是d。 + +对于第二个条件,理论上只要i与j关于sqrt(4k)同余,那么(i-j)就能被sqrt(4k)整除,也就是说(i-j)^2能被4k整除。但是sqrt(4k)可能不是一个整数。所以我们需要将k分解质因数,对于出现奇数次的质因子,显然我们需要再补一个该质因子以便k能被开方。我们将这样“松弛”后的k的开方结果记做m,那么我们只要i与j关于2m同余。就保证[(i-j)]^2能被4k整除。 + +于是本题的思路就是用两个key的hash,记录前缀的两个信息:元音辅音的个数之差,前缀长度关于2m的余数。对于任意的位置i,如果在hash表里能找到两个key都相同的位置j,那么[j+1:i]就是符合要求的substring。 From 18a843473c094a6e4b4a13bc4a70422a2a12c5c4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Dec 2023 00:13:44 -0800 Subject: [PATCH 2246/2729] Update Readme.md --- Hash/2949.Count-Beautiful-Substrings-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md index 66c3d2cf3..4eba9f814 100644 --- a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md +++ b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md @@ -1,7 +1,7 @@ ### 2949.Count-Beautiful-Substrings-II 对于求substring的问题,我们很容想到用前缀和之差来解决。显然,对于以i结尾的substring,我们想要找满足条件的起始位置j,需要满足两个条件: -1. [j+1:i]内的元音辅音个数相等 <-> [0:j]的元音辅音个数之差,需要等于[0:i]的元音辅音个数之差。 +1. [j+1:i]内的元音辅音个数相等 <-> [0:j]的元音辅音个数之差必须等于[0:i]的元音辅音个数之差。 2. [j+1:i]内的元音辅音个数乘积能被k整除 <-> `[(i-j)/2]^2 % k ==0` <-> `[(i-j)]^2 % 4k ==0` 对于第一个条件,我们只要根据[0:i]的元音辅音个数之差(假设为d),在hash表中查找之前有多少个前缀串的元音辅音个数之差也是d。 From 45406deb757deba44e20cd79a5623fa597f09af8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Dec 2023 00:14:30 -0800 Subject: [PATCH 2247/2729] Update Readme.md --- Hash/2949.Count-Beautiful-Substrings-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md index 4eba9f814..71075d0dd 100644 --- a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md +++ b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md @@ -8,4 +8,4 @@ 对于第二个条件,理论上只要i与j关于sqrt(4k)同余,那么(i-j)就能被sqrt(4k)整除,也就是说(i-j)^2能被4k整除。但是sqrt(4k)可能不是一个整数。所以我们需要将k分解质因数,对于出现奇数次的质因子,显然我们需要再补一个该质因子以便k能被开方。我们将这样“松弛”后的k的开方结果记做m,那么我们只要i与j关于2m同余。就保证[(i-j)]^2能被4k整除。 -于是本题的思路就是用两个key的hash,记录前缀的两个信息:元音辅音的个数之差,前缀长度关于2m的余数。对于任意的位置i,如果在hash表里能找到两个key都相同的位置j,那么[j+1:i]就是符合要求的substring。 +于是本题的思路就是建立包含两个key的hash,来记录每个前缀的两个信息:元音辅音的个数之差,前缀长度关于2m的余数。对于任意的位置i,如果在hash表里能找到两个key都相同的位置j,那么[j+1:i]就是符合要求的substring。 From 506382834bd6816392dc3bfb626c2eb637e1db0d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Dec 2023 13:39:52 -0800 Subject: [PATCH 2248/2729] Create 2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp --- ...mum-Changes-to-Make-K-Semi-palindromes.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp new file mode 100644 index 000000000..5187b418e --- /dev/null +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp @@ -0,0 +1,58 @@ +class Solution { + int range[205][205]; + int dp[205][205]; +public: + int helper(string& s, int a, int b, int d, int r) + { + int i = a+r; + int j = b-(d-r)+1; + int count = 0; + while (i Date: Sat, 2 Dec 2023 13:40:21 -0800 Subject: [PATCH 2249/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5b7ab22fa..91404e4c0 100644 --- a/Readme.md +++ b/Readme.md @@ -838,7 +838,8 @@ [2463.Minimum-Total-Distance-Traveled](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled) (M+) [2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings) (M+) [2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) -[2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) +[2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) +[2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From 4eb1dcf219dfee6038a69903cb0b042fcd3d25bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Dec 2023 13:56:32 -0800 Subject: [PATCH 2250/2729] Update 2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp --- .../2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp index 5187b418e..fca9fa085 100644 --- a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp @@ -45,7 +45,7 @@ class Solution { dp[i][1] = range[0][i]; for (int i=0; i Date: Sat, 2 Dec 2023 14:05:41 -0800 Subject: [PATCH 2251/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 91404e4c0..2a6e64773 100644 --- a/Readme.md +++ b/Readme.md @@ -839,7 +839,7 @@ [2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings) (M+) [2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) [2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) -[2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H) +[2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H-) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From fe45eb3fb13701fc6f26753246d36d501d4b835b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Dec 2023 14:29:10 -0800 Subject: [PATCH 2252/2729] Create Readme.md --- .../Readme.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md new file mode 100644 index 000000000..7a1074d14 --- /dev/null +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md @@ -0,0 +1,30 @@ +### 2911.Minimum-Changes-to-Make-K-Semi-palindromes + +要在整个字符串中分割出k个区间,显然是dp的套路。令dp[i][p]表示将前i个字符分割成符合条件的p个区间,所需要的最小改动操作。显然有: +```cpp +for (int i=0; i Date: Sat, 2 Dec 2023 14:54:54 -0800 Subject: [PATCH 2253/2729] Update 2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp --- ...mum-Changes-to-Make-K-Semi-palindromes.cpp | 47 +++++++++---------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp index fca9fa085..dddd507cd 100644 --- a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp @@ -1,15 +1,13 @@ class Solution { - int range[205][205]; - int dp[205][205]; public: - int helper(string& s, int a, int b, int d, int r) + int helper(string&s, int a, int b, int d, int r) { - int i = a+r; - int j = b-(d-r)+1; + int i = a + r; + int j = b - (d-r) + 1; int count = 0; while (i Date: Sat, 2 Dec 2023 15:43:18 -0800 Subject: [PATCH 2254/2729] Create 2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp --- ...-After-Collecting-Coins-From-All-Nodes.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp diff --git a/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp b/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp new file mode 100644 index 000000000..9238a78ac --- /dev/null +++ b/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp @@ -0,0 +1,53 @@ +class Solution { + int memo[100005][14]; + vectornext[100005]; +public: + int maximumPoints(vector>& edges, vector& coins, int k) + { + int n = edges.size()+1; + for (int i=0; i& coins, int k) + { + if (reduced >= 13) reduced = 13; + + if (memo[cur][reduced]!=INT_MIN/2) + return memo[cur][reduced]; + + int sum1 = helper(coins[cur], reduced) - k; + for (int nxt: next[cur]) + { + if (nxt == parent) continue; + sum1 += dfs(nxt, cur, reduced, coins, k); + } + + int sum2 = helper(coins[cur], reduced)/2; + for (int nxt: next[cur]) + { + if (nxt == parent) continue; + sum2 += dfs(nxt, cur, reduced+1, coins, k); + } + + memo[cur][reduced] = max(sum1, sum2); + return memo[cur][reduced]; + } +}; From 8b633f92b670576f0137394bd0e04b3aa289e45d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Dec 2023 15:43:46 -0800 Subject: [PATCH 2255/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2a6e64773..3af49b5cc 100644 --- a/Readme.md +++ b/Readme.md @@ -278,7 +278,8 @@ [2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) [2467.Most-Profitable-Path-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2467.Most-Profitable-Path-in-a-Tree) (M+) [2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) -[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) +[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) +[2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes) (H-) [2925.Maximum-Score-After-Applying-Operations-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree) (M) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) From 83935daf6b12ec6fb36cee62474d007a213bd34f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Dec 2023 00:10:16 -0800 Subject: [PATCH 2256/2729] Update Readme.md --- .../2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md index 7a1074d14..bd4b8a741 100644 --- a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md @@ -27,4 +27,4 @@ for (int i = 0; i < n; i++) } } ``` -注意,d与r的两层循环共用o(n)的复杂度。 +注意,d与r的两层循环共用o(nlogn)的复杂度。对于一个长度len,它的因子的个数有log(len)个;对于每个因子都需要把整个len长度的子串遍历一遍 From f7c3ddb7e52c3077a1afd6f3ad7885f359897ff1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 13 Dec 2023 23:43:53 -0800 Subject: [PATCH 2257/2729] Create 2963.Count-the-Number-of-Good-Partitions.cpp --- ...63.Count-the-Number-of-Good-Partitions.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Others/2963.Count-the-Number-of-Good-Partitions/2963.Count-the-Number-of-Good-Partitions.cpp diff --git a/Others/2963.Count-the-Number-of-Good-Partitions/2963.Count-the-Number-of-Good-Partitions.cpp b/Others/2963.Count-the-Number-of-Good-Partitions/2963.Count-the-Number-of-Good-Partitions.cpp new file mode 100644 index 000000000..b27db8b68 --- /dev/null +++ b/Others/2963.Count-the-Number-of-Good-Partitions/2963.Count-the-Number-of-Good-Partitions.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int numberOfGoodPartitions(vector& nums) + { + int n = nums.size(); + unordered_mapright; + for (int i=0; ileft; + for (int i=n-1; i>=0; i--) + left[nums[i]] = i; + + vectordiff(n); + for (auto [k,v]: left) + { + diff[left[k]]+=1; + diff[right[k]]-=1; + } + + int count = 0; + int sum = 0; + for (int i=0; i Date: Wed, 13 Dec 2023 23:44:21 -0800 Subject: [PATCH 2258/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3af49b5cc..3032f9cb1 100644 --- a/Readme.md +++ b/Readme.md @@ -1517,6 +1517,7 @@ [2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) [2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) [2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero) (H-) +[2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 3adcfbbc500b30b96380938bc830b5791be9bd58 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 13 Dec 2023 23:55:40 -0800 Subject: [PATCH 2259/2729] Create Readme.md --- Others/2963.Count-the-Number-of-Good-Partitions/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2963.Count-the-Number-of-Good-Partitions/Readme.md diff --git a/Others/2963.Count-the-Number-of-Good-Partitions/Readme.md b/Others/2963.Count-the-Number-of-Good-Partitions/Readme.md new file mode 100644 index 000000000..adb16048b --- /dev/null +++ b/Others/2963.Count-the-Number-of-Good-Partitions/Readme.md @@ -0,0 +1,7 @@ +### 2963.Count-the-Number-of-Good-Partitions + +根据题意,相同的数字必须在同一个subarray里。所以对于每一个数字,我们找到它在数组中最左边出现的位置L,和最右边出现的位置R,那么[L,R]这个区间必须在同一个subarray里。 + +此外,如果有两个区间(对应数字a和b)有任何程度的重合,那么这两个区间必然也在同一个subarray里,才能保证a和b不出现在其他subarray里。 + +由此根据所得到的若干个区间,我们就可以用差分数组(即扫描线)来进行合并,求得数组里有多少个互不相同的subarray,假设为n。那么这n个subarray必然是满足条件的最多分割。此外,这些subarray的任意合并也必然是满足条件的一种分割。根据插板法的道理,这样的分割数目有2^(n-1)个。 From b4ca8d63d7b03cd99dcb00e2e1dbef45846cc644 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 00:41:45 -0800 Subject: [PATCH 2260/2729] Create 2959.Number-of-Possible-Sets-of-Closing-Branches.cpp --- ...r-of-Possible-Sets-of-Closing-Branches.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/2959.Number-of-Possible-Sets-of-Closing-Branches.cpp diff --git a/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/2959.Number-of-Possible-Sets-of-Closing-Branches.cpp b/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/2959.Number-of-Possible-Sets-of-Closing-Branches.cpp new file mode 100644 index 000000000..2665fb090 --- /dev/null +++ b/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/2959.Number-of-Possible-Sets-of-Closing-Branches.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int numberOfSets(int n, int maxDistance, vector>& roads) + { + int ret = 0; + for (int state=0; state<(1<>d(n, vector(n, INT_MAX/3)); + for (int i=0; i>i)&1)==0) continue; + d[i][i] = 0; + } + + for (auto road: roads) + { + int a = road[0], b = road[1], w = road[2]; + if (((state>>a)&1)==0) continue; + if (((state>>b)&1)==0) continue; + + for (int i=0; i>i)&1)==0) continue; + for (int j=0; j>j)&1)==0) continue; + d[i][j] = min(d[i][j], d[i][a]+w+d[b][j]); + d[i][j] = min(d[i][j], d[i][b]+w+d[a][j]); + } + } + } + + int flag = 1; + for (int i=0; i>i)&1)==0) continue; + for (int j=0; j>j)&1)==0) continue; + if (d[i][j]>maxDistance) + { + flag = 0; + break; + } + } + if (flag==0) break; + } + if (flag) ret++; + } + + return ret; + } +}; From de147de47e896db841de0548f1780017d72f89ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 00:43:25 -0800 Subject: [PATCH 2261/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3032f9cb1..b002ae38d 100644 --- a/Readme.md +++ b/Readme.md @@ -1126,7 +1126,8 @@ [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) -[2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) +[2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) +[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 245f423721d55dcbba68e8e7a8dc8f06af90eab2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 00:56:26 -0800 Subject: [PATCH 2262/2729] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b002ae38d..272bf1c45 100644 --- a/Readme.md +++ b/Readme.md @@ -630,7 +630,6 @@ [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) -[2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) @@ -1124,6 +1123,9 @@ [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) +* ``Dijkstra`` +[2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) +[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From 6b5a78ad1f394cc3606f715541a470d697f4d9b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 00:57:14 -0800 Subject: [PATCH 2263/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 272bf1c45..4946a6c3c 100644 --- a/Readme.md +++ b/Readme.md @@ -629,7 +629,6 @@ [2714.Find-Shortest-Path-with-K-Hops](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2714.Find-Shortest-Path-with-K-Hops) (M+) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) -[2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) @@ -1124,6 +1123,7 @@ [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) * ``Dijkstra`` +[2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) [2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) * ``Floyd`` From 380dbf72e768d4564034c41e592ef0c62114b4ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 01:16:41 -0800 Subject: [PATCH 2264/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/Readme.md diff --git a/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/Readme.md b/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/Readme.md new file mode 100644 index 000000000..fd826991c --- /dev/null +++ b/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/Readme.md @@ -0,0 +1,15 @@ +### 2959.Number-of-Possible-Sets-of-Closing-Branches + +因为节点数目n只有10,所以我们可以暴力枚举所有的closure方案,只需要2^n不超过1024种。 + +对于每种closure的方案,我们可以用类似Floy算法的n^3的时间度算出任意两点间的最短距离(排除掉closed point),然后只需要检查是否都小于targetDistance即可。 + +Floyd松弛算法如下: +```cpp +for road : roads + int a = road[0], b = road[1], w = road[2]; + for (int i=0; i Date: Thu, 14 Dec 2023 23:15:43 -0800 Subject: [PATCH 2265/2729] Create 2957.Remove-Adjacent-Almost-Equal-Characters.cpp --- ...emove-Adjacent-Almost-Equal-Characters.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp diff --git a/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp b/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp new file mode 100644 index 000000000..04a8e4f61 --- /dev/null +++ b/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int maxSubarrayLength(vector& nums, int k) + { + int n = nums.size(); + unordered_mapcount; + int j = 0; + int ret = 0; + for (int i=0; i Date: Thu, 14 Dec 2023 23:16:20 -0800 Subject: [PATCH 2266/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4946a6c3c..a9f725eff 100644 --- a/Readme.md +++ b/Readme.md @@ -53,6 +53,7 @@ [2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) [2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) +[2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters) (M) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 44989b35f17e52d1095eec1bfe1ab639ddf8ec99 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 23:19:23 -0800 Subject: [PATCH 2267/2729] Update and rename 2957.Remove-Adjacent-Almost-Equal-Characters.cpp to 2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp --- .../2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Two_Pointers/{2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp => 2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp} (100%) diff --git a/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp b/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp similarity index 100% rename from Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp rename to Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp From 3ce37c992627463ac6d56198aff8e1336d107f1a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 23:20:29 -0800 Subject: [PATCH 2268/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a9f725eff..0d2737e32 100644 --- a/Readme.md +++ b/Readme.md @@ -53,7 +53,7 @@ [2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) [2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) -[2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters) (M) +[2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From bad0080f95ba99e222a5ddff93e220f523c12d9e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 15 Dec 2023 00:20:52 -0800 Subject: [PATCH 2269/2729] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/Readme.md diff --git a/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/Readme.md b/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/Readme.md new file mode 100644 index 000000000..ebc083552 --- /dev/null +++ b/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/Readme.md @@ -0,0 +1,3 @@ +### 2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency + +本题就是维护一个滑窗,使得滑窗内的任何元素的频次不能超过K。如果满足条件,那么就移动右边界;如果不满足,那就移动左边界。 From 515680ef69d19de0d058790e8a4394287896c9b9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 15 Dec 2023 00:40:01 -0800 Subject: [PATCH 2270/2729] Create 2957.Remove-Adjacent-Almost-Equal-Characters.cpp --- ...Remove-Adjacent-Almost-Equal-Characters.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp diff --git a/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp b/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp new file mode 100644 index 000000000..fdb7f18cd --- /dev/null +++ b/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int removeAlmostEqualCharacters(string word) + { + int n = word.size(); + int ret = 0; + for (int i=0; i Date: Fri, 15 Dec 2023 00:40:40 -0800 Subject: [PATCH 2271/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0d2737e32..4595b3e96 100644 --- a/Readme.md +++ b/Readme.md @@ -1565,6 +1565,7 @@ [2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices) (H-) [2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment) (H-) [2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) +[2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters) (M) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From 8b4f1dfc84c1f8b4339d1da8e622f7b5b1d5cb6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 15 Dec 2023 00:47:45 -0800 Subject: [PATCH 2272/2729] Create Readme.md --- .../2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md diff --git a/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md b/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md new file mode 100644 index 000000000..0d78e5541 --- /dev/null +++ b/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md @@ -0,0 +1,3 @@ +### 2957.Remove-Adjacent-Almost-Equal-Characters + +如果有三个连续的字母不满足条件(即相邻元素不是almost equal),那么我们只需要改动中间的一个字母,必然能够使其满足条件。由此可以拓展,如果有连续n个字母不满足条件,那么我们只需要每间隔一个地改动字母即可,改动的数目即是n/2. From b53d8f359c838c08dcdb5c6719640812a9b22524 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 14:58:07 -0800 Subject: [PATCH 2273/2729] Create 2968.Apply-Operations-to-Maximize-Frequency-Score.cpp --- ...Operations-to-Maximize-Frequency-Score.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp new file mode 100644 index 000000000..05e91e56e --- /dev/null +++ b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp @@ -0,0 +1,43 @@ +using LL = long long; +class Solution { + vectorpresum; +public: + int maxFrequencyScore(vector& nums, long long k) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + presum.resize(n); + for (int i=0; i&nums, LL k, int len) + { + for (int i=0; i+len<=nums.size(); i++) + { + LL m = i+len/2; + LL j = i+len-1; + LL sum1 = nums[m]*(m-i+1) - (presum[m] - (i==0?0:presum[i-1])); + LL sum2 = (presum[j] - (m==0?0:presum[m-1])) - nums[m]*(j-m+1); + if (sum1+sum2<=k) + { + return true; + } + + } + return false; + } +}; From 2cee734204f3a3686cc368dd9969b01ba8423687 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 14:58:55 -0800 Subject: [PATCH 2274/2729] Update Readme.md --- Readme.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Readme.md b/Readme.md index 4595b3e96..0b3d25ee3 100644 --- a/Readme.md +++ b/Readme.md @@ -1167,16 +1167,19 @@ [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` -[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) -[462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) -[2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) -[1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) +[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) -[2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) -[2607.Make-K-Subarray-Sums-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2607.Make-K-Subarray-Sums-Equal) (M+) +* ``Median`` +[462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) +[1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) +[2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) +[2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) +[2607.Make-K-Subarray-Sums-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2607.Make-K-Subarray-Sums-Equal) (M+) +[1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) +[2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) From 22284b401a3c99094fce50781efa87e5f9ae4583 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:00:42 -0800 Subject: [PATCH 2275/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0b3d25ee3..07441de4e 100644 --- a/Readme.md +++ b/Readme.md @@ -1172,7 +1172,7 @@ [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) -* ``Median`` +* ``Median Theorem`` [462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) From 6d7a1ea22918d304e54f723e54aeda695290ac6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:10:13 -0800 Subject: [PATCH 2276/2729] Create 1838.Frequency-of-the-Most-Frequent-Element_v1.cpp --- ...quency-of-the-Most-Frequent-Element_v1.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v1.cpp diff --git a/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v1.cpp b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v1.cpp new file mode 100644 index 000000000..a5744ea37 --- /dev/null +++ b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v1.cpp @@ -0,0 +1,29 @@ +using LL = long long; +class Solution { +public: + int maxFrequency(vector& nums, int k) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1]+nums[i]; + + int i=1; + int ret = 0; + for (int j=1; j<=n; j++) + { + while (!isOK(nums, presum, i, j, k)) + i++; + ret = max(ret, j-i+1); + } + return ret; + } + + bool isOK(vector&nums, vector&presum, int i, int j, int k) + { + LL detla = (LL)nums[j]*(j-i+1) - (presum[j] - presum[i-1]); + return detla <= k; + } +}; From 2c0913389ac4f68c0492a2f150b990bfebe0bdef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:10:24 -0800 Subject: [PATCH 2277/2729] Rename 1838.Frequency-of-the-Most-Frequent-Element.cpp to 1838.Frequency-of-the-Most-Frequent-Element_v2.cpp --- ...ent.cpp => 1838.Frequency-of-the-Most-Frequent-Element_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/{1838.Frequency-of-the-Most-Frequent-Element.cpp => 1838.Frequency-of-the-Most-Frequent-Element_v2.cpp} (100%) diff --git a/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element.cpp b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v2.cpp similarity index 100% rename from Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element.cpp rename to Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v2.cpp From a9ef19280a42252c7e477bf17308ef2431ac7e3c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:18:17 -0800 Subject: [PATCH 2278/2729] Update Readme.md --- .../1838.Frequency-of-the-Most-Frequent-Element/Readme.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/Readme.md b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/Readme.md index 2e582f017..ccc19819d 100644 --- a/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/Readme.md +++ b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/Readme.md @@ -1,8 +1,14 @@ ### 1838.Frequency-of-the-Most-Frequent-Element +#### 解法1: 首先需要明确,我们操作后最终得到的最高频率元素一定是数组中既有的元素。为什么?假设你可以通过操作,得到一个最高频率的元素是x,且x在原数组中没有出现过;那么你必然可以通过更少的一些操作,使得原数组里恰好比x小的元素y,也构造出相同的频次。因此我们不妨将nums按从小到大排序。 -那么这个最高频次的元素是什么呢?显然不一定是数组里既有的最高频次元素。我们必须逐个尝试一遍。假设我们通过不超过k次的操作,使nums[i]的频次最高,那么这些操作必然是作用在紧邻i前面的若干元素,使它们变成nums[i]。我们假设操作的范围是[j:i-1],需要的实际操作数就是```count = sum{nums[i]-nums[k]}, k=j,j+1, ... i-1``` +那么这个最高频次的元素是什么呢?显然不一定是数组里既有的最高频次元素。我们必须逐个尝试一遍。假设我们通过不超过k次的操作,使nums[i]的频次最高,那么这些操作必然是作用在紧邻i前面的若干元素,使它们都变成nums[i]。我们假设操作的范围是[j:i]。那么我们将这段区间内的数字都变成nums[i],所需要的操作就是`nums[i]*(i-j+1) - sum[j:i]`. 显然,如果我们实现准备好前缀和数组的话,那么这个操作数就可以o(1)求出。如果操作数大于k,那么我们必须将j右移减小区间,才有可能符合条件。 + +由此可以见,我们只要唯一个滑窗。对于每个i作为区间的右端点,我们不断移动左指针j使得区间[j:i]恰好符合要求,于是j-i+1就是将nums[i]为最高频次元素的次数。 + +#### 解法2: +接下来解释一种不需要presum的滑窗解法。同上,对于区间[j:i]需要的实际操作数,我们也可以写成```count = sum{nums[i]-nums[k]}, k=j,j+1, ... i-1```。 接下来我们考虑如果最终最高频次的元素是nums[i+1],那么我们如何高效地转移?假设需要操作的数的范围起点不变,即[j:i],那么总操作数的增量就是```count += (nums[i+1]-nums[i])*(i+1-j)```,也就是我们将nums[j:i-1]都变成nums[i]的基础上,再将这(i+1-j)个数都提升一个gap,变成nums[i+1]。此时如果count>k了,那么我们就要优先舍弃最前面的元素j,那么节省的操作数就是nums[i+1]-nums[j]。我们可能会舍弃若干个老元素并右移j,直至是的count<=k,那么此时我们就在题目的限制条件下,可以将nums[j:i]都变成了nums[i+1],即频次就是```i+1-j+1```. From 472d8cbf1c7f8582f08e5df8c60bc13e453e14a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:28:26 -0800 Subject: [PATCH 2279/2729] Update and rename 2968.Apply-Operations-to-Maximize-Frequency-Score.cpp to 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp --- ...Operations-to-Maximize-Frequency-Score.cpp | 43 ------------------- ...rations-to-Maximize-Frequency-Score_v2.cpp | 39 +++++++++++++++++ 2 files changed, 39 insertions(+), 43 deletions(-) delete mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp create mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp deleted file mode 100644 index 05e91e56e..000000000 --- a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp +++ /dev/null @@ -1,43 +0,0 @@ -using LL = long long; -class Solution { - vectorpresum; -public: - int maxFrequencyScore(vector& nums, long long k) - { - int n = nums.size(); - sort(nums.begin(), nums.end()); - - presum.resize(n); - for (int i=0; i&nums, LL k, int len) - { - for (int i=0; i+len<=nums.size(); i++) - { - LL m = i+len/2; - LL j = i+len-1; - LL sum1 = nums[m]*(m-i+1) - (presum[m] - (i==0?0:presum[i-1])); - LL sum2 = (presum[j] - (m==0?0:presum[m-1])) - nums[m]*(j-m+1); - if (sum1+sum2<=k) - { - return true; - } - - } - return false; - } -}; diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp new file mode 100644 index 000000000..70989f56b --- /dev/null +++ b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp @@ -0,0 +1,39 @@ +using LL = long long; +class Solution { +public: + int maxFrequencyScore(vector& nums, long long k) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1] + nums[i]; + + int left = 1, right = n; + while (left < right) + { + int mid = right-(right-left)/2; + if (isOK(nums, presum, k, mid)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool isOK(vector&nums, vectorpresum, LL k, int len) + { + int n = nums.size()-1; + for (int i=1; i+len-1<=n; i++) + { + LL m = i+len/2; + LL j = i+len-1; + LL sum1 = nums[m]*(m-i+1) - (presum[m] - presum[i-1]); + LL sum2 = (presum[j] - presum[m-1]) - nums[m]*(j-m+1); + if (sum1+sum2<=k) return true; + } + return false; + } +}; From 1d2897c486987cca2b697489b00ab9d9b1303e34 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:48:26 -0800 Subject: [PATCH 2280/2729] Create 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp --- ...rations-to-Maximize-Frequency-Score_v1.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp new file mode 100644 index 000000000..72a3937f3 --- /dev/null +++ b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { +public: + int maxFrequencyScore(vector& nums, long long k) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1] + nums[i]; + + int j = 1; + int ret = 0; + for (int i=1; i<=n; i++) + { + while (j<=n && isOK(nums, presum, i, j, k)) + { + ret = max(ret, j-i+1); + j++; + } + } + return ret; + } + + bool isOK(vector&nums, vector&presum, int i, int j, LL k) + { + int m = (i+j)/2; + LL sum1 = (presum[j]-presum[m]) - (LL)nums[m]*(j-m); + LL sum2 = (LL)nums[m]*(m-i) - (presum[m-1]-presum[i-1]); + return sum1+sum2 <= k; + } + +}; From 6a6fd7fe180787bf8d5e693ddbce136bc9aea07e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:48:43 -0800 Subject: [PATCH 2281/2729] Rename 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp to 2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp --- ...p => 2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2968.Apply-Operations-to-Maximize-Frequency-Score/{2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp => 2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp} (100%) diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp similarity index 100% rename from Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp rename to Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp From fee2f1e42e0bb8c247f896474318921811bd25a3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:48:53 -0800 Subject: [PATCH 2282/2729] Rename 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp to 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp --- ...p => 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2968.Apply-Operations-to-Maximize-Frequency-Score/{2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp => 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp} (100%) diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp similarity index 100% rename from Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp rename to Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp From 56cb1cfac509eec88f51bd0d890f980a73471f8d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:49:06 -0800 Subject: [PATCH 2283/2729] Rename 2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp to 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp --- ...p => 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2968.Apply-Operations-to-Maximize-Frequency-Score/{2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp => 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp} (100%) diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp similarity index 100% rename from Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp rename to Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp From 0d63442de14035e37975b67086fb0fb7a585e27d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:49:48 -0800 Subject: [PATCH 2284/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 07441de4e..e0c8b666b 100644 --- a/Readme.md +++ b/Readme.md @@ -54,6 +54,7 @@ [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) [2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) +[2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 78c29c38bf46150b45077a4c1bf6ee1834623251 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 22:09:47 -0800 Subject: [PATCH 2285/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/Readme.md diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/Readme.md b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/Readme.md new file mode 100644 index 000000000..f592523db --- /dev/null +++ b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/Readme.md @@ -0,0 +1,13 @@ +### 2968.Apply-Operations-to-Maximize-Frequency-Score + +#### 解法1:二分+固定滑窗 +为了通过有限的操作得到更多相等的元素,我们必然会将这些操作集中在原本已经接近的元素上。所以我们将nums排序之后,必然是选取其中的一段subarray,将其变成同一个数。显然,由中位数的性质,想将一个数组中的所有元素变成同一个元素,那么变成他们的中位数median能够使得改动之和最小。 + +我们可以二分搜索最大的subarray长度len。对于选定的len,我们在nums上走一遍固定长度的滑窗。对于每一个滑窗范围[i:j],根据median性质,我们将其变为nums[(i+j)/2]是最高效的做法。令中位数的index是m,那么我们就可以知道区间[i:j]所需要的改动就是两部分之和 `sum[m:j]-nums[m]*(j-m+1) + nums[m]*(m-i+1)-sum[i:m]`. 其中区间和可以用前缀和数组来实现。 + +如果存在一个滑窗使得其需要的改动小于等于k,那么说明len是可行的。我们可以再尝试更大的滑窗,否则尝试更小的滑窗。 + +#### 解法2:动态滑窗 +上述的思想也可以用动态滑窗来实现。固定左边界i之后,我们可以右移右边界j,直至区间[i:j]所需要的改动大于k。此时j-i就是一个可行的区间长度。然后再移动一格左边界i,找到下一个合适的j。 + +此题类似`1838.Frequency-of-the-Most-Frequent-Element` From 428e0931f786e95ad73e328f4c330e3de364aabc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 22:07:19 -0800 Subject: [PATCH 2286/2729] Update 564.Find-the-Closest-Palindrome.cpp --- .../564.Find-the-Closest-Palindrome.cpp | 160 +++++++----------- 1 file changed, 62 insertions(+), 98 deletions(-) diff --git a/String/564.Find-the-Closest-Palindrome/564.Find-the-Closest-Palindrome.cpp b/String/564.Find-the-Closest-Palindrome/564.Find-the-Closest-Palindrome.cpp index 4d25336c1..29796c550 100644 --- a/String/564.Find-the-Closest-Palindrome/564.Find-the-Closest-Palindrome.cpp +++ b/String/564.Find-the-Closest-Palindrome/564.Find-the-Closest-Palindrome.cpp @@ -2,115 +2,79 @@ class Solution { public: string nearestPalindromic(string n) { - int N=n.size(); - string s1,s2,s3; - - if (N%2==1) - { - string t=n.substr(0,N/2+1); - long long num=convert(t); - string t1,t2; - - // candidate 1 - t1 = to_string(num); - t2 = t1; - reverse(t2.begin(),t2.end()); - s1 = t1.substr(0,N/2)+t2; - - // candidate 2 - t1 = to_string(num-1); - t2=t1; - reverse(t2.begin(),t2.end()); - s2 = t1.substr(0,N/2)+t2; - - // candidate 3 - t1 = to_string(num+1); - t2=t1; - reverse(t2.begin(),t2.end()); - s3 = t1.substr(0,N/2)+t2; + string a = makeSmaller(n); + string b = makeGreater(n); + if (stoll(b)-stoll(n) >= stoll(n)-stoll(a)) + return a; + else + return b; + } - cout<= 0; i--) { - string t=n.substr(0,N/2); - long long num=convert(t); - string t1,t2; - - //candidate 1 - t1 = n.substr(0,N/2); - reverse(t1.begin(),t1.end()); - s1 = to_string(num)+t1; - - //candidate 2 - t1 = to_string(num-1); - if (t1=="0") - s2="9"; - else if (t1.size()==t.size()) + int d = s[i]-'0'-carry; + if (d>=0) { - t2=t1; - reverse(t2.begin(),t2.end()); - s2=t1+t2; + s[i] = '0'+d; + carry = 0; } - else if (t1.size()!=t.size()) + else { - t2=t1; - reverse(t2.begin(),t2.end()); - s2=t1+'9'+t2; + s[i] = '9'; + carry = 1; } - - //candidate 3 - t1 = to_string(num+1); - if (t1.size()==t.size()) + s[m-1-i] = s[i]; + } + if (s[0]=='0' && m>1) + return string(m - 1, '9'); + else + return s; + } + + string makeGreater(const string &n) + { + const int m = n.length(); + string s = n; + for (int i = 0, j = m - 1; i <= j;) + s[j--] = s[i++]; + if (s > n) { + return s; + } + + int carry = 1; + for (int i = (m - 1)/2; i >= 0; i--) + { + int d = s[i]-'0'+carry; + if (d<=9) { - t2=t1; - reverse(t2.begin(),t2.end()); - s3=t1+t2; + s[i] = '0'+d; + carry = 0; } - else if (t1.size()!=t.size()) + else { - t2=t1; - reverse(t2.begin(),t2.end()); - t1.pop_back(); - s3=t1+t2; + s[i] = '0'; + carry = 1; } - - cout< Date: Mon, 18 Dec 2023 22:25:50 -0800 Subject: [PATCH 2287/2729] Update Readme.md --- String/564.Find-the-Closest-Palindrome/Readme.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/String/564.Find-the-Closest-Palindrome/Readme.md b/String/564.Find-the-Closest-Palindrome/Readme.md index df47c02e5..d250f422c 100644 --- a/String/564.Find-the-Closest-Palindrome/Readme.md +++ b/String/564.Find-the-Closest-Palindrome/Readme.md @@ -2,15 +2,17 @@ 这是一道比较难的题目。 -看到题目最直观的想法是,将数字的前半部分翻转后拼接到后半部分,比如说12345,那么我们就找12321. +看到题目最直观的想法是,想要尽量接近原数,那就保持高位不变,将数字的前半部分翻转后拼接到后半部分,比如说12345,那么我们就找12321,它必然是回文数。 -但是这样的策略不是万能的,因为找到不一定是离原数最接近的。比如12399,如果我们选择直接翻转,12321就不是最优解,最优解应该是12421. 再比如19200,直接翻转的19291不是最优解,最优解是19191. 那么我们就可以见端倪了,对于形如ABCXX的形式,我们应该在ABCBA,AB(C+1)BA,AB(C-1)BA之间选择一个最接近原数的就可以了。同理,对于ABXX的形式,我们采用类似的加一减一再复制翻转的方式,于是就应该在ABBA,A(B+1)(B+1)A,A(B-1)(B-1)A之间选择一个最接近原数的。 +但是这样的策略找到不一定是离原数最接近的。比如12399,如果我们选择直接翻转,12321就不是最优解,最优解应该是12421. 再比如19200,直接翻转的19291不是最优解,最优解是19191. 总之,直接翻转的策略,我们无法确定得到的是next greater palindrome,还是next smaller palindrome。而closest palindrome可能是两者的任意一个。于是这道题其实就转换成了分别求next greater palindrome和next smaller palindrome的问题。 -但这样的话,又会有个问题,例如12088,中间的0如果减去1的话就变成9了,翻转复制就成了12921和,这与原数相差也太大了.所以我们改进上面的方法,不再只对中间的数字加减,而是对前三位120整体做加减,然后复制翻转拼接(合并掉中间一位以保证仍然是奇数位),得到11911,12021,12121.那么我们对于偶数位也采取相同的方法,例如2088,我们对20整体进行加减操作,然后复制翻转拼接(不用合并掉中间一位,因为期望仍然是偶数位),得到1991,2002,2112. +根据以上的例子,我们发现如果“直接翻转”得到的是next greater palindrome,那么我们想求next smaller palindrome的话,就需要将数字的前半部分减一后再翻转。对于形如ABCXX的奇数长度形式,它的next smaller palindrome就是(ABC-1)再对称翻转(总长度不变);同理,对于形如ABCXXX的偶数长度形式,它的next smaller palindrome也是(ABC-1)再对称翻转(总长度不变)。 -但是,如果遇到加减之后位数变化的情况怎么办呢?比如10001,我们对前三位100减1之后得到的99,复制翻转拼接之后得到的999,位数一下子就少了两位.类似的对于999,我们如果对于前两位99加一变成100,复制翻转拼接后变成10001,位数一下子就多了两位.类似的情况对于偶数位的数字也会出现.怎么办呢?方案是,我们照做不误,反正最后筛查所有候选答案的时候,这些偏差太大的候选人一定会被去掉的.但是,我们需要同时考虑到这种位数变化的情况,所以干脆也加入到候选者来.比如给出的某个n位数,那么我们就把n+1位数的100...0001直接放入候选,n-1位数的99...99也直接放入候选. +类似地,发现如果“直接翻转”得到的是next smaller palindrome,那么我们想求next greater palindrome的话,就需要将数字的前半部分加一后再翻转。对于形如ABCXX的奇数长度形式,它的next greater palindrome就是(ABC+1)再对称翻转(注意翻转轴,要保持总长度不变);同理,对于形如ABCXXX的偶数长度形式,它的next greater palindrome也是(ABC+1)再对称翻转(注意翻转轴,要保持总长度不变)。 -综上,我们有了得到五个候选人的方案,最后筛查一下.去除不是回文数的(注意有可能候选人不是回文数),选取和原数最接近的就是答案了. +但是,如果遇到加减之后位数变化的情况怎么办呢?比如10001,我们对前三位100减1之后得到的99,复制翻转拼接之后得到的999,位数一下子就少了两位.类似的对于999,我们如果对于前两位99加一变成100,复制翻转拼接后变成10001,位数一下子就多了两位.类似的情况对于偶数位的数字也会出现.怎么办呢?假设原数是n位数,对于这种位数加一会导致位数变化的情况,那么我们就直接返回n+1位数的100...0001;如果减一会导致位数变化的情况,那么我们就直接返回n-1位数的99...99。 +综上,我们有了next greater palindrome和next smaller palindrome,选取和原数最接近的就是答案了. -[Leetcode Link](https://leetcode.com/problems/find-the-closest-palindrome) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/find-the-closest-palindrome) From cc4b3da9684dd516766279df270864cfc78d5808 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 22:25:58 -0800 Subject: [PATCH 2288/2729] Update Readme.md --- String/564.Find-the-Closest-Palindrome/Readme.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/String/564.Find-the-Closest-Palindrome/Readme.md b/String/564.Find-the-Closest-Palindrome/Readme.md index d250f422c..93c663229 100644 --- a/String/564.Find-the-Closest-Palindrome/Readme.md +++ b/String/564.Find-the-Closest-Palindrome/Readme.md @@ -1,7 +1,5 @@ ### 564.Find-the-Closest-Palindrome -这是一道比较难的题目。 - 看到题目最直观的想法是,想要尽量接近原数,那就保持高位不变,将数字的前半部分翻转后拼接到后半部分,比如说12345,那么我们就找12321,它必然是回文数。 但是这样的策略找到不一定是离原数最接近的。比如12399,如果我们选择直接翻转,12321就不是最优解,最优解应该是12421. 再比如19200,直接翻转的19291不是最优解,最优解是19191. 总之,直接翻转的策略,我们无法确定得到的是next greater palindrome,还是next smaller palindrome。而closest palindrome可能是两者的任意一个。于是这道题其实就转换成了分别求next greater palindrome和next smaller palindrome的问题。 From fbf9677d54e76a74fd09d906b133f8d0bfb574a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 23:28:55 -0800 Subject: [PATCH 2289/2729] Create 2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp --- ...nimum-Cost-to-Make-Array-Equalindromic.cpp | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp diff --git a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp new file mode 100644 index 000000000..8fb9a7674 --- /dev/null +++ b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp @@ -0,0 +1,99 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(vector& nums) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + int m; + if (n%2==1) + m = nums[n/2]; + else + m = (nums[n/2-1]+nums[n/2])/2; + + string a = nextSmaller(to_string(m)); + string b = nextGreater(to_string(m)); + + LL ret = LLONG_MAX; + ret = min(ret, check(nums, stoll(a))); + ret = min(ret, check(nums, stoll(b))); + + return ret; + } + + string nextSmaller(const string &n) + { + const int m = n.length(); + string s = n; + for (int i = 0, j = m - 1; i <= j;) + s[j--] = s[i++]; + if (s <= n) { + return s; + } + + int carry = 1; + for (int i = (m - 1)/2; i >= 0; i--) + { + int d = s[i]-'0'-carry; + if (d>=0) + { + s[i] = '0'+d; + carry = 0; + } + else + { + s[i] = '9'; + carry = 1; + } + s[m-1-i] = s[i]; + } + if (s[0]=='0' && m>1) + return string(m - 1, '9'); + else + return s; + } + + string nextGreater(const string &n) + { + const int m = n.length(); + string s = n; + for (int i = 0, j = m - 1; i <= j;) + s[j--] = s[i++]; + if (s >= n) { + return s; + } + + int carry = 1; + for (int i = (m - 1)/2; i >= 0; i--) + { + int d = s[i]-'0'+carry; + if (d<=9) + { + s[i] = '0'+d; + carry = 0; + } + else + { + s[i] = '0'; + carry = 1; + } + s[m-1-i] = s[i]; + } + if (carry == 1) + { + s = string(m + 1, '0'); + s[0] = s.back() = '1'; + return s; + } + else + return s; + } + + LL check(vector&nums, LL x) + { + LL sum = 0; + for (int i=0; i Date: Mon, 18 Dec 2023 23:29:23 -0800 Subject: [PATCH 2290/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e0c8b666b..f7ee23160 100644 --- a/Readme.md +++ b/Readme.md @@ -1180,6 +1180,7 @@ [2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) [2607.Make-K-Subarray-Sums-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2607.Make-K-Subarray-Sums-Equal) (M+) [1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) +[2967.Minimum-Cost-to-Make-Array-Equalindromic](https://github.com/wisdompeak/LeetCode/tree/master/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic) (H-) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) From 4ce0f81345572f023d8e8e1f3996004b7673d738 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 23:47:56 -0800 Subject: [PATCH 2291/2729] Create Readme.md --- Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md diff --git a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md new file mode 100644 index 000000000..a64c20ad1 --- /dev/null +++ b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md @@ -0,0 +1,5 @@ +### 2967.Minimum-Cost-to-Make-Array-Equalindromic + +根据中位数定理,Make Array Equal的最小代价就是将所有元素变成数组里的中位数(median)。本题中,我们的目标就是找到最接近中位数的回文数。可以借鉴`564. Find the Closest Palindrome`的算法,求得中位数M的next greater palindrome和next smaller palinedrome,然后选取两者较小的代价即可。 + +特别注意,单纯找nearest palinedrome是不对的。当next greater palindrome和next smaller palinedrome相等时,并不是取任意一个都是最小代价。 From d5bbc7d21a821acf382742f78166d6b803c98846 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 23:51:15 -0800 Subject: [PATCH 2292/2729] Update Readme.md --- Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md index a64c20ad1..93062ba42 100644 --- a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md +++ b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md @@ -2,4 +2,4 @@ 根据中位数定理,Make Array Equal的最小代价就是将所有元素变成数组里的中位数(median)。本题中,我们的目标就是找到最接近中位数的回文数。可以借鉴`564. Find the Closest Palindrome`的算法,求得中位数M的next greater palindrome和next smaller palinedrome,然后选取两者较小的代价即可。 -特别注意,单纯找nearest palinedrome是不对的。当next greater palindrome和next smaller palinedrome相等时,并不是取任意一个都是最小代价。 +特别注意,单纯找nearest palinedrome是不对的。next greater palindrome和next smaller palinedrome相比,并不是更接近M就更好,而是与array里元素的分布有关。 From 5eee049491b3fb85a97b95064b0d3a1c6498d25d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Dec 2023 00:08:39 -0800 Subject: [PATCH 2293/2729] Update 2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp --- ...nimum-Cost-to-Make-Array-Equalindromic.cpp | 92 +++++++++---------- 1 file changed, 44 insertions(+), 48 deletions(-) diff --git a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp index 8fb9a7674..297fe86d4 100644 --- a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp +++ b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp @@ -1,43 +1,47 @@ -using LL = long long; class Solution { public: long long minimumCost(vector& nums) - { - int n = nums.size(); - sort(nums.begin(), nums.end()); - int m; - if (n%2==1) - m = nums[n/2]; - else - m = (nums[n/2-1]+nums[n/2])/2; - - string a = nextSmaller(to_string(m)); - string b = nextGreater(to_string(m)); + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + int m; + if (n%2==1) + m = nums[n/2]; + else + m = (nums[n/2] + nums[n/2-1])/2; - LL ret = LLONG_MAX; + string a = nextSmallerOrEqual(to_string(m)); + string b = nextGreaterOrEqual(to_string(m)); + + long long ret = LLONG_MAX; ret = min(ret, check(nums, stoll(a))); ret = min(ret, check(nums, stoll(b))); - return ret; } - - string nextSmaller(const string &n) + + long long check(vector& nums, long long p) + { + long long sum = 0; + for (int i=0; i= 0; i--) + for (int i=(m-1)/2; i>=0; i--) { - int d = s[i]-'0'-carry; - if (d>=0) + int d = s[i] - '0' - carry; + if (d>=0) { - s[i] = '0'+d; + s[i] = '0' + d; carry = 0; } else @@ -47,29 +51,28 @@ class Solution { } s[m-1-i] = s[i]; } - if (s[0]=='0' && m>1) - return string(m - 1, '9'); + + if (s[0] == '0' && m>1) + return string(m-1, '9'); else return s; } - string nextGreater(const string &n) + string nextGreaterOrEqual(string n) { - const int m = n.length(); + int m = n.size(); string s = n; - for (int i = 0, j = m - 1; i <= j;) - s[j--] = s[i++]; - if (s >= n) { - return s; - } + for (int i=0, j=m-1; i<=j; ) + s[j--] = s[i++]; + if (s >= n) return s; int carry = 1; - for (int i = (m - 1)/2; i >= 0; i--) + for (int i=(m-1)/2; i>=0; i--) { - int d = s[i]-'0'+carry; - if (d<=9) + int d = s[i] - '0' + carry; + if (d<=9) { - s[i] = '0'+d; + s[i] = '0' + d; carry = 0; } else @@ -79,21 +82,14 @@ class Solution { } s[m-1-i] = s[i]; } + if (carry == 1) { - s = string(m + 1, '0'); + s = string(m+1, '0'); s[0] = s.back() = '1'; return s; } else return s; } - - LL check(vector&nums, LL x) - { - LL sum = 0; - for (int i=0; i Date: Tue, 19 Dec 2023 23:21:31 -0800 Subject: [PATCH 2294/2729] Create 2952.Minimum-Number-of-Coins-to-be-Added.cpp --- ...52.Minimum-Number-of-Coins-to-be-Added.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Thinking/2952.Minimum-Number-of-Coins-to-be-Added/2952.Minimum-Number-of-Coins-to-be-Added.cpp diff --git a/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/2952.Minimum-Number-of-Coins-to-be-Added.cpp b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/2952.Minimum-Number-of-Coins-to-be-Added.cpp new file mode 100644 index 000000000..700310b4e --- /dev/null +++ b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/2952.Minimum-Number-of-Coins-to-be-Added.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int minimumAddedCoins(vector& coins, int target) + { + sort(coins.begin(), coins.end()); + int limit = 0; + int i = 0; + int ret = 0; + while (limit < target) + { + if (i==coins.size() || limit+1 < coins[i]) + { + ret++; + limit += limit+1; + } + else + { + limit += coins[i]; + i++; + } + } + + return ret; + } +}; From a3b2fecef2baca012719ba158f14d46d3578edb0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Dec 2023 23:24:44 -0800 Subject: [PATCH 2295/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index f7ee23160..be0f02aac 100644 --- a/Readme.md +++ b/Readme.md @@ -1413,7 +1413,6 @@ [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) [2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) [2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) -[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) [2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) @@ -1571,6 +1570,8 @@ [2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment) (H-) [2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) [2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters) (M) +[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) +[2952.Minimum-Number-of-Coins-to-be-Added](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2952.Minimum-Number-of-Coins-to-be-Added) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From a1af02382e0fab06db3ac9d075ac79126d7ff9df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Dec 2023 23:38:50 -0800 Subject: [PATCH 2296/2729] Create Readme.md --- Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md diff --git a/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md new file mode 100644 index 000000000..970b1cf9c --- /dev/null +++ b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md @@ -0,0 +1,5 @@ +### 2952.Minimum-Number-of-Coins-to-be-Added + +将所有的coins排序后,假设当前已有的硬币能够组成任意[0, limit]之间的面额,那么又得到一枚面值是x的硬币,此时能够组成多少种面额呢?显然,当新硬币不用时,我们依然能构造出[0, limit];当使用新硬币时,我们可以构造出[x, limit+x]。当这两段区间不连接时,即`limit+1=x`时,则意味着我们可以构造出任意[0,limit+x]区间内的面额。 + +此题和`1798.Maximum-Number-of-Consecutive-Values-You-Can-Make`非常相似。 From 3c9ade0b1c86387c4254d9c5d7badcd6d080c855 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 18:15:27 -0800 Subject: [PATCH 2297/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index be0f02aac..8e3af90f9 100644 --- a/Readme.md +++ b/Readme.md @@ -1242,7 +1242,6 @@ [665.Non-decreasing-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/665.Non-decreasing-Array) (H) 670.Maximum-Swap (M+) 649.Dota2-Senate (H) -[330.Patching-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/330.Patching-Array) (H) [683.K-Empty-Slots](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/683.K-Empty-Slots) (H) [517.Super-Washing-Machines](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/517.Super-Washing-Machines) (H) 870.Advantage-Shuffle (M) @@ -1570,6 +1569,7 @@ [2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment) (H-) [2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) [2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters) (M) +[330.Patching-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/330.Patching-Array) (H) [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2952.Minimum-Number-of-Coins-to-be-Added](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2952.Minimum-Number-of-Coins-to-be-Added) (H-) From 90a6b9d6f0a1d23b5c52071db639c4eeb226af8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 18:15:53 -0800 Subject: [PATCH 2298/2729] Update Readme.md --- Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md index 970b1cf9c..e89c2d779 100644 --- a/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md +++ b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md @@ -2,4 +2,4 @@ 将所有的coins排序后,假设当前已有的硬币能够组成任意[0, limit]之间的面额,那么又得到一枚面值是x的硬币,此时能够组成多少种面额呢?显然,当新硬币不用时,我们依然能构造出[0, limit];当使用新硬币时,我们可以构造出[x, limit+x]。当这两段区间不连接时,即`limit+1=x`时,则意味着我们可以构造出任意[0,limit+x]区间内的面额。 -此题和`1798.Maximum-Number-of-Consecutive-Values-You-Can-Make`非常相似。 +此题和`330.Patching-Array`和`1798.Maximum-Number-of-Consecutive-Values-You-Can-Make`非常相似。 From 23692e2b90bc05431a6030103de22c6cb42bacc3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 18:18:24 -0800 Subject: [PATCH 2299/2729] Create 2953.Count-Complete-Substrings.cpp --- .../2953.Count-Complete-Substrings.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp diff --git a/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp b/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp new file mode 100644 index 000000000..04f028500 --- /dev/null +++ b/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + int countCompleteSubstrings(string word, int k) + { + int n = word.size(); + int ret = 0; + for (int i=0; i& freq, int k) + { + for (int x: freq) + { + if (x != k && x != 0) + return false; + } + return true; + } + + int helper(string s, int k) + { + int count = 0; + setSet(s.begin(), s.end()); + for (int T = 1; T <= Set.size(); T++) + { + int length = T * k; + vectorfreq(26,0); + int start = 0; + int end = start + length - 1; + for (int i = start; i <= min(end, (int)s.size() - 1); i++) + { + freq[s[i]-'a']++; + } + while (end < s.size()) + { + if (check(freq, k)) count++; + freq[s[start]-'a']--; + start++; + end++; + if (end < s.size()) freq[s[end]-'a']++; + } + } + + return count; + } +}; From 7d48d822e8446ab0362037301998d0425ecd52b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 18:22:32 -0800 Subject: [PATCH 2300/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8e3af90f9..4a20d8a47 100644 --- a/Readme.md +++ b/Readme.md @@ -53,6 +53,7 @@ [2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) [2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) +[2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) * ``Sliding window : Distinct Characters`` From ac51b29cbf5a372cccb222633741d293a2b48adc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 20:48:28 -0800 Subject: [PATCH 2301/2729] Create Readme.md --- Two_Pointers/2953.Count-Complete-Substrings/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2953.Count-Complete-Substrings/Readme.md diff --git a/Two_Pointers/2953.Count-Complete-Substrings/Readme.md b/Two_Pointers/2953.Count-Complete-Substrings/Readme.md new file mode 100644 index 000000000..19d1b846e --- /dev/null +++ b/Two_Pointers/2953.Count-Complete-Substrings/Readme.md @@ -0,0 +1,5 @@ +### 2953.Count-Complete-Substrings + +很显然,第一步是将原字符串切割成若干个区间,我们只考虑那些“相邻字符大小不超过2”的那些区间. + +接下来,我们需要计算每个通过初筛区间里,再有多少个符合条件的substring,即要求substring里出现的字符的频次都是k。我们注意到字符的种类只有26种,如果只出现一种字符,那长度就是k;如果出现两种字符,那长度就是2k,以此类推,我们发现可以遍历出现字符的种类数目,然后用一个固定长度的滑窗来判定是否存在substring符合条件。滑窗的运动过程中,只要维护一个hash表即可。 From b0548a7d746d3971366a9ff2cb4b7758b8822193 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 21:06:51 -0800 Subject: [PATCH 2302/2729] Create 2954.Count-the-Number-of-Infection-Sequences.cpp --- ...ount-the-Number-of-Infection-Sequences.cpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp diff --git a/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp b/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp new file mode 100644 index 000000000..5306debae --- /dev/null +++ b/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp @@ -0,0 +1,80 @@ +using LL = long long; +class Solution { + LL power[100005]; + LL fact[100005]; + LL M = 1e9+7; + LL mod = 1e9+7; +public: + int numberOfSequence(int n, vector& sick) + { + power[0] = 1; + for (int i=1; i<=n; i++) + power[i] = power[i-1]*2 % M; + + fact[0] = 1; + for (int i=1; i<=n; i++) + fact[i] = fact[i-1]*i % M; + + vectorgroups; + for (int i=0; i0) + groups.push_back(sick[i]-sick[i-1]-1); + } + + } + if (sick.back()!=n-1) + groups.push_back(n-1-sick.back()); + + // for (int x: groups) cout<0) + ret = ret * power[x-1] % M; + } + + return ret; + } + + LL quickPow(LL x, LL y) + { + LL ret = 1; + LL cur = x; + while (y) + { + if (y & 1) + { + ret = (LL)ret * cur % mod; + } + cur = (LL)cur * cur % mod; + y >>= 1; + } + return ret; + } + + LL inv(LL x) + { + return quickPow(x, mod - 2); + } +}; From 31b03da5f0c5f9cab909c539253f0fbac4b57cf5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 21:07:19 -0800 Subject: [PATCH 2303/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4a20d8a47..8d553cdb8 100644 --- a/Readme.md +++ b/Readme.md @@ -1222,6 +1222,7 @@ [2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) [2539.Count-the-Number-of-Good-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2539.Count-the-Number-of-Good-Subsequences) (H-) [2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) +[2954.Count-the-Number-of-Infection-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2954.Count-the-Number-of-Infection-Sequences) (H) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From 303679d263ded7ec238009683f67987d2dbbab95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 23:17:14 -0800 Subject: [PATCH 2304/2729] Update 2953.Count-Complete-Substrings.cpp --- .../2953.Count-Complete-Substrings.cpp | 41 +++++++++---------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp b/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp index 04f028500..0022c9b9e 100644 --- a/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp +++ b/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp @@ -15,40 +15,37 @@ class Solution { return ret; } - bool check(vector& freq, int k) - { - for (int x: freq) - { - if (x != k && x != 0) - return false; - } - return true; - } - int helper(string s, int k) { int count = 0; setSet(s.begin(), s.end()); for (int T = 1; T <= Set.size(); T++) { - int length = T * k; + int len = T * k; vectorfreq(26,0); - int start = 0; - int end = start + length - 1; - for (int i = start; i <= min(end, (int)s.size() - 1); i++) - { - freq[s[i]-'a']++; - } - while (end < s.size()) + int j = 0; + for (int i=0; i+len-1& freq, int k) + { + for (int x: freq) + { + if (x != k && x != 0) + return false; + } + return true; + } }; From d5f73945241b68ca7a4e27da0c3f1acc74fd7776 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 21 Dec 2023 01:24:00 -0800 Subject: [PATCH 2305/2729] Update 2954.Count-the-Number-of-Infection-Sequences.cpp --- ...ount-the-Number-of-Infection-Sequences.cpp | 35 +++++-------------- 1 file changed, 9 insertions(+), 26 deletions(-) diff --git a/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp b/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp index 5306debae..8e12fe726 100644 --- a/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp +++ b/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp @@ -2,56 +2,39 @@ using LL = long long; class Solution { LL power[100005]; LL fact[100005]; - LL M = 1e9+7; LL mod = 1e9+7; public: int numberOfSequence(int n, vector& sick) { power[0] = 1; for (int i=1; i<=n; i++) - power[i] = power[i-1]*2 % M; + power[i] = power[i-1]*2 % mod; fact[0] = 1; for (int i=1; i<=n; i++) - fact[i] = fact[i-1]*i % M; + fact[i] = fact[i-1]*i % mod; vectorgroups; for (int i=0; i0) - groups.push_back(sick[i]-sick[i-1]-1); - } - + groups.push_back(sick[i]-sick[i-1]-1); } - if (sick.back()!=n-1) - groups.push_back(n-1-sick.back()); - - // for (int x: groups) cout<0) - ret = ret * power[x-1] % M; + ret = ret * power[x-1] % mod; } return ret; From feba85d4f65a28c17628cd0ab95b598cc551b9ed Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 21 Dec 2023 23:59:47 -0800 Subject: [PATCH 2306/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Math/2954.Count-the-Number-of-Infection-Sequences/Readme.md diff --git a/Math/2954.Count-the-Number-of-Infection-Sequences/Readme.md b/Math/2954.Count-the-Number-of-Infection-Sequences/Readme.md new file mode 100644 index 000000000..f0f783c25 --- /dev/null +++ b/Math/2954.Count-the-Number-of-Infection-Sequences/Readme.md @@ -0,0 +1,15 @@ +### 2954.Count-the-Number-of-Infection-Sequences + +对于两个相邻sick点之间的区间,他们被感染的次序看似很复杂,其实无非就是“感染左端点”和“感染右端点”两个选择里的随机选取。因此任意一个感染序列,都对应了一种LR的二值序列。假设区间内未被感染的点有m个,那么感染过程的序列种类(即排列)就是`2^(m-1)`。为什么是m-1?因为当只剩最后一个未感染点时,“感染左端点”和“感染右端点”这两个选择对应是同一个点。 + +此外需要注意,如果只有单边存在sick的区间(比如第一个区间或者最后一个区间),它的序列种类只有1. + +以上是一个区间的种类数。那么如何计算所有点的总的序列种类呢?假设前述的区间m1,m2,...mk的总数是n,那么这n个点的随机排列是n!种。但是,对于属于某个特定区间的点而言(比如说属于第k个区间的mk个点),它的顺序不应该是完全随机的,随意我们要再除以mk的阶乘抵消这种随机性。但是属于第k区间的点肯定也不是只有一种排列,而是有`2^(mk-1)`种方法(如果是单边存在sick的区间,那就只是1种),故需要再乘以该区间内点的排列数。 + +所以这道题的答案是 +``` +ret = n!; +for (int i=0; i Date: Fri, 22 Dec 2023 00:08:09 -0800 Subject: [PATCH 2307/2729] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8d553cdb8..98de6d08e 100644 --- a/Readme.md +++ b/Readme.md @@ -1128,7 +1128,6 @@ * ``Dijkstra`` [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) -[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From c1481a242141d5f043d67d030c88a5cac2e8f369 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 22 Dec 2023 23:15:05 -0800 Subject: [PATCH 2308/2729] Create 2950.Number-of-Divisible Substrings.cpp --- .../2950.Number-of-Divisible Substrings.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp diff --git a/Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp b/Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp new file mode 100644 index 000000000..039eda813 --- /dev/null +++ b/Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int countDivisibleSubstrings(string word) + { + int n = word.size(); + word = "#"+word; + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1] + ((word[i]-'a'+1)/3+1); + + map>Map; + for (int m=1; m<=9; m++) + Map[m][0] = 1; + + int ret = 0; + for (int j=1; j<=n; j++) + { + for (int m = 1; m <=9; m++) + { + int key = presum[j] - m*j; + if (Map.find(m)!=Map.end() && Map[m].find(key)!=Map[m].end()) + ret += Map[m][key]; + Map[m][key]+=1; + } + } + + return ret; + } +}; From 9befe5f8bd4eee6feb4a7b3ba37ec6010e65310f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 22 Dec 2023 23:15:33 -0800 Subject: [PATCH 2309/2729] Rename 2950.Number-of-Divisible Substrings.cpp to 2950.Number-of-Divisible-Substrings.cpp --- .../2950.Number-of-Divisible-Substrings.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hash/{2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp => 2950.Number-of-Divisible-Substrings/2950.Number-of-Divisible-Substrings.cpp} (100%) diff --git a/Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp b/Hash/2950.Number-of-Divisible-Substrings/2950.Number-of-Divisible-Substrings.cpp similarity index 100% rename from Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp rename to Hash/2950.Number-of-Divisible-Substrings/2950.Number-of-Divisible-Substrings.cpp From c1da42fe769aa1ebf8655138534cd1270df2cade Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 22 Dec 2023 23:16:02 -0800 Subject: [PATCH 2310/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 98de6d08e..08192c33f 100644 --- a/Readme.md +++ b/Readme.md @@ -199,6 +199,7 @@ [2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) [2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) [2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) +[2950.Number-of-Divisible-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2950.Number-of-Divisible-Substrings) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From 2d01807ee13d52d65beda78b37c589ee98139279 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Dec 2023 00:07:05 -0800 Subject: [PATCH 2311/2729] Create Readme.md --- Hash/2950.Number-of-Divisible-Substrings/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hash/2950.Number-of-Divisible-Substrings/Readme.md diff --git a/Hash/2950.Number-of-Divisible-Substrings/Readme.md b/Hash/2950.Number-of-Divisible-Substrings/Readme.md new file mode 100644 index 000000000..af0d0833b --- /dev/null +++ b/Hash/2950.Number-of-Divisible-Substrings/Readme.md @@ -0,0 +1,9 @@ +### 2950.Number-of-Divisible-Substrings + +此题有精彩的o(N)解法。 + +对于以j为结尾的substring,我们希望找到位置i Date: Sat, 23 Dec 2023 23:37:10 -0800 Subject: [PATCH 2312/2729] Create 2976.Minimum-Cost-to-Convert-String-I.cpp --- .../2976.Minimum-Cost-to-Convert-String-I.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Graph/2976.Minimum-Cost-to-Convert-String-I/2976.Minimum-Cost-to-Convert-String-I.cpp diff --git a/Graph/2976.Minimum-Cost-to-Convert-String-I/2976.Minimum-Cost-to-Convert-String-I.cpp b/Graph/2976.Minimum-Cost-to-Convert-String-I/2976.Minimum-Cost-to-Convert-String-I.cpp new file mode 100644 index 000000000..ff79a197a --- /dev/null +++ b/Graph/2976.Minimum-Cost-to-Convert-String-I/2976.Minimum-Cost-to-Convert-String-I.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { + LL d[26][26]; +public: + long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) + { + for (int i=0; i<26; i++) + for (int j=0; j<26; j++) + { + if (i!=j) + d[i][j] = LLONG_MAX/3; + else + d[i][j] = 0; + } + + + for (int i=0; i Date: Sat, 23 Dec 2023 23:37:51 -0800 Subject: [PATCH 2313/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 08192c33f..f5bdb71a9 100644 --- a/Readme.md +++ b/Readme.md @@ -1132,7 +1132,8 @@ * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) -[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) +[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) +[2976.Minimum-Cost-to-Convert-String-I](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2976.Minimum-Cost-to-Convert-String-I) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 00b9e1aa67a6e366ae01a6db7ea0b0030d65a664 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Dec 2023 23:41:04 -0800 Subject: [PATCH 2314/2729] Create Readme.md --- Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md diff --git a/Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md b/Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md new file mode 100644 index 000000000..c7ae1adf4 --- /dev/null +++ b/Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md @@ -0,0 +1,3 @@ +### 2976.Minimum-Cost-to-Convert-String-I + +此题就是求最短路径的模板题。题目给出了一系列“字符到字符的变化”,其cost相当于节点到节点的边权。最终,题目要求所有指定变化的最小代价和,即对应顶点之间最短距离的和。 From 1cf77096edea3220fe3cfefe1bbaa7b9dcbc6c07 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Dec 2023 23:43:46 -0800 Subject: [PATCH 2315/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index f5bdb71a9..4b8b582c9 100644 --- a/Readme.md +++ b/Readme.md @@ -1132,7 +1132,7 @@ * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) -[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) +[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) [2976.Minimum-Cost-to-Convert-String-I](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2976.Minimum-Cost-to-Convert-String-I) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) From 19ce8c66a8c8962cad7754706bbaca0ee99282de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:04:47 -0800 Subject: [PATCH 2316/2729] Create 2977.Minimum-Cost-to-Convert-String-II.cpp --- ...2977.Minimum-Cost-to-Convert-String-II.cpp | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp new file mode 100644 index 000000000..573244ad0 --- /dev/null +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp @@ -0,0 +1,102 @@ +using LL = long long; +class TrieNode +{ + public: + TrieNode* next[26]; + int idx; + TrieNode() + { + for (int i=0; i<26; i++) + next[i] = NULL; + idx = -1; + } +}; + +class Solution { + TrieNode* root = new TrieNode(); +public: + long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) + { + for (auto& s: original) + reverse(s.begin(), s.end()); + + for (auto& s: changed) + reverse(s.begin(), s.end()); + + unordered_setSet; + Set.insert(original.begin(), original.end()); + Set.insert(changed.begin(), changed.end()); + unordered_mapMap; + int idx = 0; + for (string word: Set) + { + Map[word] = idx; + + TrieNode* node = root; + for (char ch: word) + { + if (node->next[ch-'a']==NULL) + node->next[ch-'a'] = new TrieNode(); + node = node->next[ch-'a']; + } + node->idx = idx; + + idx++; + } + + int n = Set.size(); + LL d[205][205]; + for (int i=0; idp(m+1); + dp[0] = 0; + + for (int i=1; i<=m; i++) + { + dp[i] = LLONG_MAX/2; + if (source[i]==target[i]) + dp[i] = dp[i-1]; + + TrieNode* node1 = root; + TrieNode* node2 = root; + for (int j=i; j>=1; j--) + { + if (node1->next[source[j]-'a']==NULL) + break; + if (node2->next[target[j]-'a']==NULL) + break; + node1 = node1->next[source[j]-'a']; + node2 = node2->next[target[j]-'a']; + + int idx1 = node1->idx; + int idx2 = node2->idx; + if (idx1==-1 || idx2==-1) continue; + + dp[i] = min(dp[i], dp[j-1] + d[idx1][idx2]); + } + } + + if (dp[m]==LLONG_MAX/2) return -1; + + return dp[m]; + } +}; From 123f33f775e6caf1f22dd515cf42e652ad4ab260 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:05:33 -0800 Subject: [PATCH 2317/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4b8b582c9..289f75045 100644 --- a/Readme.md +++ b/Readme.md @@ -656,6 +656,7 @@ 1032. Stream of Characters (TBD) [1858.Longest-Word-With-All-Prefixes](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1858.Longest-Word-With-All-Prefixes) (M) [2416.Sum-of-Prefix-Scores-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2416.Sum-of-Prefix-Scores-of-Strings) (M) +[2977.Minimum-Cost-to-Convert-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2977.Minimum-Cost-to-Convert-String-II) (H) * ``Trie and XOR`` [421.Maximum-XOR-of-Two-Numbers-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/421.Maximum-XOR-of-Two-Numbers-in-an-Array) (H-) [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) From 93f6ac2aa67872fd4146c6518e936c3a4d793eb6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:05:45 -0800 Subject: [PATCH 2318/2729] Rename 2977.Minimum-Cost-to-Convert-String-II.cpp to 2977.Minimum-Cost-to-Convert-String-II_v2.cpp --- ...tring-II.cpp => 2977.Minimum-Cost-to-Convert-String-II_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Trie/2977.Minimum-Cost-to-Convert-String-II/{2977.Minimum-Cost-to-Convert-String-II.cpp => 2977.Minimum-Cost-to-Convert-String-II_v2.cpp} (100%) diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp similarity index 100% rename from Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp rename to Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp From 5b09d53f7503487f86261dac9873655717d3f5ed Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:12:00 -0800 Subject: [PATCH 2319/2729] Create 2977.Minimum-Cost-to-Convert-String-II_v1.cpp --- ...7.Minimum-Cost-to-Convert-String-II_v1.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v1.cpp diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v1.cpp b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v1.cpp new file mode 100644 index 000000000..f3b2e86c7 --- /dev/null +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v1.cpp @@ -0,0 +1,66 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) + { + unordered_setSet; + Set.insert(original.begin(), original.end()); + Set.insert(changed.begin(), changed.end()); + unordered_mapMap; + int idx = 0; + for (string x: Set) + { + Map[x] = idx; + idx++; + } + + int n = Set.size(); + LL d[n][n]; + for (int i=0; idp(m+1); + dp[0] = 0; + + for (int i=1; i<=m; i++) + { + dp[i] = LLONG_MAX/2; + if (source[i]==target[i]) + dp[i] = dp[i-1]; + + string a; + string b; + for (int j=i; j>=1; j--) + { + a = source.substr(j,1) + a; + b = target.substr(j,1) + b; + + if (Map.find(a)!=Map.end() && Map.find(b)!=Map.end()) + dp[i] = min(dp[i], dp[j-1] + d[Map[a]][Map[b]]); + } + } + + if (dp[m]==LLONG_MAX/2) return -1; + + return dp[m]; + } +}; From 640717e05e5b266f0f77169fac148fad8dc50e79 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:12:15 -0800 Subject: [PATCH 2320/2729] Update 2977.Minimum-Cost-to-Convert-String-II_v2.cpp --- .../2977.Minimum-Cost-to-Convert-String-II_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp index 573244ad0..479d6b19c 100644 --- a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp @@ -45,7 +45,7 @@ class Solution { } int n = Set.size(); - LL d[205][205]; + LL d[n][n]; for (int i=0; i Date: Sun, 24 Dec 2023 00:36:45 -0800 Subject: [PATCH 2321/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md b/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md new file mode 100644 index 000000000..3c46ce7bb --- /dev/null +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md @@ -0,0 +1,21 @@ +### 2977.Minimum-Cost-to-Convert-String-II + +本题和`2976. Minimum Cost to Convert String I`类似的思路,只不过2976里构造的最短路径图的顶点是“字母”,而本题里图的顶点是“字符串”。我们用Floyd可以容易求出“original->changed”里出现过任意两个字符串之间的最小代价,将字符串离散化后(用hash表记录每种字符串的序号),记录在数组d[][]里。 + +然后考虑从source到target的转化,很明显这是一个动态规划。对于前i个字符的前缀而言,成功转化的关键在于i所在的字符串转化是什么?我们需要找到一个位置j Date: Sun, 24 Dec 2023 00:37:18 -0800 Subject: [PATCH 2322/2729] Update Readme.md --- Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md b/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md index 3c46ce7bb..558cd466e 100644 --- a/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md @@ -17,5 +17,5 @@ for (int i=0; i Date: Mon, 25 Dec 2023 00:35:07 -0800 Subject: [PATCH 2323/2729] Create 2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp --- ...Number-of-Coins-to-Place-in-Tree-Nodes.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp diff --git a/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp b/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp new file mode 100644 index 000000000..333479b16 --- /dev/null +++ b/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp @@ -0,0 +1,46 @@ +using LL = long long; +class Solution { + vectornext[20005]; + vectorchildren[20005]; + vectorrets; +public: + vector placedCoins(vector>& edges, vector& cost) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + + rets.resize(cost.size()); + dfs(0, -1, cost); + return rets; + } + + void dfs(int cur, int parent, vector&cost) + { + vectortemp; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + dfs(nxt, cur, cost); + for (int x:children[nxt]) + temp.push_back(x); + } + temp.push_back(cost[cur]); + + sort(temp.begin(), temp.end()); + int n = temp.size(); + if (n < 3) + rets[cur] = 1; + else + rets[cur] = max(0LL, max(temp[n-3]*temp[n-2]*temp[n-1], temp[0]*temp[1]*temp[n-1])); + + if (n>=1) children[cur].push_back(temp[0]); + if (n>=2) children[cur].push_back(temp[1]); + if (n>=5) children[cur].push_back(temp[n-3]); + if (n>=4) children[cur].push_back(temp[n-2]); + if (n>=3) children[cur].push_back(temp[n-1]); + } +}; From 95160d50d142444f2d1ef8ba766532dff6445492 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Dec 2023 00:35:38 -0800 Subject: [PATCH 2324/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 289f75045..901208298 100644 --- a/Readme.md +++ b/Readme.md @@ -285,6 +285,7 @@ [2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) [2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes) (H-) [2925.Maximum-Score-After-Applying-Operations-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree) (M) +[2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes) (H-) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) From 39e00927235de356163179a02449dea90b879653 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Dec 2023 00:46:29 -0800 Subject: [PATCH 2325/2729] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/Readme.md diff --git a/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/Readme.md b/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/Readme.md new file mode 100644 index 000000000..1b67960b6 --- /dev/null +++ b/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/Readme.md @@ -0,0 +1,14 @@ +### 2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes + +本题只需要常规的DFS,对于每个节点,假设它的子树的所有的cost都收集在了temp里并保持有序,那么根据题意,收益其实就是这两者的最大值: +``` +max(temp[n-1]*temp[n-2]*temp[n-3], temp[0]*temp[1]*temp[n-1]); +``` +这是因为,三元素乘积的最大值,要么是三个最大正数的乘积,要么是两个最小负数和一个最大正数的乘积。对于前者,我们只需要盲目地取最大的三个数即可(如果不存在三个正数,那么它自然也不会是最优解);对于后者,我们也只需要盲目地取两个最小值和一个最大值即可(如果不存在两个负数,那么它自然也不会是最优解)。 + +综上,我们最多只用到了temp里的五个元素即可。并且在向上传递时,也只需要最多返回五个元素即可。分别是: +1. 最小值temp[0],当n>=1 +2. 次小值temp[1],当n>=2 +3. 第三大值temp[n-3],当n>=5时才能保证该元素不与2重复。 +4. 第二大值temp[n-2],当n>=4时才能保证该元素不与2重复。 +5. 第一大值temp[n-1],当n>=3时才能保证该元素不与2重复。 From 9f9e93d8c8de3eac530bbcd73b47ac31a8b9c345 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Dec 2023 22:46:58 -0800 Subject: [PATCH 2326/2729] Create 2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp --- ...he-Number-of-Incremovable-Subarrays-II.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp diff --git a/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp b/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp new file mode 100644 index 000000000..6d04a7d92 --- /dev/null +++ b/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long incremovableSubarrayCount(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), INT_MIN); + nums.push_back(INT_MAX); + + int l = 1; + while (l<=n) + { + if (nums[l]0) + { + if (nums[r]>nums[r-1]) r--; + else break; + } + if (r Date: Tue, 26 Dec 2023 22:47:25 -0800 Subject: [PATCH 2327/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 901208298..66825e810 100644 --- a/Readme.md +++ b/Readme.md @@ -97,6 +97,7 @@ [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) [2819.Minimum-Relative-Loss-After-Buying-Chocolates](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates) (H) +[2972.Count-the-Number-of-Incremovable-Subarrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II) (H-) * ``Binary Lifting`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) From b78e9ee01cbd2bfcfe07e3fc16a31ae316c01d5d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Dec 2023 23:06:57 -0800 Subject: [PATCH 2328/2729] Create Readme.md --- .../Readme.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/Readme.md diff --git a/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/Readme.md b/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/Readme.md new file mode 100644 index 000000000..714f0c89a --- /dev/null +++ b/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/Readme.md @@ -0,0 +1,23 @@ +### 2972.Count-the-Number-of-Incremovable-Subarrays-II + +本题最直观的考虑,就是将数组分成三段(考虑1-index):前段[1:i],中段[i+1:j-1],以及后段[j:n]。其中要移走中段,而前段和后段必须各自都是严格递增的。于是我们可以找到i的最大位置记做L,以及j的最小位置记做R。 +```cpp + int l = 1; + while (l<=n) + { + if (nums[l]0) + { + if (nums[r]>nums[r-1]) r--; + else break; + } +``` +对于[1:L]里的每一个位置i,我们可以在[R,n]用二分找到恰好大于nums[i]的位置j。那么符合条件的后段的左边界可以是j,j+1,...,n,总共有n+1-j个。 + +但是以上的思考意识强制要求前段、中段、后段都不能为空,而忽略了对应的三种情况:前段为空,中段为空、或者后段为空。需要额外考虑。 + +1. 如果中段为空,那么说明nums整体都是递增的,直接返回nums里的子区间的数目:n(n-1)/2+n. +2. 如果前端为空,或者后端为空,我们可以有一个巧妙的处理,使得之前的逻辑依然适用。在nums前添加一个无穷小(index是0),后面添加一个无穷大(index是n+1)。这样,i的遍历可以从0开始(意味着其实左段为空);而在[R:n+1]区间里进行二分的过程中可能会找到n+1这个位置(即认为后段的左边界是n+1),这其实就意味着允许了后段为空。 From 670a4aaf82da76c837e1231f7babca6d70ecf0f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Dec 2023 01:43:15 -0800 Subject: [PATCH 2329/2729] Create 2969.Minimum-Number-of-Coins-for-Fruits-II.cpp --- ....Minimum-Number-of-Coins-for-Fruits-II.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/2969.Minimum-Number-of-Coins-for-Fruits-II.cpp diff --git a/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/2969.Minimum-Number-of-Coins-for-Fruits-II.cpp b/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/2969.Minimum-Number-of-Coins-for-Fruits-II.cpp new file mode 100644 index 000000000..1a122f4c4 --- /dev/null +++ b/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/2969.Minimum-Number-of-Coins-for-Fruits-II.cpp @@ -0,0 +1,29 @@ +class Solution { + int dp[100005][2]; +public: + int minimumCoins(vector& prices) + { + int n = prices.size(); + prices.insert(prices.begin(), 0); + dp[1][0] = INT_MAX/2; + dp[1][1] = prices[1]; + + dequedq; + dq.push_back(1); + + for (int i=2; i<=n; i++) + { + dp[i][1] = min(dp[i-1][0], dp[i-1][1]) + prices[i]; + while (!dq.empty() && dq.front()*2= dp[i][1]) + dq.pop_back(); + dq.push_back(i); + } + + return min(dp[n][0], dp[n][1]); + + } +}; From 9fa334412356fd36e3abedc3b0b1d0e362a1da94 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Dec 2023 01:43:40 -0800 Subject: [PATCH 2330/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 66825e810..ad9758bba 100644 --- a/Readme.md +++ b/Readme.md @@ -461,6 +461,7 @@ [1776.Car-Fleet-II](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1776.Car-Fleet-II) (H) [2398.Maximum-Number-of-Robots-Within-Budget](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2398.Maximum-Number-of-Robots-Within-Budget) (H-) [2762.Continuous-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2762.Continuous-Subarrays) (M+) +[2969.Minimum-Number-of-Coins-for-Fruits-II](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II) (H-) #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) From 8636caafabcc46203beeaff166a85b7930332bbc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Dec 2023 22:57:25 -0800 Subject: [PATCH 2331/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/Readme.md diff --git a/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/Readme.md b/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/Readme.md new file mode 100644 index 000000000..10e3dbfe6 --- /dev/null +++ b/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/Readme.md @@ -0,0 +1,11 @@ +### 2969.Minimum-Number-of-Coins-for-Fruits-II + +对于前i件物品而言,我们令dp[i][0]表示第i个水果不付款的最小代价,dp[i][1]表示第i个水果付款的最小代价。显然,我们容易得出 +```cpp +dp[i][1] = min(dp[i-1][0], dp[i-1][1]) + prices[i] +``` +那么对于dp[i][0]而言,第i个水果不用付款,必然是因为某第j个水果付款的缘故(需要满足`2*j>=i`)。这样的j可能有多个 +```cpp +dp[i][0] = min(dp[i-1][j]) j=(i+1)/2, (i+1)/2+1, ..., i-1. +``` +显然,这是求一个滑动窗口的最小值,使用双端队列deque的套路:我们维护一个递增的deque,里面盛装的是dp[x][1]的值。当队首元素不满足`2*j>=i`时就不断弹出,最终队首元素就是合法滑窗内的最小值,即给dp[i][0]赋值。然后将dp[i][1]入队,并将所有队尾元素大于等于dp[i][1]的都弹出,这是因为它们在数值大小或序列先后上都不及第i物品。 From 5e9dee6a9724a9217bb2fe41df1acbaf54453b8f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Dec 2023 02:50:04 -0800 Subject: [PATCH 2332/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/Readme.md diff --git a/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/Readme.md b/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/Readme.md new file mode 100644 index 000000000..4bc7d7ee3 --- /dev/null +++ b/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/Readme.md @@ -0,0 +1,5 @@ +### 2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes + +常规的DFS。对于每个节点,我们需要知道它的祖先节点们总共做了几次“减半”操作,才能确定自身能够得到多少coins。所以DFS的参数里必须包含这个量。 + +对于DFS而言,我们总是与记忆化结合,可以优化时间复杂度。根据参数,记忆化数组需要的维度是`T*N`,其中T是对每个节点而言可能做多的“减半”操作次数。注意到任意节点的初始coins是1e4,这就意味着祖先最多累积13次减半操作,就可以让自身的coins变为零而不再变化。所以DFS的空间复杂度是可以接受的。 From 129d0557c2ac7782fd5027201aadead1d88a5e5e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Dec 2023 01:47:43 -0800 Subject: [PATCH 2333/2729] Create 2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp --- ...ost-Expensive-Item-That-Can-Not-Be-Bought.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp diff --git a/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp b/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp new file mode 100644 index 000000000..67b56c06c --- /dev/null +++ b/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int mostExpensiveItem(int primeOne, int primeTwo) + { + int p1=primeOne, p2=primeTwo; + vectordp(p1*p2+1); + dp[0] = 1; + int ret = 0; + for (int i=1; i<=p1*p2; i++) + { + dp[i] = (i>=p1 && dp[i-p1]) || (i>=p2 && dp[i-p2]); + if (dp[i]==0) ret = max(ret, i); + } + return ret; + } +}; From 332edc98d8fa82fc7c19fcb26a1b8a514b49caca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Dec 2023 01:51:42 -0800 Subject: [PATCH 2334/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/Readme.md diff --git a/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/Readme.md b/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/Readme.md new file mode 100644 index 000000000..ab903b0cb --- /dev/null +++ b/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/Readme.md @@ -0,0 +1,5 @@ +### 2979.Most-Expensive-Item-That-Can-Not-Be-Bought + +本题是给出两个质数p1和p2,求不能写成p1与p2的线性组合的最大自然数。此题有数学解,就是`p1*p2-p1-p2`. + +事实上此题有常规的DP解法。令dp[i]表示i是否能写成p1和p2的线性组合,则有`dp[i]=dp[i-p1]||dp[i-p2]`。当我们尝试到`i=p1*p2`时即可停止。事实上大于`p1*p2`的自然数必然能写成两者的线性组合。 From 49a28800242c766fc5f9e1521374b77f777787a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Dec 2023 01:52:26 -0800 Subject: [PATCH 2335/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ad9758bba..96f204f4e 100644 --- a/Readme.md +++ b/Readme.md @@ -739,6 +739,7 @@ [2826.Sorting-Three-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2826.Sorting-Three-Groups) (M) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) +[2979.Most-Expensive-Item-That-Can-Not-Be-Bought](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought) (M+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 47dc8e13b09a4778afad0943a0b02aec31b6260f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 14:56:17 -0800 Subject: [PATCH 2336/2729] Update range_sum_increase_by.cpp --- .../SegmentTree/range_sum_increase_by.cpp | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/Template/SegmentTree/range_sum_increase_by.cpp b/Template/SegmentTree/range_sum_increase_by.cpp index 86febd552..92bba4ce0 100644 --- a/Template/SegmentTree/range_sum_increase_by.cpp +++ b/Template/SegmentTree/range_sum_increase_by.cpp @@ -1,4 +1,5 @@ using LL = long long; +LL M = 1e9+7; class SegTreeNode { public: @@ -51,7 +52,9 @@ class SegTreeNode { if (tag==1 && left) { + left->info += delta * (left->end - left->start + 1); left->delta += delta; + right->info += delta * (right->end - right->start + 1); right->delta += delta; left->tag = 1; right->tag = 1; @@ -66,21 +69,24 @@ class SegTreeNode return; if (a <= start && end <=b) // completely covered within [a,b] { + info += val * (end-start+1); delta += val; tag = 1; return; } if (left) - { - pushDown(); - left->updateRangeBy(a, b, val); - right->updateRangeBy(a, b, val); + { + pushDown(); + left->updateRangeBy(a, b, val+delta); + right->updateRangeBy(a, b, val+delta); + delta = 0; + tag = 0; info = left->info + right->info; // write your own logic } } - LL queryRange(int a, int b) // query the maximum value within range [a,b] + LL queryRange(int a, int b) // query the sum within range [a,b] { if (b < start || a > end ) { @@ -88,8 +94,8 @@ class SegTreeNode } if (a <= start && end <=b) { - return info + delta*(end-start+1); // check with your own logic - } + return info; // check with your own logic + } if (left) { From 3c30bb6390084462935190f9ba59d842b8acc3fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:08:39 -0800 Subject: [PATCH 2337/2729] Create 2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp --- ...ays-Distinct-Element-Sum-of-Squares-II.cpp | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp new file mode 100644 index 000000000..fe25d0520 --- /dev/null +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp @@ -0,0 +1,145 @@ +using LL = long long; +LL M = 1e9+7; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + LL delta; + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info += delta * (left->end - left->start + 1); + left->delta += delta; + right->info += delta * (right->end - right->start + 1); + right->delta += delta; + left->tag = 1; + right->tag = 1; + tag = 0; + delta = 0; + } + } + + void updateRangeBy(int a, int b, int val) // increase range [a,b] by val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info += val * (end-start+1); + delta += val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRangeBy(a, b, val+delta); + right->updateRangeBy(a, b, val+delta); + delta = 0; + tag = 0; + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +class Solution { +public: + int sumCounts(vector& nums) + { + unordered_mapMap; + int n = nums.size(); + vectorprev(n, -1); + for (int i=0; idp(n); + for (int i=0; iqueryRange(j+1, i-1) + i-1-j; + dp[i] += 1; + dp[i] %= M; + root->updateRangeBy(j+1, i, 1); + } + + LL ret = 0; + for (int i=0; i Date: Mon, 1 Jan 2024 15:09:14 -0800 Subject: [PATCH 2338/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 96f204f4e..009c51782 100644 --- a/Readme.md +++ b/Readme.md @@ -345,6 +345,7 @@ [2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) +[2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 43aec9b906c082b054076fdc6e2f41642594c96c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:26:40 -0800 Subject: [PATCH 2339/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md new file mode 100644 index 000000000..b827a4360 --- /dev/null +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md @@ -0,0 +1,21 @@ +### 2916.Subarrays-Distinct-Element-Sum-of-Squares-II + +我们声明建立一个线段树,在i时刻,线段树每个叶子节点j表示区间[j:i]里distinct number的个数,记做count[j]。注意,我们遍历时刻i=0,1,2...n-1,其中n就是nums的元素个数。当j>i时,区间实际不存在,故记做count[j]=0. + +我们令square[i]表示所有以i为结尾的区间的square of distinct number的和。 + +我们定义count[a:b]表示某个区间内的distinct number的数目,square[a:b]表示该区间内distinct number的数目的平方。 + +对于位置i,我们在数组里找到相同nums[i]出现的前一个位置k。于是 +1. 对于j=0,1,...,k而言,`square[j:i] = square[j:i-1]`. +2. 对于j=k+1,k+2,...,i-1而言,`count[j:i] = count[j:i-1]+1,两边平方一下就得到`square[j:i] = square[j:i-1] + 2*count[j:i-1] + 1`. +将两部分相加得到 +``` +sum{square[j:i]} = sum{square[j:i-1]} (for j=0,1,2,...i-1) + 2 * sum{count[j:i-1]} + (i-1-k)`, j=k+1,...i-1 +``` +可见`sum{square[j:i]}`与`sum{square[j:i-1]}`之间存在递推关系。其中相差的部分`sum{count[j:i-1]}`就是之前定义的线段树中在t=i-1时刻,叶子节点区间[k+1, i-1]的元素之和。 + +当我们求出`sum{square[j:i]}`之后,该如何更新这棵线段树呢?显然,只有以k+1,k+2,...i-1开头的这些区间,随着i的加入,distinct number会增1. 所以我们只需要将叶子节点区间[k+1, i-1]的元素统一都增加1即可。 + +最终的答案就是将每个位置i的`sum{square[j:i]}`再加起来。 + From f12761948e85339640ea2d996859f80d2c8d7c45 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:27:54 -0800 Subject: [PATCH 2340/2729] Update Readme.md --- .../2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md index b827a4360..0e04e1848 100644 --- a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md @@ -1,6 +1,6 @@ ### 2916.Subarrays-Distinct-Element-Sum-of-Squares-II -我们声明建立一个线段树,在i时刻,线段树每个叶子节点j表示区间[j:i]里distinct number的个数,记做count[j]。注意,我们遍历时刻i=0,1,2...n-1,其中n就是nums的元素个数。当j>i时,区间实际不存在,故记做count[j]=0. +我们声明建立一个线段树,在`i`时刻,线段树每个叶子节点`j`表示区间[j:i]里distinct number的个数。注意,我们遍历时刻`i=0,1,2...n-1`,其中n就是nums的元素个数。当j>i时,区间实际不存在,故标记0. 我们令square[i]表示所有以i为结尾的区间的square of distinct number的和。 From 9b05fb9b133c689213f74ecc61ac3c21c327dd54 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:28:50 -0800 Subject: [PATCH 2341/2729] Update Readme.md --- .../Readme.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md index 0e04e1848..26b8f8135 100644 --- a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md @@ -1,14 +1,12 @@ ### 2916.Subarrays-Distinct-Element-Sum-of-Squares-II -我们声明建立一个线段树,在`i`时刻,线段树每个叶子节点`j`表示区间[j:i]里distinct number的个数。注意,我们遍历时刻`i=0,1,2...n-1`,其中n就是nums的元素个数。当j>i时,区间实际不存在,故标记0. +我们声明建立一个线段树,在`i`时刻,线段树每个叶子节点`j`表示区间`[j:i]`里distinct number的个数。注意,我们遍历时刻`i=0,1,2...n-1`,其中n就是nums的元素个数。当j>i时,区间实际不存在,故标记0. -我们令square[i]表示所有以i为结尾的区间的square of distinct number的和。 - -我们定义count[a:b]表示某个区间内的distinct number的数目,square[a:b]表示该区间内distinct number的数目的平方。 +我们再定义`count[a:b]`表示某个区间内的distinct number的数目,`square[a:b]`表示该区间内distinct number的数目的平方。 对于位置i,我们在数组里找到相同nums[i]出现的前一个位置k。于是 -1. 对于j=0,1,...,k而言,`square[j:i] = square[j:i-1]`. -2. 对于j=k+1,k+2,...,i-1而言,`count[j:i] = count[j:i-1]+1,两边平方一下就得到`square[j:i] = square[j:i-1] + 2*count[j:i-1] + 1`. +1. 对于`j=0,1,...,k`而言,`square[j:i] = square[j:i-1]`. +2. 对于`j=k+1,k+2,...,i-1`而言,`count[j:i] = count[j:i-1]+1,两边平方一下就得到`square[j:i] = square[j:i-1] + 2*count[j:i-1] + 1`. 将两部分相加得到 ``` sum{square[j:i]} = sum{square[j:i-1]} (for j=0,1,2,...i-1) + 2 * sum{count[j:i-1]} + (i-1-k)`, j=k+1,...i-1 From 7f1a234f69b27bb8521eda6c827ced15d5721aa9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:29:22 -0800 Subject: [PATCH 2342/2729] Update Readme.md --- .../2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md index 26b8f8135..b12f19807 100644 --- a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md @@ -9,7 +9,7 @@ 2. 对于`j=k+1,k+2,...,i-1`而言,`count[j:i] = count[j:i-1]+1,两边平方一下就得到`square[j:i] = square[j:i-1] + 2*count[j:i-1] + 1`. 将两部分相加得到 ``` -sum{square[j:i]} = sum{square[j:i-1]} (for j=0,1,2,...i-1) + 2 * sum{count[j:i-1]} + (i-1-k)`, j=k+1,...i-1 +sum{square[j:i]} = sum{square[j:i-1]} (for j=0,1,2,...i-1) + 2 * sum{count[j:i-1]} + (i-1-k) (for j=k+1,...i-1) ``` 可见`sum{square[j:i]}`与`sum{square[j:i-1]}`之间存在递推关系。其中相差的部分`sum{count[j:i-1]}`就是之前定义的线段树中在t=i-1时刻,叶子节点区间[k+1, i-1]的元素之和。 From 6e9041b23b6c2c4f62bfe2f20c80e361e5393e51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 Jan 2024 02:20:36 -0800 Subject: [PATCH 2343/2729] Update Readme.md --- .../1092.Shortest-Common-Supersequence/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1092.Shortest-Common-Supersequence/Readme.md b/Dynamic_Programming/1092.Shortest-Common-Supersequence/Readme.md index 424f7265c..a8f64a578 100644 --- a/Dynamic_Programming/1092.Shortest-Common-Supersequence/Readme.md +++ b/Dynamic_Programming/1092.Shortest-Common-Supersequence/Readme.md @@ -4,7 +4,7 @@ 如果只是问Shortest-Common-Supersequence的长度,那么就是一道非常基本的dp题,典型的"two string conversion"的套路. 现在要求打印出这样的Shortest-Common-Supersequence,无非就是从dp[M][N]逆着往回走,每一步我们都需要判断dp[i][j]之前的状态是什么?其实就是重复一遍给dp赋值的逻辑: -1. 如果dp[i][j]是由dp[i-1][j-1]+1得来,也即是说str1[i]==str2[j],那么就意味着当时在构建SCS的时候,最后一步是在dp[i-1][j-1]的基础上加上str1[i](或者str2[j]) +1. 如果dp[i][j]是由dp[i-1][j-1]+1得来,也即是说str1[i]==str2[j],那么就意味着当时在构建SCS的时候,最后一步是在dp[i-1][j-1]的基础上加上```str1[i]```(或者str2[j]) 2. 如果dp[i][j]是由dp[i-1][j]+1得来,那么说明当时是在dp[i-1][j]的基础上加上str1[i],现在逆序重构的时候需要先加上str1[i]. 3. 如果dp[i][j]是由dp[i][j-1]+1得来,那么说明当时是在dp[i][j-1]的基础上加上str2[j],现在逆序重构的时候需要先加上str2[j]. From b2a802a65a619db5d5643019dd464afb6a4a0a77 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 18:45:49 -0800 Subject: [PATCH 2344/2729] Create 3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp --- ...eautiful-Indices-in-the-Given-Array-II.cpp | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp diff --git a/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp b/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp new file mode 100644 index 000000000..4c65f9dd0 --- /dev/null +++ b/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp @@ -0,0 +1,64 @@ +class Solution { + vector strStr(string haystack, string needle) + { + vectorrets; + + int n = haystack.size(); + int m = needle.size(); + if (m==0) return {}; + if (n==0) return {}; + + vector suf = preprocess(needle); + + vectordp(n,0); + dp[0] = (haystack[0]==needle[0]); + if (m==1 && dp[0]==1) + rets.push_back(0); + + + for (int i=1; i0 && haystack[i]!=needle[j]) + j = suf[j-1]; + dp[i] = j + (haystack[i]==needle[j]); + if (dp[i]==needle.size()) + rets.push_back(i-needle.size()+1); + } + return rets; + } + + vector preprocess(string s) + { + int n = s.size(); + vectordp(n,0); + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + return dp; + } + +public: + vector beautifulIndices(string s, string a, string b, int k) + { + vector A = strStr(s,a); + vector B = strStr(s,b); + + vectorrets; + for (int i:A) + { + auto iter1 = lower_bound(B.begin(), B.end(), i-k); + auto iter2 = upper_bound(B.begin(), B.end(), i+k); + if (iter2-iter1>=1) + rets.push_back(i); + } + return rets; + + } +}; From 56b1e5c06b6f09b73a908fc501f846946100ca9e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 18:46:23 -0800 Subject: [PATCH 2345/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 009c51782..8c663222f 100644 --- a/Readme.md +++ b/Readme.md @@ -1018,7 +1018,8 @@ 1397.Find All Good Strings (TBD) [1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array) (H) [2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/String/2301.Match-Substring-After-Replacement) (H-) -[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) +[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) +[3008.Find-Beautiful-Indices-in-the-Given-Array-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II) (H-) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From 77c3486c476b0235d70eb8cf40f2dfa173b38ae3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 19:00:16 -0800 Subject: [PATCH 2346/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/Readme.md diff --git a/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/Readme.md b/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/Readme.md new file mode 100644 index 000000000..4b821348d --- /dev/null +++ b/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/Readme.md @@ -0,0 +1,5 @@ +### 3008.Find-Beautiful-Indices-in-the-Given-Array-II + +很显然,我们只需要找出a在s中出现的所有位置pos1,以及b在s中出现的所有位置pos2。这个用KMP的模板即可。 + +对于pos1中的每个位置i,我们只需要查找`i-k`在pos2里的位置(lower_bound,第一个大于等于该数的迭代器),以及`i+k`在pos2里的位置(upper_bound,第一个大于该数的迭代器),两个位置之差即代表有多少pos2的元素位于[i-k, i+k]之间。 From 8f9c5bc1bcd774e499928fe4e6399445c1694aff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 19:37:36 -0800 Subject: [PATCH 2347/2729] Create 3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp --- ...-the-Prices-Is-Less-Than-or-Equal-to-K.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp diff --git a/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp b/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp new file mode 100644 index 000000000..c1800f6f0 --- /dev/null +++ b/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp @@ -0,0 +1,55 @@ +using LL = long long; +class Solution { +public: + long long findMaximumNumber(long long k, int x) + { + LL left = 1, right = 1e15; + + while (left < right) + { + LL mid = right-(right-left)/2; + if (checkOK(mid, k, x)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool checkOK(LL A, LL k, int x) + { + LL ret = 0; + for (int i=x-1; (1LL<arr; + while (a>0) + { + arr.push_back(a%2); + a/=2; + } + if (arr[i]==1) + { + LL b = 0; + for (int j=arr.size()-1; j>i; j--) + b = b*2+arr[j]; + ret += b * pow(2, i); + b = 0; + for (int j=i-1; j>=0; j--) + b = b*2+arr[j]; + ret += b+1; + } + else + { + LL b = 0; + for (int j=arr.size()-1; j>i; j--) + b = b*2+arr[j]; + ret += b * pow(2, i); + } + + if (ret > k) return false; + } + + return true; + } +}; From 54e9bba1d36489259258188f1939e41327a3f689 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 19:38:21 -0800 Subject: [PATCH 2348/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8c663222f..e531413e1 100644 --- a/Readme.md +++ b/Readme.md @@ -1568,7 +1568,8 @@ [973.K-Closest-Points-to-Origin](https://github.com/wisdompeak/LeetCode/tree/master/Others/973.K-Closest-Points-to-Origin) (M) [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``Digit counting`` -[233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) +[233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) +[3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K) (H) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) From 9a1711e897ff1cd118438504fbab5afb9e2c2a6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 19:50:50 -0800 Subject: [PATCH 2349/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/Readme.md diff --git a/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/Readme.md b/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/Readme.md new file mode 100644 index 000000000..a77e2165e --- /dev/null +++ b/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/Readme.md @@ -0,0 +1,13 @@ +### 3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K + +首先我们很容易看出此题的答案具有单调性。答案越大,就有越多的bit 1能够被计入;反之,被计入的bit 1会越少。所以整体的框架就是一个二分,核心就是制定一个上限A,想问从1到A的所有自然数的二进制表达里,总共有多少个bit 1出现在第x位、第2x位、... + +这个问题和`LC 233.Number-of-Digit-One`非常相似。我们不会固定一个数,再数里面有多少个bit 1;而是相反的策略,对于某位bit,我们计算有多少个数会在该bit的值是1. + +我们令上限A表达为`XXX i YYY`,考虑从1到A总共多少个自然数在第i位bit上的值是1呢? + +如果A[i]==0,那么高位部分可以是任意000 ~ (XXX-1),低位部分可以是任意 000 ~ 999。两处的任意组合,都可以保证整体的数值不超过上限A。这样的数有`XXX * 2^t`种,其中t表示`YYY`的位数。此外没有任何数可以满足要求。 + +如果A[i]==1,那么高位部分可以是任意000 ~ (XXX-1),低位部分可以是任意 000 ~ 999。两处的任意组合,都可以保证整体的数值不超过上限A。同样,这样的数有`XXX * 2^t`种,其中t表示`YYY`的位数。。此外,当高位恰好是`XXX`时,低位可以是从000~YYY,这样就额外有`YYY+1`种。 + +以上就统计了从1-A的所有自然数有多少个在第i位bit是1。我们再循环处理下一个的bit(隔x位)即可。 From 7f2cc2a68ed46b74b8080a624e08486ab89d7e57 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 22:48:21 -0800 Subject: [PATCH 2350/2729] Create 2999.Count-the-Number-of-Powerful-Integers.cpp --- ....Count-the-Number-of-Powerful-Integers.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Recursion/2999.Count-the-Number-of-Powerful-Integers/2999.Count-the-Number-of-Powerful-Integers.cpp diff --git a/Recursion/2999.Count-the-Number-of-Powerful-Integers/2999.Count-the-Number-of-Powerful-Integers.cpp b/Recursion/2999.Count-the-Number-of-Powerful-Integers/2999.Count-the-Number-of-Powerful-Integers.cpp new file mode 100644 index 000000000..c345b0ae5 --- /dev/null +++ b/Recursion/2999.Count-the-Number-of-Powerful-Integers/2999.Count-the-Number-of-Powerful-Integers.cpp @@ -0,0 +1,43 @@ +using LL = long long; +class Solution { +public: + long long numberOfPowerfulInt(long long start, long long finish, int limit, string s) + { + return helper(to_string(finish), limit, s) - helper(to_string(start-1), limit, s); + } + + LL helper(string a, int limit, string s) + { + if (a.size() < s.size()) return 0; + return dfs(a, s, limit, 0, true); + } + + LL dfs(string a, string s, int limit, int k, bool same) + { + if (a.size() - k == s.size()) + { + int len = s.size(); + if (!same || a.substr(a.size()-len, len) >= s) return 1; + else return 0; + } + + LL ret = 0; + if (!same) + { + int d = a.size()-s.size()-k; + ret = pow(1+limit, d); + } + else + { + for (int i=0; i<=limit; i++) + { + if (i > a[k]-'0') break; + else if (i == a[k]-'0') + ret += dfs(a, s, limit, k+1, true); + else + ret += dfs(a, s, limit, k+1, false); + } + } + return ret; + } +}; From fa045bf00c5e2bbbd97736092e78a1b57e14285f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 22:48:56 -0800 Subject: [PATCH 2351/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e531413e1..998f67174 100644 --- a/Readme.md +++ b/Readme.md @@ -1114,6 +1114,7 @@ [2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) [2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) +[2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 5543f46d5b2e80a41382afe0676307626850ee8d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 23:04:27 -0800 Subject: [PATCH 2352/2729] Create Readme.md --- .../2999.Count-the-Number-of-Powerful-Integers/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Recursion/2999.Count-the-Number-of-Powerful-Integers/Readme.md diff --git a/Recursion/2999.Count-the-Number-of-Powerful-Integers/Readme.md b/Recursion/2999.Count-the-Number-of-Powerful-Integers/Readme.md new file mode 100644 index 000000000..fc0cc3ebf --- /dev/null +++ b/Recursion/2999.Count-the-Number-of-Powerful-Integers/Readme.md @@ -0,0 +1,7 @@ +### 2999.Count-the-Number-of-Powerful-Integers + +首先,对于区间内的计数,常用的技巧就是转化为`helper(to_string(finish), limit, s) - helper(to_string(start-1), limit, s)`,其中`helper(string a, int limit, string s)`表示在[1:a]区间内有多少符合条件的数(即每个digit不超过limit且后缀为s)。 + +接下来写helper函数。令上限a的长度为d,那么我们计数的时候只需要逐位填充、循环d次即可。对于第k位而言,分两种情况: +1. 如果填充的前k-1位小于a同样长度的前缀,那么第k位可以任意填充0 ~ limit都不会超过上限a。甚至从第k+1位起,直至固定的后缀s之前,总共有`d = a.size()-s.size()-k`位待填充的数字,都可以任意填充为0~limit。故直接返回计数结果:`pow(1+limit, d)`. +2. 如果填充的前k-1位等于a同样长度的前缀,那么第k位可以填充为0 ~ min(limit, a[k])。确定之后,接下来递归处理下一位即可。注意,如果填充为a[k]的话,需要告知递归函数“已构造的前缀继续与a相同”,否则告知递归函数“已构造的前缀小于a”。这样下一轮递归函数知道选择哪一个分支。 From 0be0fa576f1fe793aa647a3058264cf14bfda8fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 00:31:06 -0800 Subject: [PATCH 2353/2729] Create 2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp --- ...er-of-Operations-to-Make-X-and-Y-Equal.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp diff --git a/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp b/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp new file mode 100644 index 000000000..3b37dbf42 --- /dev/null +++ b/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp @@ -0,0 +1,23 @@ +class Solution { + int memo[10001]; +public: + int minimumOperationsToMakeEqual(int x, int y) + { + if (y>=x) return y-x; + + if (memo[x]!=0) return memo[x]; + + int ret = INT_MAX/2; + ret = min(ret, minimumOperationsToMakeEqual( (x-(x%11))/11, y) + x%11+1); + ret = min(ret, minimumOperationsToMakeEqual( (x+ (11-x%11))/11, y) + (11-x%11) + 1); + + ret = min(ret, minimumOperationsToMakeEqual( (x-(x%5))/5, y) + x%5+1); + ret = min(ret, minimumOperationsToMakeEqual( (x+(5-x%5))/5, y) + (5-x%5)+1); + + ret = min(ret, x-y); + + memo[x] = ret; + + return ret; + } +}; From 6914619d6d8f6bf230fcb7896d64f59bf9eddc77 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 00:31:50 -0800 Subject: [PATCH 2354/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 998f67174..ded0df2f9 100644 --- a/Readme.md +++ b/Readme.md @@ -1093,6 +1093,7 @@ [1274.Number-of-Ships-in-a-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1274.Number-of-Ships-in-a-Rectangle) (M) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) +[2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal) (M+) * ``Evaluate Expressions`` [241.Different-Ways-to-Add-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/241.Different-Ways-to-Add-Parentheses) (M+) [2019.The-Score-of-Students-Solving-Math-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2019.The-Score-of-Students-Solving-Math-Expression) (H-) From 0eaa191b57d91d0ec2611f952c8b65b951fd3b04 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 00:39:23 -0800 Subject: [PATCH 2355/2729] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/Readme.md diff --git a/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/Readme.md b/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/Readme.md new file mode 100644 index 000000000..7116e1b72 --- /dev/null +++ b/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/Readme.md @@ -0,0 +1,10 @@ +### 2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal + +因为除法操作最高效,所有的增减操作都是为了能够凑出除法操作。所以当x>y时,我们想要将x拉低至y,只需要考虑以下五种操作: +1. 增加x,使得x能被11整除 +2. 减小x,使得x能被11整除 +3. 增加x,使得x能被5整除 +4. 减小x,使得x能被5整除 +5. 直接将x与y拉平。 + +此外,本题需要记忆化来提升效率。 From b03014aacc12199daf523e963a4ae7e0e65a8c6d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 14:57:30 -0800 Subject: [PATCH 2356/2729] Create 2992.Number-of-Self-Divisible-Permutations.cpp --- ....Number-of-Self-Divisible-Permutations.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/2992.Number-of-Self-Divisible-Permutations.cpp diff --git a/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/2992.Number-of-Self-Divisible-Permutations.cpp b/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/2992.Number-of-Self-Divisible-Permutations.cpp new file mode 100644 index 000000000..a281fd721 --- /dev/null +++ b/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/2992.Number-of-Self-Divisible-Permutations.cpp @@ -0,0 +1,20 @@ +class Solution { + int dp[13][4096]; +public: + int selfDivisiblePermutationCount(int n) + { + int state = 0; + dp[0][0] = 1; + for (int i=1; i<=n; i++) + for (int state = 0; state<(1<>(d-1))&1)==0) continue; + dp[i][state] += dp[i-1][state-(1<<(d-1))]; + } + } + return dp[n][(1< Date: Mon, 15 Jan 2024 15:00:31 -0800 Subject: [PATCH 2357/2729] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/Readme.md diff --git a/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/Readme.md b/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/Readme.md new file mode 100644 index 000000000..9a9c2fbe4 --- /dev/null +++ b/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/Readme.md @@ -0,0 +1,14 @@ +### 2992.Number-of-Self-Divisible-Permutations + +此题如果暴力DFS的话,会有12!种排列,显然会TLE. + +考虑到2^12=4096,我们可以逐位填充,用一个bitmask来表示哪些数字已经被选中了。令dp[i][state]表示前i位里填充状态是state(每个bit位表示对应的数字已经使用)时,有多少种合法的排列。有状态转移方程 +```cpp +for (int d=1; d<=n; d++) +{ + if (gcd(d,i)!=1) continue; + if (((state>>(d-1))&1)==0) continue; + dp[i][state] += dp[i-1][state-(1<<(d-1))]; +} +``` +最终返回dp[n][(1< Date: Mon, 15 Jan 2024 15:00:59 -0800 Subject: [PATCH 2358/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ded0df2f9..7c1df3c14 100644 --- a/Readme.md +++ b/Readme.md @@ -943,6 +943,7 @@ [2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) [2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) [2802.Find-The-K-th-Lucky-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number) (M+) +[2992.Number-of-Self-Divisible-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 704b23c50031605ed5d503eafc94e69f097cdc0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 16:36:28 -0800 Subject: [PATCH 2359/2729] Create 2983.Palindrome-Rearrangement-Queries.cpp --- .../2983.Palindrome-Rearrangement-Queries.cpp | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp b/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp new file mode 100644 index 000000000..d5dc9f083 --- /dev/null +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp @@ -0,0 +1,95 @@ +using PII = pair; +class Solution { + int diff[100005]; + int presum1[100005][26]; + int presum2[100005][26]; +public: + vector canMakePalindromeQueries(string s, vector>& queries) + { + int n = s.size(); + string t = s.substr(n/2, n/2); + reverse(t.begin(), t.end()); + int m = t.size(); + s = s.substr(0, n/2); + t = "#"+t; + s = "#"+s; + + for (int i=1; i<=m; i++) + diff[i] = diff[i-1] + (s[i]!=t[i]); + + for (int i=1; i<=m; i++) + for (int j=0; j<26; j++) + { + presum1[i][j] = presum1[i-1][j] + (s[i]=='a'+j); + presum2[i][j] = presum2[i-1][j] + (t[i]=='a'+j); + } + + vectorrets; + for (auto& query: queries) + { + int a = query[0]+1, b = query[1]+1; + int c = m-1-(query[3]-n/2)+1; + int d = m-1-(query[2]-n/2)+1; + + rets.push_back(process(a,b,c,d,m)); + } + return rets; + } + + bool process(int a, int b, int c, int d, int m) + { + vectorcross; + if (max(a,c) <= min(b,d)) cross.push_back({max(a,c), min(b,d)}); + vectorpart1; + vectorpart2; + if (cross.size() == 0) + { + part1.push_back({a,b}); + part2.push_back({c,d}); + } + else + { + if (a<=c-1) part1.push_back({a,c-1}); + if (d+1<=b) part1.push_back({d+1,b}); + if (c<=a-1) part2.push_back({c,a-1}); + if (b+1<=d) part2.push_back({b+1,d}); + } + + + int count_diff = 0; + vectorUnion; + for (auto x: cross) Union.push_back(x); + for (auto x: part1) Union.push_back(x); + for (auto x: part2) Union.push_back(x); + for (auto [s, e]: Union) + count_diff += diff[e]-diff[s-1]; + if (count_diff != diff[m]) return false; + + vectorcount1(26); + vectorcount2(26); + for (int ch=0; ch<26; ch++) + { + count1[ch] = presum1[b][ch]-presum1[a-1][ch]; + count2[ch] = presum2[d][ch]-presum2[c-1][ch]; + } + + for (int ch=0; ch<26; ch++) + { + for (auto [s,e]: part1) + count1[ch] -= presum2[e][ch]-presum2[s-1][ch]; + for (auto [s,e]: part2) + count2[ch] -= presum1[e][ch]-presum1[s-1][ch]; + if (count1[ch]<0 || count2[ch]<0) + return false; + + } + + for (int ch=0; ch<26; ch++) + { + if (count1[ch]!=count2[ch]) return false; + } + + return true; + } + +}; From 7002f592b7ba3b782e7c76a8edc890497203d4bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 16:37:05 -0800 Subject: [PATCH 2360/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7c1df3c14..0776796f4 100644 --- a/Readme.md +++ b/Readme.md @@ -1412,7 +1412,8 @@ [1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) -[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) +[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) +[2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/new/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From ea6fafea9f4b6d733996fe0a5c881ca7f9033a44 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 17:06:54 -0800 Subject: [PATCH 2361/2729] Create Readme.md --- .../Readme.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md new file mode 100644 index 000000000..854adf0ab --- /dev/null +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md @@ -0,0 +1,24 @@ +### 2983.Palindrome-Rearrangement-Queries + +首先我们预处理一下,将s的后半段翻转之后记为t,令s和t的长度都是m=n/2。并且将两个字符串都看做1-index。 + +我们容易得到s中可以重排的区间A记做[a,b],t中可以重排的区间B记做[c,d]. 考虑到这两个区间可能有多种交汇的可能:不相交、相交但不包含,完全包含。我们做如下区间处理: +1. 计算相交的区间cross:```{max(a,c), min(b,d)}```,注意该区间可能为空。 +2. 计算属于区间A但不属于B的区域:part1 + ```cpp + if (a<=c-1) part1.push_back({a, c-1}); + if (d+1<=b) part1.push_back({d+1, b}); + ``` +3. 计算属于区间B但不属于C的区域:part2 + ```cpp + if (c<=a-1) part2.push_back({c,a-1}); + if (b+1<=d) part2.push_back({b+1,d}); + ``` +4. 计算要么属于A要么属于B的区间:Union,就是以上cross, part1, part2里面区间的合并。 + +判断合法的条件有如下: +1. 在Union之外的区域,必须要求s和t每个字符都相等。这里有一个巧妙的判定方法。我们构造前缀数组diff[i]表示前i个位置里有多少个s与t字母不相同的位置。于是我们只需要查验Union里面的、不同字母的位置个数,是否等于diff[m]即可。 +2. 对于part1区间,s里面的字符调整后必须和t里面的字符完全一致。所以我们先将s在区间A的字符频次放入count1,再消耗掉t在区间part1里的字符频次。要求不能出现负数。 +3. 对于part2区间,t里面的字符调整后必须和s里面的字符完全一致。所以我们先将t在区间B的字符频次放入count2,再消耗掉s在区间part2里的字符频次。要求不能出现负数。 +4. 最后,剩余的count1和count2代表了cross部分,两者的字母频次必须完全一致。 + From ba46dc904e884b044fb35c4c97bb84299820eea9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 17:58:17 -0800 Subject: [PATCH 2362/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0776796f4..b60552a5f 100644 --- a/Readme.md +++ b/Readme.md @@ -1412,7 +1412,7 @@ [1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) -[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) +[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/new/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) From ccdaead1658393c7e0f77818f28bd68a1eddaba0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 18:02:02 -0800 Subject: [PATCH 2363/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b60552a5f..e3ecee4cb 100644 --- a/Readme.md +++ b/Readme.md @@ -1413,7 +1413,7 @@ [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) -[2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/new/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) +[2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 8ffe9b993bef16205403553b3df2c47e759d139e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 18:45:00 -0800 Subject: [PATCH 2364/2729] Update Readme.md --- .../Readme.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md index 854adf0ab..e1838d7b4 100644 --- a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md @@ -4,21 +4,21 @@ 我们容易得到s中可以重排的区间A记做[a,b],t中可以重排的区间B记做[c,d]. 考虑到这两个区间可能有多种交汇的可能:不相交、相交但不包含,完全包含。我们做如下区间处理: 1. 计算相交的区间cross:```{max(a,c), min(b,d)}```,注意该区间可能为空。 -2. 计算属于区间A但不属于B的区域:part1 +2. 计算属于区间ab但不属于cd的区域:A ```cpp - if (a<=c-1) part1.push_back({a, c-1}); - if (d+1<=b) part1.push_back({d+1, b}); + if (a<=c-1) A.push_back({a, c-1}); + if (d+1<=b) A.push_back({d+1, b}); ``` -3. 计算属于区间B但不属于C的区域:part2 +3. 计算属于区间cd但不属于ab的区域:B ```cpp - if (c<=a-1) part2.push_back({c,a-1}); - if (b+1<=d) part2.push_back({b+1,d}); + if (c<=a-1) B.push_back({c,a-1}); + if (b+1<=d) B.push_back({b+1,d}); ``` -4. 计算要么属于A要么属于B的区间:Union,就是以上cross, part1, part2里面区间的合并。 +4. 计算要么属于A要么属于B的区间:Union,就是以上cross, A, B里面区间的合并。 判断合法的条件有如下: 1. 在Union之外的区域,必须要求s和t每个字符都相等。这里有一个巧妙的判定方法。我们构造前缀数组diff[i]表示前i个位置里有多少个s与t字母不相同的位置。于是我们只需要查验Union里面的、不同字母的位置个数,是否等于diff[m]即可。 -2. 对于part1区间,s里面的字符调整后必须和t里面的字符完全一致。所以我们先将s在区间A的字符频次放入count1,再消耗掉t在区间part1里的字符频次。要求不能出现负数。 -3. 对于part2区间,t里面的字符调整后必须和s里面的字符完全一致。所以我们先将t在区间B的字符频次放入count2,再消耗掉s在区间part2里的字符频次。要求不能出现负数。 +2. 对于A区间,s里面的字符调整后必须和t里面的字符完全一致。所以我们先将s在区间ab的字符频次放入count1,再消耗掉t在区间A里的字符频次。要求不能出现负数。 +3. 对于B区间,t里面的字符调整后必须和s里面的字符完全一致。所以我们先将t在区间cd的字符频次放入count2,再消耗掉s在区间B里的字符频次。要求不能出现负数。 4. 最后,剩余的count1和count2代表了cross部分,两者的字母频次必须完全一致。 From 424ccddfac06aeba8c8544bb12e6c793d9e9eca6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 18:45:16 -0800 Subject: [PATCH 2365/2729] Update Readme.md --- Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md index e1838d7b4..6c1bd4227 100644 --- a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md @@ -14,7 +14,7 @@ if (c<=a-1) B.push_back({c,a-1}); if (b+1<=d) B.push_back({b+1,d}); ``` -4. 计算要么属于A要么属于B的区间:Union,就是以上cross, A, B里面区间的合并。 +4. 计算要么属于ab要么属于cd的区间:Union,就是以上cross, A, B里面区间的合并。 判断合法的条件有如下: 1. 在Union之外的区域,必须要求s和t每个字符都相等。这里有一个巧妙的判定方法。我们构造前缀数组diff[i]表示前i个位置里有多少个s与t字母不相同的位置。于是我们只需要查验Union里面的、不同字母的位置个数,是否等于diff[m]即可。 From 024c7fa312c34e1b46579d8be592bf518a3103fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 18:45:43 -0800 Subject: [PATCH 2366/2729] Update 2983.Palindrome-Rearrangement-Queries.cpp --- .../2983.Palindrome-Rearrangement-Queries.cpp | 67 +++++++++---------- 1 file changed, 31 insertions(+), 36 deletions(-) diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp b/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp index d5dc9f083..15bf8654b 100644 --- a/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp @@ -6,10 +6,10 @@ class Solution { public: vector canMakePalindromeQueries(string s, vector>& queries) { - int n = s.size(); + int n = s.size(); string t = s.substr(n/2, n/2); reverse(t.begin(), t.end()); - int m = t.size(); + int m = n/2; s = s.substr(0, n/2); t = "#"+t; s = "#"+s; @@ -17,13 +17,13 @@ class Solution { for (int i=1; i<=m; i++) diff[i] = diff[i-1] + (s[i]!=t[i]); - for (int i=1; i<=m; i++) - for (int j=0; j<26; j++) + for (int i=1; i<=m; i++) + for (int ch=0; ch<26; ch++) { - presum1[i][j] = presum1[i-1][j] + (s[i]=='a'+j); - presum2[i][j] = presum2[i-1][j] + (t[i]=='a'+j); - } - + presum1[i][ch] = presum1[i-1][ch] + (s[i]=='a'+ch); + presum2[i][ch] = presum2[i-1][ch] + (t[i]=='a'+ch); + } + vectorrets; for (auto& query: queries) { @@ -39,57 +39,52 @@ class Solution { bool process(int a, int b, int c, int d, int m) { vectorcross; - if (max(a,c) <= min(b,d)) cross.push_back({max(a,c), min(b,d)}); - vectorpart1; - vectorpart2; + if (max(a,c) <= min(b,d)) + cross.push_back({max(a,c), min(b,d)}); + vectorA; + vectorB; if (cross.size() == 0) { - part1.push_back({a,b}); - part2.push_back({c,d}); + A.push_back({a,b}); + B.push_back({c,d}); } else { - if (a<=c-1) part1.push_back({a,c-1}); - if (d+1<=b) part1.push_back({d+1,b}); - if (c<=a-1) part2.push_back({c,a-1}); - if (b+1<=d) part2.push_back({b+1,d}); + if (a<=c-1) A.push_back({a,c-1}); + if (d+1<=b) A.push_back({d+1, b}); + if (b+1<=d) B.push_back({b+1, d}); + if (c<=a-1) B.push_back({c, a-1}); } - - int count_diff = 0; + int count_diff = 0; vectorUnion; - for (auto x: cross) Union.push_back(x); - for (auto x: part1) Union.push_back(x); - for (auto x: part2) Union.push_back(x); - for (auto [s, e]: Union) - count_diff += diff[e]-diff[s-1]; - if (count_diff != diff[m]) return false; + for (auto x: cross) Union.push_back(x); + for (auto x: A) Union.push_back(x); + for (auto x: B) Union.push_back(x); + for (auto [s,e]: Union) + count_diff += diff[e] - diff[s-1]; + if (diff[m] - count_diff != 0) return false; vectorcount1(26); vectorcount2(26); for (int ch=0; ch<26; ch++) { - count1[ch] = presum1[b][ch]-presum1[a-1][ch]; - count2[ch] = presum2[d][ch]-presum2[c-1][ch]; + count1[ch] = presum1[b][ch] - presum1[a-1][ch]; + count2[ch] = presum2[d][ch] - presum2[c-1][ch]; } - for (int ch=0; ch<26; ch++) { - for (auto [s,e]: part1) - count1[ch] -= presum2[e][ch]-presum2[s-1][ch]; - for (auto [s,e]: part2) - count2[ch] -= presum1[e][ch]-presum1[s-1][ch]; + for (auto [s,e]: A) + count1[ch] -= presum2[e][ch] - presum2[s-1][ch]; + for (auto [s,e]: B) + count2[ch] -= presum1[e][ch] - presum1[s-1][ch]; if (count1[ch]<0 || count2[ch]<0) return false; - } for (int ch=0; ch<26; ch++) - { if (count1[ch]!=count2[ch]) return false; - } return true; } - }; From 7c76e25b3041ccc3e582046cfd86207e6b314e16 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 19:17:22 -0800 Subject: [PATCH 2367/2729] Update Readme.md --- Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md index 6c1bd4227..ddaeb877e 100644 --- a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md @@ -2,19 +2,19 @@ 首先我们预处理一下,将s的后半段翻转之后记为t,令s和t的长度都是m=n/2。并且将两个字符串都看做1-index。 -我们容易得到s中可以重排的区间A记做[a,b],t中可以重排的区间B记做[c,d]. 考虑到这两个区间可能有多种交汇的可能:不相交、相交但不包含,完全包含。我们做如下区间处理: -1. 计算相交的区间cross:```{max(a,c), min(b,d)}```,注意该区间可能为空。 -2. 计算属于区间ab但不属于cd的区域:A +我们容易得到s中可以重排的区间记做[a,b],t中可以重排的区间记做[c,d]. 考虑到这两个区间可能有多种交汇的可能:不相交、相交但不包含,完全包含。我们做如下区间处理: +1. 计算相交的区间,记做cross:```{max(a,c), min(b,d)}```,注意该区间可能为空。 +2. 计算属于区间ab但不属于cd的区域,记做A ```cpp if (a<=c-1) A.push_back({a, c-1}); if (d+1<=b) A.push_back({d+1, b}); ``` -3. 计算属于区间cd但不属于ab的区域:B +3. 计算属于区间cd但不属于ab的区域,记做B ```cpp if (c<=a-1) B.push_back({c,a-1}); if (b+1<=d) B.push_back({b+1,d}); ``` -4. 计算要么属于ab要么属于cd的区间:Union,就是以上cross, A, B里面区间的合并。 +4. 计算要么属于ab要么属于cd的区间,记做Union,其实就是以上cross, A, B里面区间的合并。 判断合法的条件有如下: 1. 在Union之外的区域,必须要求s和t每个字符都相等。这里有一个巧妙的判定方法。我们构造前缀数组diff[i]表示前i个位置里有多少个s与t字母不相同的位置。于是我们只需要查验Union里面的、不同字母的位置个数,是否等于diff[m]即可。 From 0fa60efddd29da3cd2e3dbe8396e51e74cf9f1dd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 11:57:20 -0800 Subject: [PATCH 2368/2729] Create 3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp --- ...ber-of-Houses-at-a-Certain-Distance-II.cpp | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp new file mode 100644 index 000000000..30d63aa65 --- /dev/null +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp @@ -0,0 +1,95 @@ +using LL = long long; +class Solution { + LL rets[100005]; + int n; +public: + vector countOfPairs(int n, int x, int y) + { + if (x>y) return countOfPairs(n,y,x); + vectorans; + this->n = n; + + if (x==y || abs(x-y)==1) + { + for (int t=1; t<=n; t++) + ans.push_back((n-t)*2); + return ans; + } + + LL ret = 0; + int d = y-x-1; + + helper0(x-1); //AA + helper0(n-y); //BB + + helper1(x-1, n-y); //AB + helper2(x, (d+1)/2, d/2+1); //AC + + helper2(n-y+1, (d+1)/2, d/2+1); //BC + + for (int t=1; t<=n; t++) + rets[t] *= 2; + + helper3(d+2); // CC + + for (int t=1; t<=n; t++) + ans.push_back(rets[t]); + return ans; + } + + void helper0(LL a) + { + for (int t=1; t<=n; t++) + { + LL start = 1; + LL end = a-t; + rets[t] += max(0LL, end-start+1); + } + + } + + void helper1(LL a, LL b) + { + for (int t=1; t<=n; t++) + { + LL start = max(a+3-t, 1ll); + LL end = min(a+2+b-t, a); + rets[t] += max(0LL, end-start+1); + } + } + + void helper2(LL a, LL b, LL c) + { + for (int t=1; t<=n; t++) + { + LL start = max(a+1-t, 1ll); + LL end = min(a+b-t, a-1); + rets[t] += max(0LL, end-start+1); + } + + for (int t=1; t<=n; t++) + { + LL start = max(a+1-t, 1ll); + LL end = min(a+c-t, a-1); + rets[t] += max(0LL, end-start+1); + } + + for (int t=1; t<=n; t++) + { + if (a-1>=t) + rets[t] += 1; + } + + } + + void helper3(LL d) + { + for (int t=1; t<=n; t++) + { + if (2*t Date: Sun, 21 Jan 2024 11:58:12 -0800 Subject: [PATCH 2369/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e3ecee4cb..14f337ab1 100644 --- a/Readme.md +++ b/Readme.md @@ -1136,6 +1136,7 @@ [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) +[3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II) (H) * ``Dijkstra`` [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) From 9a6065daf094256aa04af74249f79d9c019721e2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:24:10 -0800 Subject: [PATCH 2370/2729] Create Readme.md --- .../Readme.md | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md new file mode 100644 index 000000000..9763aa55a --- /dev/null +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -0,0 +1,66 @@ +### 3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II + +我们画一个示意图,将图划分为ABC三个区域,其中[x,y]部分为C。 +``` +A-A-A-C(x)-C------C-C(y)-B-B-B + |______________| +``` + +任意两个房子之间的最短距离,可以落入如下六个分类之中, AA,BB,AC,BC,AB,CC. 比如AC表示其中一个放在位于A区,另一个房子位于C区。我们分类讨论。 + +1. AA:对于长度为a个房子的简单串联,里面有多少对距离为t的配对呢?我们记做`helper0(a)` + +对于一个合法配对,将第一个房子记做i,则另一个房子记做i+t,那么要求 +``` +i>=1 +i+t<=a-1 +``` +得到i的范围是[1, a-1-t]. 故对于距离t,我们可以增加`a-1-t`个配对(暂时不计首尾互换的重复路径) + +2. BB,计算方法同AA。 + +3. AC:这部分是由一个长度为a的长链,加上一个长度为d的圆环。里面有多少对距离为t的配对呢? + +显然,对于处于圆环上的点,为了与A实现最短距离,我们会根据它们离圆环入口x的位置,平均拆分成两半。这样就行程了三叉的形状:一条单链长度是a+1,然后接着两条支链,长度分别是d/2和(d-1)/2. + +对于在单链上的任意一点i,与长度为b的支链上的任意一点(不包括x点)能组成合法配对的条件是 +``` +i>=1 +i+t>=a+2 +i+t<=a+b +``` +得到i的范围是[1, min(a+b-t,a+b-t)]. 由此可以计算出有多少个配对。 + +同理,可以计算单链上的任意一点,与长度为c的另一条支链上的任意一点(不包括x点)能组成的合法配对。 + +此外,我们需要单独出计算单链上的任意一点i,到x点能组成的合法配对。单独计算这个是为了避免在处理两条支链时重复计算。 +``` +i>=1 +i+t==a+1 +``` +即需要满足t<=a-1时,可以增加一个配对。 + +4. BC,计算方法同AC + +5. AB,计算方法类似AA。假设A的部分长度是a,B的部分长度是b,中间间隔了2(因为x和y相连)。里面有多少对距离为t的配对呢?我们记做`helper2(a)` + +对于在A上的任意一点i,与B上的任意一点能组成合法配对的条件是 +``` +i>=1 +i<=a +i+t>=a+3 +i+t<=a+2+b +``` +得到i的范围是[max(1,a), min(a+3-t,a+b+2-t)]. 由此可以计算出有多少个配对。 + +6. CC,此部分是一个长度为d的圆环,问里面有多少个长度为t的配对? + +对于圆环上任意一点i,顺时针走t步到达i+t的位置。这两个位置要形成一个有效配对,此时要保证它们的逆时针路径要小于t。即 +``` +t < d-t +``` +对于满足这个要求的t,那么圆环上的任意一点都是可以合法配对的起点,故可以增加d个配对。比如说d=4,那么当t=1时的四个配对是[1,2],[2,3],[3,4],[4,1]. + +此时有一个特别需要注意的地方,当`2*t==d`时,虽然也可以增加d个配对,但是这d个配对里,已经包含了首尾颠倒的重复路径。比如说d=4,那么当t=2时的四个配对是[1,3],[2,4],[3,1],[4,2],可以其中包含了重复的路径。而我们之前所有情况的讨论,所计算的配对都是单向的(编号小的在前,编号大的在后),都是需要乘以2的。唯独这个情况下,我们不能再乘以2. + +将以上六种情况的计数全部加起来就是最终答案。 From 621092f40d7585689375bcec722ef5aa626a1f28 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:25:35 -0800 Subject: [PATCH 2371/2729] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index 9763aa55a..a8424ed27 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -13,9 +13,9 @@ A-A-A-C(x)-C------C-C(y)-B-B-B 对于一个合法配对,将第一个房子记做i,则另一个房子记做i+t,那么要求 ``` i>=1 -i+t<=a-1 +i+t<=a ``` -得到i的范围是[1, a-1-t]. 故对于距离t,我们可以增加`a-1-t`个配对(暂时不计首尾互换的重复路径) +得到i的范围是[1, a-t]. 故对于距离t,我们可以增加`a-t`个配对(暂时不计首尾互换的重复路径) 2. BB,计算方法同AA。 From 9299516d5bcfa837ebc2f914ae97561f130e6069 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:26:54 -0800 Subject: [PATCH 2372/2729] Update Readme.md --- .../Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index a8424ed27..6c0f7fa4e 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -27,9 +27,10 @@ i+t<=a ``` i>=1 i+t>=a+2 +i<=a i+t<=a+b ``` -得到i的范围是[1, min(a+b-t,a+b-t)]. 由此可以计算出有多少个配对。 +得到i的范围是[max(1,a+2-t), min(a,a+b-t)]. 由此可以计算出有多少个配对。 同理,可以计算单链上的任意一点,与长度为c的另一条支链上的任意一点(不包括x点)能组成的合法配对。 From b29640f60d6f2a3137ee1689b8ca268c40463dd1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:28:23 -0800 Subject: [PATCH 2373/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index 6c0f7fa4e..1e8dd940f 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -52,7 +52,7 @@ i<=a i+t>=a+3 i+t<=a+2+b ``` -得到i的范围是[max(1,a), min(a+3-t,a+b+2-t)]. 由此可以计算出有多少个配对。 +得到i的范围是[max(1,a+3-t), min(a,a+b+2-t)]. 由此可以计算出有多少个配对。 6. CC,此部分是一个长度为d的圆环,问里面有多少个长度为t的配对? From bd40124134fb13cbf8d07aa321b648ea7d6e5bdc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:53:50 -0800 Subject: [PATCH 2374/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index 1e8dd940f..05395bbfa 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -39,7 +39,7 @@ i+t<=a+b i>=1 i+t==a+1 ``` -即需要满足t<=a-1时,可以增加一个配对。 +即需要满足t<=a时,可以增加一个配对。 4. BC,计算方法同AC From 38714f67203a17311b9ef7988b3f36f1cd23384f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 16:10:58 -0800 Subject: [PATCH 2375/2729] Update 3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp --- ...ber-of-Houses-at-a-Certain-Distance-II.cpp | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp index 30d63aa65..c82560c76 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp @@ -17,20 +17,20 @@ class Solution { } LL ret = 0; - int d = y-x-1; + int d = y-x+1; helper0(x-1); //AA helper0(n-y); //BB helper1(x-1, n-y); //AB - helper2(x, (d+1)/2, d/2+1); //AC - - helper2(n-y+1, (d+1)/2, d/2+1); //BC + + helper2(x-1, (d-1)/2, (d-1)-(d-1)/2); //AC + helper2(n-y, (d-1)/2, (d-1)-(d-1)/2); //BC for (int t=1; t<=n; t++) rets[t] *= 2; - helper3(d+2); // CC + helper3(d); // CC for (int t=1; t<=n; t++) ans.push_back(rets[t]); @@ -56,27 +56,27 @@ class Solution { LL end = min(a+2+b-t, a); rets[t] += max(0LL, end-start+1); } - } - + } + void helper2(LL a, LL b, LL c) { for (int t=1; t<=n; t++) { - LL start = max(a+1-t, 1ll); - LL end = min(a+b-t, a-1); + LL start = max(a+2-t, 1ll); + LL end = min(a+1+b-t, a); rets[t] += max(0LL, end-start+1); } for (int t=1; t<=n; t++) { - LL start = max(a+1-t, 1ll); - LL end = min(a+c-t, a-1); + LL start = max(a+2-t, 1ll); + LL end = min(a+1+c-t, a); rets[t] += max(0LL, end-start+1); } for (int t=1; t<=n; t++) { - if (a-1>=t) + if (a>=t) rets[t] += 1; } From 43c89764659f07dc0b1f292639063fb319f183bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 16:12:45 -0800 Subject: [PATCH 2376/2729] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index 05395bbfa..09dc30780 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -28,9 +28,9 @@ i+t<=a i>=1 i+t>=a+2 i<=a -i+t<=a+b +i+t<=a+1+b ``` -得到i的范围是[max(1,a+2-t), min(a,a+b-t)]. 由此可以计算出有多少个配对。 +得到i的范围是[max(1,a+2-t), min(a,a+b+1-t)]. 由此可以计算出有多少个配对。 同理,可以计算单链上的任意一点,与长度为c的另一条支链上的任意一点(不包括x点)能组成的合法配对。 From 5c7424a3da37512e7ce2b04c26721226cd9e72a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 18:11:56 -0800 Subject: [PATCH 2377/2729] Update 3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp --- ...ber-of-Houses-at-a-Certain-Distance-II.cpp | 115 +++++++++--------- 1 file changed, 58 insertions(+), 57 deletions(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp index c82560c76..4e0fb5d7c 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp @@ -1,95 +1,96 @@ using LL = long long; class Solution { - LL rets[100005]; + LL count[100005]; int n; public: vector countOfPairs(int n, int x, int y) { - if (x>y) return countOfPairs(n,y,x); - vectorans; + if (x>y) return countOfPairs(n, y, x); this->n = n; - - if (x==y || abs(x-y)==1) + + vectorrets; + + if (abs(x-y)<=1) { for (int t=1; t<=n; t++) - ans.push_back((n-t)*2); - return ans; + rets.push_back((n-t)*2); + return rets; } - - LL ret = 0; + + f1(x-1); + f1(n-y); + + cout<<"OK"<=t) - rets[t] += 1; - } - + if (a>=t) count[t] += 1; + } } - - void helper3(LL d) + + void f4(LL d) { for (int t=1; t<=n; t++) { - if (2*t Date: Sun, 21 Jan 2024 23:02:51 -0800 Subject: [PATCH 2378/2729] rename heap to sorted_container --- .../1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp | 0 .../1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md | 0 .../1348.Tweet-Counts-Per-Frequency.cpp | 0 .../1348.Tweet-Counts-Per-Frequency/Readme.md | 0 .../1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp | 0 {Heap => Sorted_Container}/1488.Avoid-Flood-in-The-City/Readme.md | 0 .../1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp | 0 .../Readme.md | 0 .../1675.Minimize-Deviation-in-Array.cpp | 0 .../1675.Minimize-Deviation-in-Array/Readme.md | 0 .../1825.Finding-MK-Average/1825.Finding-MK-Average.cpp | 0 {Heap => Sorted_Container}/1825.Finding-MK-Average/Readme.md | 0 .../1847.Closest-Room/1847.Closest-Room.cpp | 0 {Heap => Sorted_Container}/1847.Closest-Room/Readme.md | 0 .../1912.Design-Movie-Rental-System.cpp | 0 .../1912.Design-Movie-Rental-System/Readme.md | 0 .../2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp | 0 .../2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp | 0 .../2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp | 0 .../2102.Sequentially-Ordinal-Rank-Tracker/Readme.md | 0 .../220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp | 0 {Heap => Sorted_Container}/220.Contains-Duplicate-III/Readme.md | 0 .../2213.Longest-Substring-of-One-Repeating-Character.cpp | 0 .../2213.Longest-Substring-of-One-Repeating-Character/Readme.md | 0 .../2276.Count-Integers-in-Intervals.cpp | 0 .../2276.Count-Integers-in-Intervals/Readme.md | 0 .../2382.Maximum-Segment-Sum-After-Removals.cpp | 0 .../2382.Maximum-Segment-Sum-After-Removals/Readme.md | 0 .../2612.Minimum-Reverse-Operations.cpp | 0 .../2612.Minimum-Reverse-Operations/Readme.md | 0 .../2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp | 0 {Heap => Sorted_Container}/2653.Sliding-Subarray-Beauty/Readme.md | 0 .../2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp | 0 {Heap => Sorted_Container}/2736.Maximum-Sum-Queries/Readme.md | 0 ...07.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp | 0 ...07.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp | 0 .../Readme.md | 0 .../2926.Maximum-Balanced-Subsequence-Sum.cpp | 0 .../2926.Maximum-Balanced-Subsequence-Sum/Readme.md | 0 .../2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp | 0 .../2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md | 0 .../2945.Find-Maximum-Non-decreasing-Array-Length.cpp | 0 .../2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md | 0 .../295.Find-Median-from-Data-Stream.cpp | 0 .../295.Find-Median-from-Data-Stream_v2.cpp | 0 .../295.Find-Median-from-Data-Stream/Readme.md | 0 .../352.Data Stream as Disjoint Intervals.cpp | 0 .../352.Data-Stream-as-Disjoint-Intervals-v2.cpp | 0 .../352.Data-Stream-as-Disjoint-Intervals-v3.cpp | 0 .../352.Data-Stream-as-Disjoint-Intervals/Readme.md | 0 .../363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp | 0 .../363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md | 0 .../480.Sliding-Window-Median/480.Sliding-Window-Median.cpp | 0 {Heap => Sorted_Container}/480.Sliding-Window-Median/Readme.md | 0 .../632.Smallest-Range-Covering-Elements-from-K-Lists.cpp | 0 .../632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md | 0 .../729.My-Calendar-I/729.My-Calendar-I.cpp | 0 {Heap => Sorted_Container}/729.My-Calendar-I/Readme.md | 0 {Heap => Sorted_Container}/855.Exam-Room/855.Exam-Room.cpp | 0 {Heap => Sorted_Container}/855.Exam-Room/Readme.md | 0 .../975.Odd-Even-Jump/975.Odd-Even-Jump.cpp | 0 {Heap => Sorted_Container}/975.Odd-Even-Jump/Readme.md | 0 62 files changed, 0 insertions(+), 0 deletions(-) rename {Heap => Sorted_Container}/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp (100%) rename {Heap => Sorted_Container}/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md (100%) rename {Heap => Sorted_Container}/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp (100%) rename {Heap => Sorted_Container}/1348.Tweet-Counts-Per-Frequency/Readme.md (100%) rename {Heap => Sorted_Container}/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp (100%) rename {Heap => Sorted_Container}/1488.Avoid-Flood-in-The-City/Readme.md (100%) rename {Heap => Sorted_Container}/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp (100%) rename {Heap => Sorted_Container}/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md (100%) rename {Heap => Sorted_Container}/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp (100%) rename {Heap => Sorted_Container}/1675.Minimize-Deviation-in-Array/Readme.md (100%) rename {Heap => Sorted_Container}/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp (100%) rename {Heap => Sorted_Container}/1825.Finding-MK-Average/Readme.md (100%) rename {Heap => Sorted_Container}/1847.Closest-Room/1847.Closest-Room.cpp (100%) rename {Heap => Sorted_Container}/1847.Closest-Room/Readme.md (100%) rename {Heap => Sorted_Container}/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp (100%) rename {Heap => Sorted_Container}/1912.Design-Movie-Rental-System/Readme.md (100%) rename {Heap => Sorted_Container}/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp (100%) rename {Heap => Sorted_Container}/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp (100%) rename {Heap => Sorted_Container}/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp (100%) rename {Heap => Sorted_Container}/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md (100%) rename {Heap => Sorted_Container}/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp (100%) rename {Heap => Sorted_Container}/220.Contains-Duplicate-III/Readme.md (100%) rename {Heap => Sorted_Container}/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp (100%) rename {Heap => Sorted_Container}/2213.Longest-Substring-of-One-Repeating-Character/Readme.md (100%) rename {Heap => Sorted_Container}/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp (100%) rename {Heap => Sorted_Container}/2276.Count-Integers-in-Intervals/Readme.md (100%) rename {Heap => Sorted_Container}/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp (100%) rename {Heap => Sorted_Container}/2382.Maximum-Segment-Sum-After-Removals/Readme.md (100%) rename {Heap => Sorted_Container}/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp (100%) rename {Heap => Sorted_Container}/2612.Minimum-Reverse-Operations/Readme.md (100%) rename {Heap => Sorted_Container}/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp (100%) rename {Heap => Sorted_Container}/2653.Sliding-Subarray-Beauty/Readme.md (100%) rename {Heap => Sorted_Container}/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp (100%) rename {Heap => Sorted_Container}/2736.Maximum-Sum-Queries/Readme.md (100%) rename {Heap => Sorted_Container}/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp (100%) rename {Heap => Sorted_Container}/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp (100%) rename {Heap => Sorted_Container}/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md (100%) rename {Heap => Sorted_Container}/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp (100%) rename {Heap => Sorted_Container}/2926.Maximum-Balanced-Subsequence-Sum/Readme.md (100%) rename {Heap => Sorted_Container}/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp (100%) rename {Heap => Sorted_Container}/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md (100%) rename {Heap => Sorted_Container}/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp (100%) rename {Heap => Sorted_Container}/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md (100%) rename {Heap => Sorted_Container}/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp (100%) rename {Heap => Sorted_Container}/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp (100%) rename {Heap => Sorted_Container}/295.Find-Median-from-Data-Stream/Readme.md (100%) rename {Heap => Sorted_Container}/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp (100%) rename {Heap => Sorted_Container}/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp (100%) rename {Heap => Sorted_Container}/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp (100%) rename {Heap => Sorted_Container}/352.Data-Stream-as-Disjoint-Intervals/Readme.md (100%) rename {Heap => Sorted_Container}/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp (100%) rename {Heap => Sorted_Container}/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md (100%) rename {Heap => Sorted_Container}/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp (100%) rename {Heap => Sorted_Container}/480.Sliding-Window-Median/Readme.md (100%) rename {Heap => Sorted_Container}/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp (100%) rename {Heap => Sorted_Container}/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md (100%) rename {Heap => Sorted_Container}/729.My-Calendar-I/729.My-Calendar-I.cpp (100%) rename {Heap => Sorted_Container}/729.My-Calendar-I/Readme.md (100%) rename {Heap => Sorted_Container}/855.Exam-Room/855.Exam-Room.cpp (100%) rename {Heap => Sorted_Container}/855.Exam-Room/Readme.md (100%) rename {Heap => Sorted_Container}/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp (100%) rename {Heap => Sorted_Container}/975.Odd-Even-Jump/Readme.md (100%) diff --git a/Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp b/Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp similarity index 100% rename from Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp rename to Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp diff --git a/Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md b/Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md similarity index 100% rename from Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md rename to Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md diff --git a/Heap/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp b/Sorted_Container/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp similarity index 100% rename from Heap/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp rename to Sorted_Container/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp diff --git a/Heap/1348.Tweet-Counts-Per-Frequency/Readme.md b/Sorted_Container/1348.Tweet-Counts-Per-Frequency/Readme.md similarity index 100% rename from Heap/1348.Tweet-Counts-Per-Frequency/Readme.md rename to Sorted_Container/1348.Tweet-Counts-Per-Frequency/Readme.md diff --git a/Heap/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp b/Sorted_Container/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp similarity index 100% rename from Heap/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp rename to Sorted_Container/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp diff --git a/Heap/1488.Avoid-Flood-in-The-City/Readme.md b/Sorted_Container/1488.Avoid-Flood-in-The-City/Readme.md similarity index 100% rename from Heap/1488.Avoid-Flood-in-The-City/Readme.md rename to Sorted_Container/1488.Avoid-Flood-in-The-City/Readme.md diff --git a/Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp b/Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp similarity index 100% rename from Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp rename to Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp diff --git a/Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md b/Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md similarity index 100% rename from Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md rename to Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md diff --git a/Heap/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp b/Sorted_Container/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp similarity index 100% rename from Heap/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp rename to Sorted_Container/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp diff --git a/Heap/1675.Minimize-Deviation-in-Array/Readme.md b/Sorted_Container/1675.Minimize-Deviation-in-Array/Readme.md similarity index 100% rename from Heap/1675.Minimize-Deviation-in-Array/Readme.md rename to Sorted_Container/1675.Minimize-Deviation-in-Array/Readme.md diff --git a/Heap/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp b/Sorted_Container/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp similarity index 100% rename from Heap/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp rename to Sorted_Container/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp diff --git a/Heap/1825.Finding-MK-Average/Readme.md b/Sorted_Container/1825.Finding-MK-Average/Readme.md similarity index 100% rename from Heap/1825.Finding-MK-Average/Readme.md rename to Sorted_Container/1825.Finding-MK-Average/Readme.md diff --git a/Heap/1847.Closest-Room/1847.Closest-Room.cpp b/Sorted_Container/1847.Closest-Room/1847.Closest-Room.cpp similarity index 100% rename from Heap/1847.Closest-Room/1847.Closest-Room.cpp rename to Sorted_Container/1847.Closest-Room/1847.Closest-Room.cpp diff --git a/Heap/1847.Closest-Room/Readme.md b/Sorted_Container/1847.Closest-Room/Readme.md similarity index 100% rename from Heap/1847.Closest-Room/Readme.md rename to Sorted_Container/1847.Closest-Room/Readme.md diff --git a/Heap/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp b/Sorted_Container/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp similarity index 100% rename from Heap/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp rename to Sorted_Container/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp diff --git a/Heap/1912.Design-Movie-Rental-System/Readme.md b/Sorted_Container/1912.Design-Movie-Rental-System/Readme.md similarity index 100% rename from Heap/1912.Design-Movie-Rental-System/Readme.md rename to Sorted_Container/1912.Design-Movie-Rental-System/Readme.md diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp b/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp similarity index 100% rename from Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp rename to Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp b/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp similarity index 100% rename from Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp rename to Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp b/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp similarity index 100% rename from Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp rename to Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md b/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md similarity index 100% rename from Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md rename to Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md diff --git a/Heap/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp b/Sorted_Container/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp similarity index 100% rename from Heap/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp rename to Sorted_Container/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp diff --git a/Heap/220.Contains-Duplicate-III/Readme.md b/Sorted_Container/220.Contains-Duplicate-III/Readme.md similarity index 100% rename from Heap/220.Contains-Duplicate-III/Readme.md rename to Sorted_Container/220.Contains-Duplicate-III/Readme.md diff --git a/Heap/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp b/Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp similarity index 100% rename from Heap/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp rename to Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp diff --git a/Heap/2213.Longest-Substring-of-One-Repeating-Character/Readme.md b/Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character/Readme.md similarity index 100% rename from Heap/2213.Longest-Substring-of-One-Repeating-Character/Readme.md rename to Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character/Readme.md diff --git a/Heap/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp b/Sorted_Container/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp similarity index 100% rename from Heap/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp rename to Sorted_Container/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp diff --git a/Heap/2276.Count-Integers-in-Intervals/Readme.md b/Sorted_Container/2276.Count-Integers-in-Intervals/Readme.md similarity index 100% rename from Heap/2276.Count-Integers-in-Intervals/Readme.md rename to Sorted_Container/2276.Count-Integers-in-Intervals/Readme.md diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp b/Sorted_Container/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp similarity index 100% rename from Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp rename to Sorted_Container/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md b/Sorted_Container/2382.Maximum-Segment-Sum-After-Removals/Readme.md similarity index 100% rename from Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md rename to Sorted_Container/2382.Maximum-Segment-Sum-After-Removals/Readme.md diff --git a/Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp b/Sorted_Container/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp similarity index 100% rename from Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp rename to Sorted_Container/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp diff --git a/Heap/2612.Minimum-Reverse-Operations/Readme.md b/Sorted_Container/2612.Minimum-Reverse-Operations/Readme.md similarity index 100% rename from Heap/2612.Minimum-Reverse-Operations/Readme.md rename to Sorted_Container/2612.Minimum-Reverse-Operations/Readme.md diff --git a/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp b/Sorted_Container/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp similarity index 100% rename from Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp rename to Sorted_Container/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp diff --git a/Heap/2653.Sliding-Subarray-Beauty/Readme.md b/Sorted_Container/2653.Sliding-Subarray-Beauty/Readme.md similarity index 100% rename from Heap/2653.Sliding-Subarray-Beauty/Readme.md rename to Sorted_Container/2653.Sliding-Subarray-Beauty/Readme.md diff --git a/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp b/Sorted_Container/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp similarity index 100% rename from Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp rename to Sorted_Container/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Sorted_Container/2736.Maximum-Sum-Queries/Readme.md similarity index 100% rename from Heap/2736.Maximum-Sum-Queries/Readme.md rename to Sorted_Container/2736.Maximum-Sum-Queries/Readme.md diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp b/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp similarity index 100% rename from Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp rename to Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp b/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp similarity index 100% rename from Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp rename to Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md b/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md similarity index 100% rename from Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md rename to Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp b/Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp similarity index 100% rename from Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp rename to Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md b/Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum/Readme.md similarity index 100% rename from Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md rename to Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum/Readme.md diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp b/Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp similarity index 100% rename from Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp rename to Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md b/Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md similarity index 100% rename from Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md rename to Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp b/Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp similarity index 100% rename from Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp rename to Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md b/Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md similarity index 100% rename from Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md rename to Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md diff --git a/Heap/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp b/Sorted_Container/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp similarity index 100% rename from Heap/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp rename to Sorted_Container/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp diff --git a/Heap/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp b/Sorted_Container/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp similarity index 100% rename from Heap/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp rename to Sorted_Container/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp diff --git a/Heap/295.Find-Median-from-Data-Stream/Readme.md b/Sorted_Container/295.Find-Median-from-Data-Stream/Readme.md similarity index 100% rename from Heap/295.Find-Median-from-Data-Stream/Readme.md rename to Sorted_Container/295.Find-Median-from-Data-Stream/Readme.md diff --git a/Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp b/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp similarity index 100% rename from Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp rename to Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp diff --git a/Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp b/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp similarity index 100% rename from Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp rename to Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp diff --git a/Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp b/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp similarity index 100% rename from Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp rename to Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp diff --git a/Heap/352.Data-Stream-as-Disjoint-Intervals/Readme.md b/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/Readme.md similarity index 100% rename from Heap/352.Data-Stream-as-Disjoint-Intervals/Readme.md rename to Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/Readme.md diff --git a/Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp b/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp similarity index 100% rename from Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp rename to Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp diff --git a/Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md b/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md similarity index 100% rename from Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md rename to Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md diff --git a/Heap/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp b/Sorted_Container/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp similarity index 100% rename from Heap/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp rename to Sorted_Container/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp diff --git a/Heap/480.Sliding-Window-Median/Readme.md b/Sorted_Container/480.Sliding-Window-Median/Readme.md similarity index 100% rename from Heap/480.Sliding-Window-Median/Readme.md rename to Sorted_Container/480.Sliding-Window-Median/Readme.md diff --git a/Heap/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp b/Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp similarity index 100% rename from Heap/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp rename to Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp diff --git a/Heap/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md b/Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md similarity index 100% rename from Heap/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md rename to Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md diff --git a/Heap/729.My-Calendar-I/729.My-Calendar-I.cpp b/Sorted_Container/729.My-Calendar-I/729.My-Calendar-I.cpp similarity index 100% rename from Heap/729.My-Calendar-I/729.My-Calendar-I.cpp rename to Sorted_Container/729.My-Calendar-I/729.My-Calendar-I.cpp diff --git a/Heap/729.My-Calendar-I/Readme.md b/Sorted_Container/729.My-Calendar-I/Readme.md similarity index 100% rename from Heap/729.My-Calendar-I/Readme.md rename to Sorted_Container/729.My-Calendar-I/Readme.md diff --git a/Heap/855.Exam-Room/855.Exam-Room.cpp b/Sorted_Container/855.Exam-Room/855.Exam-Room.cpp similarity index 100% rename from Heap/855.Exam-Room/855.Exam-Room.cpp rename to Sorted_Container/855.Exam-Room/855.Exam-Room.cpp diff --git a/Heap/855.Exam-Room/Readme.md b/Sorted_Container/855.Exam-Room/Readme.md similarity index 100% rename from Heap/855.Exam-Room/Readme.md rename to Sorted_Container/855.Exam-Room/Readme.md diff --git a/Heap/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp b/Sorted_Container/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp similarity index 100% rename from Heap/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp rename to Sorted_Container/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp diff --git a/Heap/975.Odd-Even-Jump/Readme.md b/Sorted_Container/975.Odd-Even-Jump/Readme.md similarity index 100% rename from Heap/975.Odd-Even-Jump/Readme.md rename to Sorted_Container/975.Odd-Even-Jump/Readme.md From ce6f055be352e701d6cdaad3e8f6d83fe0622b51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:05:34 -0800 Subject: [PATCH 2379/2729] Update Readme.md --- Readme.md | 64 +++++++++++++++++++++++++++---------------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/Readme.md b/Readme.md index 14f337ab1..ce35495c9 100644 --- a/Readme.md +++ b/Readme.md @@ -202,41 +202,41 @@ [2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) [2950.Number-of-Divisible-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2950.Number-of-Divisible-Substrings) (H-) -#### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) -[220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) -[295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Heap/295.Find-Median-from-Data-Stream) (M) -[363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) -[352.Data-Stream-as-Disjoint-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/352.Data-Stream-as-Disjoint-Intervals) (H) -[480.Sliding-Window-Median](https://github.com/wisdompeak/LeetCode/blob/master/Heap/480.Sliding-Window-Median) (H) +#### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/sorted_container) +[220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/220.Contains-Duplicate-III) (M) +[295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/295.Find-Median-from-Data-Stream) (M) +[363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) +[352.Data-Stream-as-Disjoint-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals) (H) +[480.Sliding-Window-Median](https://github.com/wisdompeak/LeetCode/blob/master/Sorted_Container/480.Sliding-Window-Median) (H) [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) -[729.My-Calendar-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/729.My-Calendar-I) (M) -[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/855.Exam-Room) (M+) -[975.Odd-Even-Jump](https://github.com/wisdompeak/LeetCode/tree/master/Heap/975.Odd-Even-Jump) (H-) -[632.Smallest-Range-Covering-Elements-from-K-Lists](https://github.com/wisdompeak/LeetCode/tree/master/Heap/632.Smallest-Range-Covering-Elements-from-K-Lists) (H-) -[1675.Minimize-Deviation-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1675.Minimize-Deviation-in-Array) (H) -[1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers) (M) +[729.My-Calendar-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/729.My-Calendar-I) (M) +[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/855.Exam-Room) (M+) +[975.Odd-Even-Jump](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/975.Odd-Even-Jump) (H-) +[632.Smallest-Range-Covering-Elements-from-K-Lists](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists) (H-) +[1675.Minimize-Deviation-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1675.Minimize-Deviation-in-Array) (H) +[1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers) (M) 1348.Tweet-Counts-Per-Frequency (H-) -[1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1488.Avoid-Flood-in-The-City) (H-) -[1606.Find-Servers-That-Handled-Most-Number-of-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests) (M) +[1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1488.Avoid-Flood-in-The-City) (H-) +[1606.Find-Servers-That-Handled-Most-Number-of-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests) (M) 1797.Design Authentication Manager (M) -[1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1825.Finding-MK-Average) (H) -[1847.Closest-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1847.Closest-Room) (M+) -[1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) +[1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1825.Finding-MK-Average) (H) +[1847.Closest-Room](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1847.Closest-Room) (M+) +[1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) -[2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) -[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) -[2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2736.Maximum-Sum-Queries) (H) +[2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2612.Minimum-Reverse-Operations) (H) +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) +[2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2736.Maximum-Sum-Queries) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) -[2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) -[2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) -[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) -* ``Monotonic Heap`` -[2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) -[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) -[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) -[2945.Find-Maximum-Non-decreasing-Array-Length](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2945.Find-Maximum-Non-decreasing-Array-Length) (H) +[2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character) (H) +[2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2276.Count-Integers-in-Intervals) (H-) +[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2382.Maximum-Segment-Sum-After-Removals) (M+) +* ``Sorted_Container w/ monotonic mapping values`` +[2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) +[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum) (H) +[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) +[2945.Find-Maximum-Non-decreasing-Array-Length](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) @@ -344,7 +344,7 @@ [2286.Booking-Concert-Tickets-in-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups) (H-) [2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) -[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) +[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) #### [Binary Index Tree] @@ -485,9 +485,9 @@ [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) -[2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) +[2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker) (H-) [2402.Meeting-Rooms-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2402.Meeting-Rooms-III) (M+) -[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) * ``Sort+PQ`` [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) @@ -625,7 +625,7 @@ [2503.Maximum-Number-of-Points-From-Grid-Queries](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries) (H-) [505.The-Maze-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/505.The-Maze-II) (H-) [499.The-Maze-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/499.The-Maze-III) (H) -[787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) +[787.CSorted_Containerest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.CSorted_Containerest-Flights-Within-K-Stops) (H) [882.Reachable-Nodes-In-Subdivided-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/882.Reachable-Nodes-In-Subdivided-Graph ) (H) [1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) [1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid) (H) From 236d192577338474786d3fb10a6ef4e0eedb5d03 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:06:31 -0800 Subject: [PATCH 2380/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ce35495c9..cb3ed0c63 100644 --- a/Readme.md +++ b/Readme.md @@ -202,7 +202,7 @@ [2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) [2950.Number-of-Divisible-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2950.Number-of-Divisible-Substrings) (H-) -#### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/sorted_container) +#### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/220.Contains-Duplicate-III) (M) [295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/295.Find-Median-from-Data-Stream) (M) [363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) From 2d92779d76f2efb0ff2903f058cba17fb34fc59e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:07:28 -0800 Subject: [PATCH 2381/2729] Create 3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp --- ...ay-Into-Subarrays-With-Minimum-Cost-II.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp diff --git a/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp b/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp new file mode 100644 index 000000000..bc7aaec45 --- /dev/null +++ b/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp @@ -0,0 +1,58 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(vector& nums, int k, int dist) + { + int n = nums.size(); + + multisetSet1; + multisetSet2; + + LL sum = 0; + LL ret = LLONG_MAX; + + k--; + + for (int i=1; i=dist+1) + { + ret = min(ret, sum); + + int t = nums[i-dist]; + if (Set2.find(t)!=Set2.end()) + Set2.erase(Set2.find(t)); + else + { + Set1.erase(Set1.find(t)); + sum -= t; + if (!Set2.empty()) + { + Set1.insert(*Set2.begin()); + sum += *Set2.begin(); + Set2.erase(Set2.begin()); + } + } + } + } + + return ret + nums[0]; + + } +}; From 6e9a97df09935be1bdcdedcb0b37b08f6423f470 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:08:14 -0800 Subject: [PATCH 2382/2729] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cb3ed0c63..ec0b127e6 100644 --- a/Readme.md +++ b/Readme.md @@ -225,8 +225,10 @@ 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2612.Minimum-Reverse-Operations) (H) -[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2736.Maximum-Sum-Queries) (H) +* ``Dual Container`` +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) +[3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II) (H-) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character) (H) From 0c3a03b1ab67ee1a0ee7f9f1602673f555a1ed2b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:09:49 -0800 Subject: [PATCH 2383/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index ec0b127e6..40007eeb9 100644 --- a/Readme.md +++ b/Readme.md @@ -219,14 +219,14 @@ [1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1488.Avoid-Flood-in-The-City) (H-) [1606.Find-Servers-That-Handled-Most-Number-of-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests) (M) 1797.Design Authentication Manager (M) -[1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1825.Finding-MK-Average) (H) [1847.Closest-Room](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1847.Closest-Room) (M+) [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2612.Minimum-Reverse-Operations) (H) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2736.Maximum-Sum-Queries) (H) -* ``Dual Container`` +* ``Dual Multiset`` +[1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1825.Finding-MK-Average) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) [3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II) (H-) * ``Maintain intervals`` From 326bf86716831b0b4236e23dc93d02dc14b55e98 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:11:14 -0800 Subject: [PATCH 2384/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 40007eeb9..3cbad2611 100644 --- a/Readme.md +++ b/Readme.md @@ -204,7 +204,6 @@ #### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/220.Contains-Duplicate-III) (M) -[295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/295.Find-Median-from-Data-Stream) (M) [363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) [352.Data-Stream-as-Disjoint-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals) (H) [480.Sliding-Window-Median](https://github.com/wisdompeak/LeetCode/blob/master/Sorted_Container/480.Sliding-Window-Median) (H) @@ -226,6 +225,7 @@ [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2612.Minimum-Reverse-Operations) (H) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2736.Maximum-Sum-Queries) (H) * ``Dual Multiset`` +[295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/295.Find-Median-from-Data-Stream) (M) [1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1825.Finding-MK-Average) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) [3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II) (H-) From f283da154263df093092c20d3c9669788c316cce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:35:38 -0800 Subject: [PATCH 2385/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/Readme.md diff --git a/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/Readme.md b/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/Readme.md new file mode 100644 index 000000000..e647631d7 --- /dev/null +++ b/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/Readme.md @@ -0,0 +1,11 @@ +### 3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II + +本题的本质就是从nums[1]开始,寻找一个长度为dist+1的滑窗,使得里面top k smallest的元素和最小。 + +对于求top k smallest,有常规的套路,就是用两个multiset。将滑窗内的top k smallest放入Set1,其余元素放入Set2. + +当滑窗移动时,需要加入进入的新元素k。我们需要考察是否能进入Set1(与尾元素比较)。如果能,那么需要将Set1的尾元素取出,放入Set2. 否则,将k放入Set2。 + +同理,当滑窗移动时,我们需要移除离开滑窗的旧元素k。我们考察k是否是Set1的元素。如果是,那么我们需要将Set1的k取出,同时将Set2的首元素加入进Set1里。 + +以上操作不断更新Set1的时候(加入元素和弹出元素),同时维护一个Set1元素的和变量sum,找到全局最小值即可。 From ebb5bdb6f8d1489e5082e6e3b6b94d8fc8508e56 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 23 Jan 2024 23:02:17 -0800 Subject: [PATCH 2386/2729] Create 3012.Minimize-Length-of-Array-Using-Operations.cpp --- ....Minimize-Length-of-Array-Using-Operations.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Greedy/3012.Minimize-Length-of-Array-Using-Operations/3012.Minimize-Length-of-Array-Using-Operations.cpp diff --git a/Greedy/3012.Minimize-Length-of-Array-Using-Operations/3012.Minimize-Length-of-Array-Using-Operations.cpp b/Greedy/3012.Minimize-Length-of-Array-Using-Operations/3012.Minimize-Length-of-Array-Using-Operations.cpp new file mode 100644 index 000000000..a3b8e6b96 --- /dev/null +++ b/Greedy/3012.Minimize-Length-of-Array-Using-Operations/3012.Minimize-Length-of-Array-Using-Operations.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int minimumArrayLength(vector& nums) + { + sort(nums.begin(), nums.end()); + for (int i=1; i Date: Tue, 23 Jan 2024 23:02:50 -0800 Subject: [PATCH 2387/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3cbad2611..c34e11dd3 100644 --- a/Readme.md +++ b/Readme.md @@ -1438,6 +1438,7 @@ [2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) [2753.Count-Houses-in-a-Circular-Street-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2753.Count-Houses-in-a-Circular-Street-II) (H-) +[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From a2a49605ef2960354ec58ef50ea8fc78bccada2b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 23 Jan 2024 23:27:14 -0800 Subject: [PATCH 2388/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/3012.Minimize-Length-of-Array-Using-Operations/Readme.md diff --git a/Greedy/3012.Minimize-Length-of-Array-Using-Operations/Readme.md b/Greedy/3012.Minimize-Length-of-Array-Using-Operations/Readme.md new file mode 100644 index 000000000..1b6f5df5d --- /dev/null +++ b/Greedy/3012.Minimize-Length-of-Array-Using-Operations/Readme.md @@ -0,0 +1,9 @@ +### 3012.Minimize-Length-of-Array-Using-Operations + +这是一道精彩的构造性问题。 + +我们注意到,对于任意x Date: Thu, 25 Jan 2024 23:57:12 -0800 Subject: [PATCH 2389/2729] Create Readme.md --- .../2781.Length-of-the-Longest-Valid-Substring/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 String/2781.Length-of-the-Longest-Valid-Substring/Readme.md diff --git a/String/2781.Length-of-the-Longest-Valid-Substring/Readme.md b/String/2781.Length-of-the-Longest-Valid-Substring/Readme.md new file mode 100644 index 000000000..ed33e9eb0 --- /dev/null +++ b/String/2781.Length-of-the-Longest-Valid-Substring/Readme.md @@ -0,0 +1,9 @@ +### 2781.Length-of-the-Longest-Valid-Substring + +注意到forbidden里面的字符串都很短,长度不超过10,我们可以用一个26进制的长度来编码的话,二进制的bit只需要最多50位,故一个64位长整形就能满足。这样,我们在word里走10遍不同长度的固定滑窗,每个滑窗对应一个编码,如果与forbidden里的编码相同,那么就意味着这个滑窗对应一个forbidden里的字符串。这样,我们就可以高效地知道word里所有的forbidden字串的位置。 + +接下来要做的就是在word里找到一个最长的区间,里面不包括任何完整的forbidden字串。这是一个典型的区间问题。我们考虑这样一个子问题:以i为右端点的区间,其左端点最远可以到哪里能符合条件?我们注意到,任何右边界超过i的forbidden子串都不会影响结果(他们肯定不会被完整包含)。所以我们只需要考虑所有右端点不超过i的forbidden子串,为了不完整包括它们中的任何一个,我们显然会取这些forbidden子串的所有左边界里的最大值j,这样[j+1,i]的区间就会符合条件。 + +于是我们可以归纳出算法。将所有forbidden子串按照右边界排序。这样我们从左往右扫描位置i时,就可以将顺次将所有右边界不超过i的子串加入集合,并从中更新它们左边界的最大值j。于是[j+1,i]就对应了以i为右端点、且不包括任何完整forbidden子串的最大区间。 + +同理,如果将所有forbidden子串按照左边界排序,也可以适用同样的算法,只不过从右往左扫一遍。 From 5e06fc4c4b4a5894c402e76696ebada07d507493 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 25 Jan 2024 23:58:17 -0800 Subject: [PATCH 2390/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c34e11dd3..dc4e0a5a1 100644 --- a/Readme.md +++ b/Readme.md @@ -1417,6 +1417,7 @@ [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) +[2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 1bade9ee84579e2c094b2d93a7f328289c8594cc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 2 Feb 2024 23:28:59 -0800 Subject: [PATCH 2391/2729] Create 3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp --- ...of-Remaining-Elements-Using-Operations.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp diff --git a/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp b/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp new file mode 100644 index 000000000..ecb06b73a --- /dev/null +++ b/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int minOrAfterOperations(vector& nums, int k) + { + int n = nums.size(); + vectorarr(n); + int ret = 0; + for (int t=29; t>=0; t--) + { + for (int i=0; i>t)&1); + + if (checkOK(arr, k)) + ret = ret*2+0; + else + { + ret = ret*2+1; + for (int i=0; i> 1); + } + } + return ret; + } + + bool checkOK(vector&arr, int k) + { + int n = arr.size(); + int count = 0; + int i = 0; + while (i Date: Fri, 2 Feb 2024 23:29:36 -0800 Subject: [PATCH 2392/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index dc4e0a5a1..1e6a5093b 100644 --- a/Readme.md +++ b/Readme.md @@ -1320,8 +1320,9 @@ [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) [2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) [2868.The-Wording-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2868.The-Wording-Game) (M) -[2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) -* ``Boyer-Moore Majority Voting`` +[2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) +[3022.Minimize-OR-of-Remaining-Elements-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations) (H) +* ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) * ``Lexicographical Sequence`` From 91d5ff1201bd629568cf9c1c84214489d9da44f5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Feb 2024 00:02:21 -0800 Subject: [PATCH 2393/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/Readme.md diff --git a/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/Readme.md b/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/Readme.md new file mode 100644 index 000000000..f12fd1191 --- /dev/null +++ b/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/Readme.md @@ -0,0 +1,11 @@ +### 3022.Minimize-OR-of-Remaining-Elements-Using-Operations + +本题的时间复杂度要求o(n),单纯用one pass很难求解。此时可以考虑到引入常数量,来适当松弛时间复杂度的要求。比如说,本题任何一个数字的二进制位不超过30,那么可以尝试类似o(30n)的解法。事实上,求解本题的突破口就在于逐位构造。 + +我们现在只考虑最高位,我们希望最终结果是0的话,那么意味着你需要将数组分割成若干个区间,每个区间内的AND结果都是0(这样,区间彼此之间的OR的结果才能是0)。这样的分割方法可能有很多种,但是我们并不需要关心具体的操作,只需要判定“能否实现”即可。这个可以用贪心法解决。从左往右依次处理,如果有非零元素,那么我们必然将其与右边的元素进行AND操作,重复进行直至变成0。此时所扫过的区间就是我们想要的一个最小区间。这是因为我们有贪心的思想:分割的每个区间越小,即总区间的数目越多,就意味着我们需要的AND操作最少。这是因为AND的总操作数本质就是n减去区间的数目。 + +我们如果用上述的方法,判定出“最高位不能够构造出0”,那么我们就直接将result的最高位放置1即可。在后续的分析中,我们都不需要考虑nums数组里任何元素的最高位。它们不会对我们后续的构造(即区间分割)带来负面的“牵制”(已经摆烂了),即任何区间分割的方法都不会使得result的最高位能变成0。 + +我们如果用上述的方法,判定出“最高位能够构造出0”,此时需要注意:符合条件的分割可能有很多种策略,但我们不关心具体的操作,因为最优的分割需要结合到次高位的制约。接下来我们就考察次高位,依然是尝试判断“能否在该位构造出0”。这时候我们要注意,因为贪心,我们必须仍然要保持最高位的结果是0,同时也希望次高位的结果也是0,所以本质就是判断“仅考虑最高的两个bit位的前提下,能否将数组风格成若干个区间,每个区间内的AND结果都是00”。如果结论是true,就意味着最终result的次高位也直接置0,否则最终result的次高位置1. 接下来,重复策略,如果刚才的结论是true,我们接下来会尝试能否在最高的三位构造出000;如果是false,那么之后的考察就要忽略掉所有元素的次高位(任何分割都不会是的result的次高位变成0)。 + +以此类推,通过查看数组能否被分割成若干个AND为0的区间(仅限前对应二进制的前缀),可以从高到低判定是否能在result里的每个bit上置零。如果不能,记得将nums里所有元素的该bit位直接划去。 From 778ff4c10b3223e61a2e776166d2fc6e72406b6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Feb 2024 23:39:12 -0800 Subject: [PATCH 2394/2729] Create 3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp --- ...ime-to-Revert-Word-to-Initial-State-II.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp diff --git a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp new file mode 100644 index 000000000..adcf23444 --- /dev/null +++ b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector longestPrefix(string s) + { + int n = s.size(); + vectordp(n); + dp[0] = 0; + + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + + return dp; + } + + int minimumTimeToInitialState(string word, int k) + { + int n = word.size(); + vectorlcp = longestPrefix (word); + int len = lcp[n-1]; + while (len!=0 && (n-len)%k!=0) + len = lcp[len-1]; + + if (len!=0) + return (n-len)/k; + else + return (n%k==0)?(n/k):(n/k+1); + } +}; From 5274613d7347afcf322a8c7a8dc27d59fc6942b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Feb 2024 23:39:40 -0800 Subject: [PATCH 2395/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1e6a5093b..a415b8d57 100644 --- a/Readme.md +++ b/Readme.md @@ -1023,6 +1023,7 @@ [2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/String/2301.Match-Substring-After-Replacement) (H-) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [3008.Find-Beautiful-Indices-in-the-Given-Array-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II) (H-) +[3031.Minimum-Time-to-Revert-Word-to-Initial-State-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II) (H) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From fee5b1e3e87a3bb11d4f322839a22ea148992753 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 5 Feb 2024 00:03:35 -0800 Subject: [PATCH 2396/2729] Create Readme.md --- .../Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md diff --git a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md new file mode 100644 index 000000000..16690c43b --- /dev/null +++ b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md @@ -0,0 +1,8 @@ +### 3031.Minimum-Time-to-Revert-Word-to-Initial-State-II + +本题的题意是说,在字符串里寻找一个最长的后缀长度len,使得该后缀同时也是字符串的前缀,并且要求n-len是k的整数。 + +如果没有第二个要求,那么本题就是一个非常典型的最长公共前后缀问题,用KMP算法的预处理代码,就可以求得一个数组next[i],表示对于s[0:i]而言的最长公共前后缀长度。即如果next[i]=L,那么就有`s[0:L-1] = s[i-L+1:i]`. (注意,这里所说的最长公共前后缀都不能包括字符串本身。) + +当我们查看`len = next[n-1]`但是发现不满足n-len能被k整除怎么办?显然,我们希望尝试word的“第二长的公共前后缀”。那么这个怎么求呢?其实因为s[0:len-1] = s[n-len:n-1]已经是s的最长公共前后缀,那么s[0:len-1]的“最长公共前后缀”必然也是s的“公共前后缀”,并且就是第二长的。所以我们只需要求s[0:len-1]的“最长公共前后缀”即可,那就是next[len-1]。依次类推,我们可以求得s的第二长、第三长...的公共前后缀len。只要发现n-len是k的整数倍,就可以知道需要切几刀。如果始终不符合条件,那么就意味着要将整个长度n都切完才行。 + From 613eb9625dd1f30f49ca31a6097f72cf5c2ce8c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 5 Feb 2024 00:11:02 -0800 Subject: [PATCH 2397/2729] Create 3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp --- ...um-Time-to-Revert-Word-to-Initial-State-II_v2.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp diff --git a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp new file mode 100644 index 000000000..30c2e84a4 --- /dev/null +++ b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minimumTimeToInitialState(string word, int k) + { + int t=1; + int n = word.size(); + char* s = &(word[0]); + while (t*k Date: Mon, 5 Feb 2024 00:12:36 -0800 Subject: [PATCH 2398/2729] Update Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md index 16690c43b..6c4741cbc 100644 --- a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md +++ b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md @@ -1,8 +1,15 @@ ### 3031.Minimum-Time-to-Revert-Word-to-Initial-State-II +#### 解法1 本题的题意是说,在字符串里寻找一个最长的后缀长度len,使得该后缀同时也是字符串的前缀,并且要求n-len是k的整数。 如果没有第二个要求,那么本题就是一个非常典型的最长公共前后缀问题,用KMP算法的预处理代码,就可以求得一个数组next[i],表示对于s[0:i]而言的最长公共前后缀长度。即如果next[i]=L,那么就有`s[0:L-1] = s[i-L+1:i]`. (注意,这里所说的最长公共前后缀都不能包括字符串本身。) 当我们查看`len = next[n-1]`但是发现不满足n-len能被k整除怎么办?显然,我们希望尝试word的“第二长的公共前后缀”。那么这个怎么求呢?其实因为s[0:len-1] = s[n-len:n-1]已经是s的最长公共前后缀,那么s[0:len-1]的“最长公共前后缀”必然也是s的“公共前后缀”,并且就是第二长的。所以我们只需要求s[0:len-1]的“最长公共前后缀”即可,那就是next[len-1]。依次类推,我们可以求得s的第二长、第三长...的公共前后缀len。只要发现n-len是k的整数倍,就可以知道需要切几刀。如果始终不符合条件,那么就意味着要将整个长度n都切完才行。 +#### 解法2 +本题可以直接暴力。使用cpp的函数memcpy可以高效判断两段相同长度的内存空间里的字节是否相等。 +``` +int memcmp(const void *s1, const void *s2, size_t n); +``` +返回值为零表示相等。 From 00c509d067b1e7102bae4328c6785ebe420421ef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 8 Feb 2024 00:47:54 -0800 Subject: [PATCH 2399/2729] Update 028.Implement-strStr-KMP.cpp --- String/028.Implement-strStr/028.Implement-strStr-KMP.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp b/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp index 39ba57963..7de750598 100644 --- a/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp +++ b/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp @@ -18,7 +18,7 @@ class Solution { for (int i=1; i0 && haystack[i]!=needle[j]) + while (j>0 && (j==needle.size() || haystack[i]!=needle[j])) j = suf[j-1]; dp[i] = j + (haystack[i]==needle[j]); if (dp[i]==needle.size()) From e626c700022c61a49bed0e840b3160b8f58c6141 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Feb 2024 19:19:13 -0800 Subject: [PATCH 2400/2729] Create 3027.Find-the-Number-of-Ways-to-Place-People-II.cpp --- ...-the-Number-of-Ways-to-Place-People-II.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/3027.Find-the-Number-of-Ways-to-Place-People-II.cpp diff --git a/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/3027.Find-the-Number-of-Ways-to-Place-People-II.cpp b/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/3027.Find-the-Number-of-Ways-to-Place-People-II.cpp new file mode 100644 index 000000000..12efd800b --- /dev/null +++ b/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/3027.Find-the-Number-of-Ways-to-Place-People-II.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int numberOfPairs(vector>& points) + { + sort(points.begin(), points.end(), [](vector&a, vector&b){ + if (a[0]==b[0]) return a[1]>b[1]; + else return a[0] upper) continue; + if (points[j][1] > lower && points[j][1] <= upper) + ret++; + lower = max(lower, points[j][1]); + } + } + + return ret; + } +}; From 6b07fc2ef5bb429e0935a655f594703ce62e787f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Feb 2024 19:19:47 -0800 Subject: [PATCH 2401/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index a415b8d57..d6a57857e 100644 --- a/Readme.md +++ b/Readme.md @@ -1388,8 +1388,9 @@ [1996.The-Number-of-Weak-Characters-in-the-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1996.The-Number-of-Weak-Characters-in-the-Game) (M+) [2250.Count-Number-of-Rectangles-Containing-Each-Point](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point) (H-) [2343.Query-Kth-Smallest-Trimmed-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2343.Query-Kth-Smallest-Trimmed-Number) (H-) -[2412.Minimum-Money-Required-Before-Transactions](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2412.Minimum-Money-Required-Before-Transactions) (H-) -[2345.Finding-the-Number-of-Visible-Mountains](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2345.Finding-the-Number-of-Visible-Mountains) (H-) +[2412.Minimum-Money-Required-Before-Transactions](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2412.Minimum-Money-Required-Before-Transactions) (H-) +[2345.Finding-the-Number-of-Visible-Mountains](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2345.Finding-the-Number-of-Visible-Mountains) (H-) +[3027.Find-the-Number-of-Ways-to-Place-People-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II) (M) * ``Indexing Sort`` [041.First-Missing-Positive](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/041.First-Missing-Positive/Readme.md) (H) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 99a99df2bd9f2bb56a9311fc69603f672422b96d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Feb 2024 19:30:30 -0800 Subject: [PATCH 2402/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/Readme.md diff --git a/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/Readme.md b/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/Readme.md new file mode 100644 index 000000000..feb2bb3cf --- /dev/null +++ b/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/Readme.md @@ -0,0 +1,5 @@ +### 3027.Find-the-Number-of-Ways-to-Place-People-II + +此题允许n^2的时间复杂度,可以暴力枚举所有符合条件的{左上角、右下角}配对,判断是否是合法的解。 + +对于二维坐标的点,有两个方向上的自由度,同时考虑他们之间的包含关系肯定复杂,我们必然会尝试将他们先按照一个维度排序,比如说x轴。对于两个点A和B在x轴上是递增的,他们能够配对成功的条件就是:x轴上A与B之间的点,不能在y轴上也出现在A与B之间。换句话说,如果横坐标位于A与B之间的所有点的y坐标上限是P(排除那些高于A的点),那么B能与A配对的条件就是:B的y周坐标必须大于P。随着B在x轴上离A越远,那么这个上限值其实是单调递增的。由此从左到右扫一遍所有的点,不断更新上限P,就能判断出每个点是否可以与A配对。 From 3764611948fe550c582aabdf0d7617ad3edfff9f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Feb 2024 23:52:07 -0800 Subject: [PATCH 2403/2729] Create 3045.Count-Prefix-and-Suffix-Pairs-II.cpp --- .../3045.Count-Prefix-and-Suffix-Pairs-II.cpp | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 String/3045.Count-Prefix-and-Suffix-Pairs-II/3045.Count-Prefix-and-Suffix-Pairs-II.cpp diff --git a/String/3045.Count-Prefix-and-Suffix-Pairs-II/3045.Count-Prefix-and-Suffix-Pairs-II.cpp b/String/3045.Count-Prefix-and-Suffix-Pairs-II/3045.Count-Prefix-and-Suffix-Pairs-II.cpp new file mode 100644 index 000000000..76a0d1ceb --- /dev/null +++ b/String/3045.Count-Prefix-and-Suffix-Pairs-II/3045.Count-Prefix-and-Suffix-Pairs-II.cpp @@ -0,0 +1,86 @@ +using LL = long long; +class Solution { + class TrieNode + { + public: + TrieNode* next[26]; + int count; + TrieNode() + { + for (int i=0; i<26; i++) + next[i]=NULL; + count = 0; + } + }; + TrieNode* root = new TrieNode(); +public: + vector longestPrefix(string s) + { + int n = s.size(); + vectordp(n); + dp[0] = 0; + + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + + return dp; + } + + void add(TrieNode* root, string& word, unordered_set&Set) + { + TrieNode* node = root; + int n = word.size(); + for (int i=0; inext[word[i]-'a']==NULL) + node->next[word[i]-'a'] = new TrieNode(); + node = node->next[word[i]-'a']; + if (Set.find(i+1)!=Set.end()) + node->count++; + } + } + + int find(TrieNode* root, string& word) + { + TrieNode* node = root; + int n = word.size(); + for (int i=0; inext[word[i]-'a']==NULL) + return 0; + node = node->next[word[i]-'a']; + } + return node->count; + } + + + long long countPrefixSuffixPairs(vector& words) + { + LL ret = 0; + for (int i=words.size()-1; i>=0; i--) + { + ret += find(root, words[i]); + + int n = words[i].size(); + vectorlcp = longestPrefix (words[i]); + unordered_setSet; + int len = lcp[n-1]; + while (len!=0) + { + Set.insert(len); + len = lcp[len-1]; + } + Set.insert(n); + + add(root, words[i], Set); + } + return ret; + } +}; From 2090f09105a5f26142a765aecf70bde23d0d7638 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Feb 2024 23:52:34 -0800 Subject: [PATCH 2404/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d6a57857e..1be13ea37 100644 --- a/Readme.md +++ b/Readme.md @@ -1024,6 +1024,7 @@ [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [3008.Find-Beautiful-Indices-in-the-Given-Array-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II) (H-) [3031.Minimum-Time-to-Revert-Word-to-Initial-State-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II) (H) +[3045.Count-Prefix-and-Suffix-Pairs-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3045.Count-Prefix-and-Suffix-Pairs-II) (H) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From 95a19b1c645949e4d6ef6f09214e9aba94439f03 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 00:05:03 -0800 Subject: [PATCH 2405/2729] Create Readme.md --- String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md diff --git a/String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md b/String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md new file mode 100644 index 000000000..180ff71c7 --- /dev/null +++ b/String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md @@ -0,0 +1,7 @@ +### 3045.Count-Prefix-and-Suffix-Pairs-II + +对于一对pair里的两个字符串而言,前者是后者的一部分,所以我们必然需要先处理后者。故我们需要从后往前遍历字符串。 + +对于一个字符串s,要使得其他字符串既是它的前缀,也是它的后缀,这是一个比较苛刻的条件。我们很容易联想到KMP算法,可以用线性的时间就能找到s里的所有符合条件的子串(参考`LeetCode 3031 Minimum Time to Revert Word to Initial State II`)。对于这些子串(字符串的“前缀&后缀”),我们必然会将其放入一棵字典树里。这样,对于其他字符串t,我们可以通过搜索字典树进行匹配,从而得知t同时是多少字符串的“前缀&后缀”。 + +在字典树的数据结构里,我们会给每个节点标记count。任何需要填入字典树的子串,我们都会在其路径的最后一个节点的count增1. 对于待查询的字符串t,如果它与字典树里的某个路径匹配,那么该路径的最后一个节点的count就代表了t能配对的字符串的数量。 From b4cd73306afc180c2415eeb72a4cc4e00fff6e21 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 23:48:42 -0800 Subject: [PATCH 2406/2729] Create 3023.Find-Pattern-in-Infinite-Stream-I.cpp --- ...3023.Find-Pattern-in-Infinite-Stream-I.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 String/3023.Find-Pattern-in-Infinite-Stream-I/3023.Find-Pattern-in-Infinite-Stream-I.cpp diff --git a/String/3023.Find-Pattern-in-Infinite-Stream-I/3023.Find-Pattern-in-Infinite-Stream-I.cpp b/String/3023.Find-Pattern-in-Infinite-Stream-I/3023.Find-Pattern-in-Infinite-Stream-I.cpp new file mode 100644 index 000000000..e45b8ad7f --- /dev/null +++ b/String/3023.Find-Pattern-in-Infinite-Stream-I/3023.Find-Pattern-in-Infinite-Stream-I.cpp @@ -0,0 +1,56 @@ +/** + * Definition for an infinite stream. + * class InfiniteStream { + * public: + * InfiniteStream(vector bits); + * int next(); + * }; + */ +class Solution { +public: + vector preprocess(vector s) + { + int n = s.size(); + vectordp(n,0); + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + return dp; + } + + int findPattern(InfiniteStream* stream, vector& pattern) + { + int m = pattern.size(); + if (m==0) return 0; + + vector suf = preprocess(pattern); + + unordered_mapdp; + + int num = stream->next(); + dp[0] = (num==pattern[0]); + if (m==1 && dp[0]==1) + return 0; + + int i = 1; + while (1) + { + int num = stream->next(); + + int j = dp[i-1]; + while (j>0 && (j==pattern.size() || num!=pattern[j])) + j = suf[j-1]; + dp[i] = j + (num==pattern[j]); + if (dp[i]==m) + return i-pattern.size()+1; + i++; + } + return -1; + } +}; From e7535b67cb0d85ac71114040ede2963abd2c2fde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 23:55:46 -0800 Subject: [PATCH 2407/2729] Create Readme.md --- String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md diff --git a/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md b/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md new file mode 100644 index 000000000..13bc1c26d --- /dev/null +++ b/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md @@ -0,0 +1,5 @@ +### 3023.Find-Pattern-in-Infinite-Stream-I + +此题是KMP的模板题。先将pattern进行预处理求得它的前缀数组`suf`。然后对stream产生的nums[i]逐位处理,利用`suf`计算nums的前缀数组dp[i]。其中dp[i]的定义是以nums[i]结尾的最长后缀,同时也是pattern的前缀。 + +当dp[i]等于pattern的长度m时,说明`i-m+1`就是匹配的位置。 From 45090bce4f4395499a7ca0b1a4a347536ada094d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 23:56:18 -0800 Subject: [PATCH 2408/2729] Update Readme.md --- String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md b/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md index 13bc1c26d..e1736235c 100644 --- a/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md +++ b/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md @@ -2,4 +2,4 @@ 此题是KMP的模板题。先将pattern进行预处理求得它的前缀数组`suf`。然后对stream产生的nums[i]逐位处理,利用`suf`计算nums的前缀数组dp[i]。其中dp[i]的定义是以nums[i]结尾的最长后缀,同时也是pattern的前缀。 -当dp[i]等于pattern的长度m时,说明`i-m+1`就是匹配的位置。 +当发现某处的dp[i]等于pattern的长度m时,说明`i-m+1`就是匹配的位置。 From 3ba0c2f1b749a16aa271e0a1a6ab817d95f56a32 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 23:58:11 -0800 Subject: [PATCH 2409/2729] Create 3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp --- ...lements-in-an-Array-After-Modification.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp new file mode 100644 index 000000000..1c9611b2a --- /dev/null +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp @@ -0,0 +1,39 @@ +class Solution { + int dp[100005][2]; +public: + int maxSelectedElements(vector& nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + + dp[0][0] = 1; + dp[0][1] = 1; + + int ret = 1; + + for (int i=1; i Date: Sun, 18 Feb 2024 23:58:58 -0800 Subject: [PATCH 2410/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1be13ea37..5585b35a4 100644 --- a/Readme.md +++ b/Readme.md @@ -743,6 +743,7 @@ [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) [2979.Most-Expensive-Item-That-Can-Not-Be-Bought](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought) (M+) +[3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 5531fae4c12e2af884f0273734fab56e38c8f158 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 00:48:11 -0800 Subject: [PATCH 2411/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md new file mode 100644 index 000000000..c2377236b --- /dev/null +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md @@ -0,0 +1,11 @@ +### 3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification + +因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。 + +我们先考虑所有的元素都不相同的情况。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 + +1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 +2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` +3. 如果a与b相同,那么必须将b+1之后连接在a后面,所以有`dp[i][1] = dp[i-1][0]+1`. 但是同时注意到,我们其实不需要同时选取nums[i-1]和nums[i],因为两者的数值相同,可以舍弃其中一个,但是保留所有以i-1为结尾的序列。即`dp[i][0] = dp[i-1][0]`和`dp[i][1] = dp[i-1][1]`。 + +记录下任何时候dp[i][0]和dp[i][1]的最大值,即是最终答案。 From 3267f3ae661a3974ec275153b28143790fd336f7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 00:49:25 -0800 Subject: [PATCH 2412/2729] Update Readme.md --- .../Readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md index c2377236b..88c8d7171 100644 --- a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md @@ -1,8 +1,6 @@ ### 3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification -因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。 - -我们先考虑所有的元素都不相同的情况。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 +因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` From 9584301a4ad4e8754d930a110dca36ce7eb03afa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 00:57:42 -0800 Subject: [PATCH 2413/2729] Update Readme.md --- .../Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md index 88c8d7171..36c829a0a 100644 --- a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md @@ -2,8 +2,10 @@ 因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 -1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 -2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` -3. 如果a与b相同,那么必须将b+1之后连接在a后面,所以有`dp[i][1] = dp[i-1][0]+1`. 但是同时注意到,我们其实不需要同时选取nums[i-1]和nums[i],因为两者的数值相同,可以舍弃其中一个,但是保留所有以i-1为结尾的序列。即`dp[i][0] = dp[i-1][0]`和`dp[i][1] = dp[i-1][1]`。 +1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 + +2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` + +3. 如果a与b相同,那么必须将b+1之后连接在a后面,所以有`dp[i][1] = dp[i-1][0]+1`. 但是同时注意到,我们其实不需要同时选取nums[i-1]和nums[i],因为两者的数值相同,可以舍弃其中一个,但是保留所有以i-1为结尾的序列。即`dp[i][0] = dp[i-1][0]`和`dp[i][1] = dp[i-1][1]`。 记录下任何时候dp[i][0]和dp[i][1]的最大值,即是最终答案。 From 904308bb952ec57d639d18ce55a47f50159cce97 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 00:58:16 -0800 Subject: [PATCH 2414/2729] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md index 36c829a0a..8afcdcf29 100644 --- a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md @@ -1,8 +1,8 @@ ### 3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification -因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 +因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 -1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 +1. 如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` From 24ed87c613d0d9bf8aa31c37f0e5636bfbab3f62 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 13:46:08 -0800 Subject: [PATCH 2415/2729] Create 3009.Maximum-Number-of-Intersections-on-the-Chart.cpp --- ...m-Number-of-Intersections-on-the-Chart.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Others/3009.Maximum-Number-of-Intersections-on-the-Chart/3009.Maximum-Number-of-Intersections-on-the-Chart.cpp diff --git a/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/3009.Maximum-Number-of-Intersections-on-the-Chart.cpp b/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/3009.Maximum-Number-of-Intersections-on-the-Chart.cpp new file mode 100644 index 000000000..e9e27cee7 --- /dev/null +++ b/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/3009.Maximum-Number-of-Intersections-on-the-Chart.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int maxIntersectionCount(vector& y) + { + int n = y.size(); + mapMap; + for (int i=1; i Date: Mon, 19 Feb 2024 13:46:33 -0800 Subject: [PATCH 2416/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5585b35a4..d0771f6c7 100644 --- a/Readme.md +++ b/Readme.md @@ -1549,6 +1549,7 @@ [2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) [2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero) (H-) [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) +[3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 9ccb7388b26cb7c33855cfeb919638654248642c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 14:09:38 -0800 Subject: [PATCH 2417/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Others/3009.Maximum-Number-of-Intersections-on-the-Chart/Readme.md diff --git a/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/Readme.md b/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/Readme.md new file mode 100644 index 000000000..9ff9ed2d4 --- /dev/null +++ b/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/Readme.md @@ -0,0 +1,11 @@ +### 3009.Maximum-Number-of-Intersections-on-the-Chart + +很容易看出这题需要用到扫描线。对于每一段折线相当于一段区间,我们要找出有最多重叠区间的位置。 + +这里需要注意的是,每个区间的端点不能都是双闭的。否则在端点处就会有重复的计数。比如"1,2,0". 如果认为有两处区间[1,2]和[0,2],那么会认为在位置y=2处划扫描线的话可以有两个交点,但实际只有一个。对此一个比较容易想到的解决方案是,除了最后一个区间,其他所有的区间都设定为左闭右开(其中左右的定义是按照nums的先后,而不是数值的大小)。比如“1,2,0,...”,那么我们认为前两处区间`[1,2)`和`(0,2]`. 这样我们找跨越最多区间的扫描线时,就不会出错。 + +但是接下来还有一个问题,就是何时记录差分。对于形如`[a,b)`的区间,很明显,我们会在`diff[a]+=1`,在`diff[b]-=1`.而对于形如`(a,b]`的区间,我们可能会采用`diff[a+1]+=1`,在`diff[b+1]-=1`. 但是这样会引入一个问题。比如说"2,1,2...",我们有两段区间分别是`(1,2]`和`[1,2)`. 我们会发现,如果依据之前的差分策略,在x=1处的总diff为1,而x=2处的总diff也是1。但事实上扫描线位于[1,2]之间的位置应该能至少扫过两个交点。这就暴露了一个缺陷,我们的差分点都在整数点的位置上,但是本题里的扫描线是可以落在半整数点的位置上(比如说1.5). 一个灵活的解决方案是,对于形如`(a,b]`的区间,为了反映在半整数点位置的扫描性的变化,我们可能会采用`diff[a+0.5]+=1`,在`diff[b+0.5]-=1`,也就是提早进行差分的更新。 + +由此得到所有的差分更新点后,走一遍积分,取全局最大值就是答案。 + +注意别忘了特别处理最后一个区间的右端点q,它应该被特殊处理为“闭”。所以额外单独为它额外增加一个差分点:`diff[q]+=1`和`diff[q+0.5]-=1`。 From a019b70d7b3626eb822be0532485a780d4313622 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 22:34:28 -0800 Subject: [PATCH 2418/2729] Create fill.cpp --- Template/CPP_LANG/fill.cpp | 1 + 1 file changed, 1 insertion(+) create mode 100644 Template/CPP_LANG/fill.cpp diff --git a/Template/CPP_LANG/fill.cpp b/Template/CPP_LANG/fill.cpp new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/Template/CPP_LANG/fill.cpp @@ -0,0 +1 @@ + From 3de316241d11e6f5846544cf0184e5189dfbd5a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 22:45:16 -0800 Subject: [PATCH 2419/2729] Update fill.cpp --- Template/CPP_LANG/fill.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Template/CPP_LANG/fill.cpp b/Template/CPP_LANG/fill.cpp index 8b1378917..a395dac00 100644 --- a/Template/CPP_LANG/fill.cpp +++ b/Template/CPP_LANG/fill.cpp @@ -1 +1,17 @@ +main() { + int arr[10]; + fill(arr, arr+10, 3); + for (int i=0; i<10; i++) cout<arr3(10); + fill(arr3.begin(), arr3.end(), 3); + for (int i=0; i<10; i++) cout< Date: Mon, 19 Feb 2024 22:48:06 -0800 Subject: [PATCH 2420/2729] Update fill.cpp --- Template/CPP_LANG/fill.cpp | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/Template/CPP_LANG/fill.cpp b/Template/CPP_LANG/fill.cpp index a395dac00..5d27c5802 100644 --- a/Template/CPP_LANG/fill.cpp +++ b/Template/CPP_LANG/fill.cpp @@ -1,17 +1,10 @@ main() { - int arr[10]; - fill(arr, arr+10, 3); - for (int i=0; i<10; i++) cout<arr3(10); - fill(arr3.begin(), arr3.end(), 3); - for (int i=0; i<10; i++) cout<arr3(10); + fill(arr3.begin(), arr3.end(), 3); } From 50afd51e40f62de6284dbf490b3c9b22f87f623d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 22:48:18 -0800 Subject: [PATCH 2421/2729] Update fill.cpp --- Template/CPP_LANG/fill.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/CPP_LANG/fill.cpp b/Template/CPP_LANG/fill.cpp index 5d27c5802..303c15b99 100644 --- a/Template/CPP_LANG/fill.cpp +++ b/Template/CPP_LANG/fill.cpp @@ -1,10 +1,10 @@ main() { int arr[10]; fill(arr, arr+10, 3); - + int arr2[2][5]; fill(&arr2[0][0], &arr2[0][0]+10, 3); - + vectorarr3(10); fill(arr3.begin(), arr3.end(), 3); } From 9da9592d4c6ede956382e11309d7aa760ccc1e20 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 23:42:39 -0800 Subject: [PATCH 2422/2729] Create 3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp --- ...emoval-Queries-That-Can-Be-Processed-I.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp diff --git a/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp new file mode 100644 index 000000000..2a2b3cf37 --- /dev/null +++ b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp @@ -0,0 +1,40 @@ +class Solution { + int dp[1005][1005]; +public: + int maximumProcessableQueries(vector& nums, vector& queries) + { + int n = nums.size(); + int ret = 0; + + dp[0][n-1] = 0; + for (int len = n-1; len >=1; len--) + for (int i=0; i+len-1=0) + { + int t = dp[i-1][j]; + if (t= queries[t]) + dp[i][j] = max(dp[i][j], dp[i-1][j] + 1); + else + dp[i][j] = max(dp[i][j], dp[i-1][j]); + } + if (j+1= queries[t]) + dp[i][j] = max(dp[i][j], dp[i][j+1] + 1); + else + dp[i][j] = max(dp[i][j], dp[i][j+1]); + } + ret = max(ret, dp[i][j]); + } + + for (int i=0; i=queries[dp[i][i]]) + ret = max(ret, dp[i][i]+1); + } + return ret; + } +}; From 3d9e5902f9a2fa96531b74d048c669c7fe737068 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 23:43:10 -0800 Subject: [PATCH 2423/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d0771f6c7..5a9cdae93 100644 --- a/Readme.md +++ b/Readme.md @@ -869,7 +869,8 @@ [1682.Longest-Palindromic-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1682.Longest-Palindromic-Subsequence-II) (H) [1690.Stone-Game-VII](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1690.Stone-Game-VII) (H-) [1745.Palindrome-Partitioning-IV](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1745.Palindrome-Partitioning-IV) (M) -[1770.Maximum-Score-from-Performing-Multiplication-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1770.Maximum-Score-from-Performing-Multiplication-Operations) (H-) +[1770.Maximum-Score-from-Performing-Multiplication-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1770.Maximum-Score-from-Performing-Multiplication-Operations) (H-) +[3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I) (H-) * ``双序列型`` [010.Regular-Expression-Matching](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/010.Regular-Expression-Matching) (H) [044.Wildcard-Matching](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/044.Wildcard-Matching) (H-) From 13f4815032ff4df08da19c0f288872b51e8745e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 20 Feb 2024 00:00:35 -0800 Subject: [PATCH 2424/2729] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/Readme.md diff --git a/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/Readme.md b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/Readme.md new file mode 100644 index 000000000..6f9636866 --- /dev/null +++ b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/Readme.md @@ -0,0 +1,12 @@ +### 3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I + +我们令dp[i][j]表示将nums砍至区间[i:j]时,能够通过多少个queries。显然,dp[i][j]是可以由dp[i-1][j]或dp[i][j+1]转化来的。例如,令`dp[i-1][j]=t`,说明操作至[i-1:j]时已经通过了t个queries,那么如果`nums[i-1]>=queries[t]`的话,就可以再砍去nums[i-1]使得通过`t+1`个queries. 反之如果`nums[i-1]=queries[t]`,那么意味着nums可以全部被删除(即通过t+1个queries)。在更新最终答案时需要额外处理这种情况。 + From 268607af03e76640c0e74938e6f100f4b27ae951 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 24 Feb 2024 16:28:02 -0800 Subject: [PATCH 2425/2729] Update 3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp --- ...of-Removal-Queries-That-Can-Be-Processed-I.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp index 2a2b3cf37..42ae27531 100644 --- a/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp +++ b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp @@ -15,25 +15,26 @@ class Solution { { int t = dp[i-1][j]; if (t= queries[t]) - dp[i][j] = max(dp[i][j], dp[i-1][j] + 1); + dp[i][j] = max(dp[i][j], t + 1); else - dp[i][j] = max(dp[i][j], dp[i-1][j]); + dp[i][j] = max(dp[i][j], t); } if (j+1= queries[t]) - dp[i][j] = max(dp[i][j], dp[i][j+1] + 1); + dp[i][j] = max(dp[i][j], t + 1); else - dp[i][j] = max(dp[i][j], dp[i][j+1]); - } - ret = max(ret, dp[i][j]); + dp[i][j] = max(dp[i][j], t); + } } for (int i=0; i=queries[dp[i][i]]) - ret = max(ret, dp[i][i]+1); + ret = max(ret, dp[i][i]+1); + else + ret = max(ret, dp[i][i]); } return ret; } From f268cf28e27fad2a0b5f359757973820c243dc2f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Feb 2024 23:26:57 -0800 Subject: [PATCH 2426/2729] Create 3048.Earliest-Second-to-Mark-Indices-I.cpp --- ...3048.Earliest-Second-to-Mark-Indices-I.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/3048.Earliest-Second-to-Mark-Indices-I.cpp diff --git a/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/3048.Earliest-Second-to-Mark-Indices-I.cpp b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/3048.Earliest-Second-to-Mark-Indices-I.cpp new file mode 100644 index 000000000..7349d072e --- /dev/null +++ b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/3048.Earliest-Second-to-Mark-Indices-I.cpp @@ -0,0 +1,53 @@ +class Solution { + int n,m; +public: + int earliestSecondToMarkIndices(vector& nums, vector& changeIndices) + { + n = nums.size(); + m = changeIndices.size(); + nums.insert(nums.begin(), 0); + changeIndices.insert(changeIndices.begin(), 0); + + int left=1, right=m; + while (left < right) + { + int mid = left + (right-left)/2; + + if (isOK(mid, nums, changeIndices)) + right = mid; + else + left = mid+1; + } + + if (!isOK(left, nums, changeIndices)) return -1; + else return left; + } + + bool isOK(int m, vector& nums, vector& changeIndices) + { + vectorlast(n+1); + for (int i=1; i<=m; i++) + last[changeIndices[i]]=i; + + for (int i=1; i<=n; i++) + if (last[i]==0) return false; + + int count = 0; + for (int i=1; i<=m; i++) + { + int idx = changeIndices[i]; + + if (i!=last[idx]) + { + count++; + } + else + { + count -= nums[idx]; + if (count < 0) return false; + } + } + + return true; + } +}; From f3e79aae9a4d82f8db145e48cd527f8b7475084a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Feb 2024 23:27:45 -0800 Subject: [PATCH 2427/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5a9cdae93..e1fe25b1e 100644 --- a/Readme.md +++ b/Readme.md @@ -140,6 +140,7 @@ [2616.Minimize-the-Maximum-Difference-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs) (H-) [2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) [2861.Maximum-Number-of-Alloys](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2861.Maximum-Number-of-Alloys) (M+) +[3048.Earliest-Second-to-Mark-Indices-I](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I) (M+) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From e44ff5b1963db0e83b2cf330e8c58159a6625efe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Feb 2024 23:43:29 -0800 Subject: [PATCH 2428/2729] Create Readme.md --- .../3048.Earliest-Second-to-Mark-Indices-I/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md diff --git a/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md new file mode 100644 index 000000000..c825b4c89 --- /dev/null +++ b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md @@ -0,0 +1,7 @@ +### 3048.Earliest-Second-to-Mark-Indices-I + +首先要看出这道题存在单调性,肯定时间越多的话,越有机会将所有元素都清零并标记。由此我们考虑尝试二分搜值。二分法的有点是,不用直接求“最优解”,而是转化为判定“可行解”,难度上会小很多。 + +本题里,我们需要在给定时间s的情况下,问能否将所有元素都清零并标记。对于一个给定的index而言,我们必须在对其“标记”前完成清零,因此我们肯定会将“标记”操作尽量延后,方便腾出更多时间做减一的操作。显然,我们会贪心地将index最后一次出现的时刻做“标记”操作;而如果index出现了不止一次多次,那么除了在最后一次的时刻做“标记”外,其余的时刻都会留作做“减一”操作(但不一定针对nums[idx])。为了顺利能够在最后一次index出现的时候做标记,我们需要保证之前积累的“减一”操作足够多,能够大于等于nums[idx]即可。于是我们只要顺着index出现的顺序,模拟上述的操作:要么积累“减一”操作count(如果不是最后一个出现),要么进行“标记”操作(如果是最后一次操作)。对于后者,能进行“标记”操作的前提是已经对那个index的数进行多次减一至零,故要求`count>=nums[idx]`. + +如果能够顺利地走完changeIndices[1:s]、并且将所有的nums都完成“标记”的话,就说明s秒能够实现目标。 From 9055a5a2f88ef18fff8471c259ac4f1c5aa988a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Feb 2024 23:43:50 -0800 Subject: [PATCH 2429/2729] Update Readme.md --- Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md index c825b4c89..7a08e8eb3 100644 --- a/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md +++ b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md @@ -1,6 +1,6 @@ ### 3048.Earliest-Second-to-Mark-Indices-I -首先要看出这道题存在单调性,肯定时间越多的话,越有机会将所有元素都清零并标记。由此我们考虑尝试二分搜值。二分法的有点是,不用直接求“最优解”,而是转化为判定“可行解”,难度上会小很多。 +首先要看出这道题存在单调性,肯定时间越多的话,越有机会将所有元素都清零并标记。由此我们考虑尝试二分搜值。二分法的优点是,不用直接求“最优解”,而是转化为判定“可行解”,难度上会小很多。 本题里,我们需要在给定时间s的情况下,问能否将所有元素都清零并标记。对于一个给定的index而言,我们必须在对其“标记”前完成清零,因此我们肯定会将“标记”操作尽量延后,方便腾出更多时间做减一的操作。显然,我们会贪心地将index最后一次出现的时刻做“标记”操作;而如果index出现了不止一次多次,那么除了在最后一次的时刻做“标记”外,其余的时刻都会留作做“减一”操作(但不一定针对nums[idx])。为了顺利能够在最后一次index出现的时候做标记,我们需要保证之前积累的“减一”操作足够多,能够大于等于nums[idx]即可。于是我们只要顺着index出现的顺序,模拟上述的操作:要么积累“减一”操作count(如果不是最后一个出现),要么进行“标记”操作(如果是最后一次操作)。对于后者,能进行“标记”操作的前提是已经对那个index的数进行多次减一至零,故要求`count>=nums[idx]`. From 532233baeb1b4ea26041e6da5e7f68976ddca9e9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 00:40:43 -0800 Subject: [PATCH 2430/2729] Create 3049.Earliest-Second-to-Mark-Indices-II.cpp --- ...049.Earliest-Second-to-Mark-Indices-II.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/3049.Earliest-Second-to-Mark-Indices-II.cpp diff --git a/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/3049.Earliest-Second-to-Mark-Indices-II.cpp b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/3049.Earliest-Second-to-Mark-Indices-II.cpp new file mode 100644 index 000000000..f13c3cacc --- /dev/null +++ b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/3049.Earliest-Second-to-Mark-Indices-II.cpp @@ -0,0 +1,67 @@ +using LL = long long; +class Solution { + int n,m; +public: + int earliestSecondToMarkIndices(vector& nums, vector& changeIndices) + { + n = nums.size(); + m = changeIndices.size(); + + nums.insert(nums.begin(), 0); + changeIndices.insert(changeIndices.begin(), 0); + + int left=1, right=m; + while (left < right) + { + int mid = left + (right-left)/2; + + if (isOK(mid, nums, changeIndices)) + right = mid; + else + left = mid+1; + } + + if (!isOK(left, nums, changeIndices)) return -1; + else return left; + } + + bool isOK(int t, vector&nums, vector changeIndices) + { + if (tfirst(n+1, 0); + for (int i=1; i<=t; i++) + { + if (first[changeIndices[i]]==0 && nums[changeIndices[i]]!=0) + first[changeIndices[i]]=i; + else + changeIndices[i] = 0; + } + + LL total = accumulate(nums.begin(), nums.end(), 0ll); + + multisetresets; + for (int i=t; i>=1; i--) + { + int idx = changeIndices[i]; + + if (idx == 0) continue; + + int marks = (t-i+1) - (resets.size() + 1); + if (resets.size() +1 > marks) + { + resets.insert(nums[idx]); + resets.erase(resets.begin()); + } + else + { + resets.insert(nums[idx]); + } + } + + LL total_clear = 0; + for (int x: resets) total_clear+=x; + + return total_clear + (t-n-resets.size()) >= total; + } +}; From 6ec0c7a62e550733a1abc69d4d5df62f0181b63b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 00:41:20 -0800 Subject: [PATCH 2431/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e1fe25b1e..8c502a124 100644 --- a/Readme.md +++ b/Readme.md @@ -141,6 +141,7 @@ [2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) [2861.Maximum-Number-of-Alloys](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2861.Maximum-Number-of-Alloys) (M+) [3048.Earliest-Second-to-Mark-Indices-I](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I) (M+) +[3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From b37629e51d6a494a6a938f822898495e266eeb6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 13:51:54 -0800 Subject: [PATCH 2432/2729] Create Readme.md --- .../3049.Earliest-Second-to-Mark-Indices-II/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md diff --git a/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md new file mode 100644 index 000000000..a90da78dc --- /dev/null +++ b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md @@ -0,0 +1,7 @@ +### 3049.Earliest-Second-to-Mark-Indices-II + +首先,容易看出此题的答案具有单调性。时间越长,就越容易有清零的机会,也就越容易实现目标。所以我们在最外层套用二分搜值的框架,将求“最优解”的问题,转化为判定“可行解”的问题。 + +假设给出T秒的时刻,如何判定是否可行呢?我们发现,“清零”操作的性价比是非常高的,如果对于某个index有机会做“清零”操作,我们必然这样做(除非nums[idx]本身就是零)。如果对于某个index,它在时间序列里出现了多次,我们会在哪个时候去清零呢?相对而言我们尽早清零是最优的选择,因为如果你晚些时候去做清零操作,可能存在一个风险:后续没有足够的机会取做“标记”操作了。由此,我们可以在时间序列changeIndices里面,预处理得到哪些时刻我们是在做“清零”。 + +至此,我们知道哪些时候做“清零”,其余的时候基本首选就是做“减一”,而唯一的制约因素就是要在最后留有足够“标记”的机会。当然并不是无脑的选最后n秒都做“标记”,因为有些“清零”可能在很靠后的时刻才会发生。 From 848411890d1e65b83cb15884058d45791e8a5546 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 14:13:49 -0800 Subject: [PATCH 2433/2729] Update Readme.md --- .../3049.Earliest-Second-to-Mark-Indices-II/Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md index a90da78dc..a29d5808e 100644 --- a/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md +++ b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md @@ -4,4 +4,8 @@ 假设给出T秒的时刻,如何判定是否可行呢?我们发现,“清零”操作的性价比是非常高的,如果对于某个index有机会做“清零”操作,我们必然这样做(除非nums[idx]本身就是零)。如果对于某个index,它在时间序列里出现了多次,我们会在哪个时候去清零呢?相对而言我们尽早清零是最优的选择,因为如果你晚些时候去做清零操作,可能存在一个风险:后续没有足够的机会取做“标记”操作了。由此,我们可以在时间序列changeIndices里面,预处理得到哪些时刻我们是在做“清零”。 -至此,我们知道哪些时候做“清零”,其余的时候基本首选就是做“减一”,而唯一的制约因素就是要在最后留有足够“标记”的机会。当然并不是无脑的选最后n秒都做“标记”,因为有些“清零”可能在很靠后的时刻才会发生。 +至此,我们知道哪些时候做“清零”,其余的时候基本首选就是做“减一”,而唯一的制约因素就是要在最后留有足够“标记”的机会。当然并不是无脑的选最后n秒都做“标记”,因为有些“清零”可能在很靠后的时刻才会发生。怎么制定策略呢?这就需要从后往前去安排。 + +我们维护一个multiset叫做resets,里面存放那些确定要进行清零操作的nums的数值。当我们从后往前遍历的时候,判定时刻i是否能够进行“清零”,有以下两个条件:1.时刻i本身正是之前已经“计划”进行清零的时刻。2.假设i时刻进行清零的话,要保证在剩余的[i:t]的时间里,进行清零的数量(即multiset里面的元素个数)要小于剩余时间的一半,这样才能保证这些被清零的元素有机会被“标记”。如果不满足条件怎么办呢,这意味着我们不能增加这个清零名额,但是可以“调换”一个清零名额,将resets里面腾出一个来转给当前的index做清零。我们这样做有什么好处呢?这是因为也许可以减少“减一”操作的次数。假设当前时刻的元素如果做清零的话效果是-5,而resets里面有一个元素做清零其效果是-3,那么显然我们需要将resets里面做清零的元素拿出来留给当前元素。这叫做“反悔贪心”。 + +最终从后往前走完一遍之后,我们就知道哪些元素是真正需要被实施“清零”的。刨去这些之外,最后的n个时刻显然就是做“标记”操作的。这个安排保证了所有被清零的元素都能够得到“标记”。剩下的时刻就是应该做“减一”操作:我们必须要求所有“减一”操作的效果,加上“清零”操作的效果,最终一定是要大于nums里元素的总和。满足这些之后,才能判定目标在时间t内可行。 From 8cdcbe7bf049eae6d047d59b39eaf9f291be147f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 14:14:43 -0800 Subject: [PATCH 2434/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8c502a124..7ffb0cb2d 100644 --- a/Readme.md +++ b/Readme.md @@ -484,7 +484,8 @@ * ``反悔贪心`` [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) -[2599.Make-the-Prefix-Sum-Non-negative](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative) (H-) +[2599.Make-the-Prefix-Sum-Non-negative](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative) (H-) +[3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) * ``Dual PQ`` [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) From bb85485134359336403d8c296e454f6837c7bcb8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 15:40:08 -0800 Subject: [PATCH 2435/2729] Create 3068.Find-the-Maximum-Sum-of-Node-Values.cpp --- ...68.Find-the-Maximum-Sum-of-Node-Values.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Others/3068.Find-the-Maximum-Sum-of-Node-Values/3068.Find-the-Maximum-Sum-of-Node-Values.cpp diff --git a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/3068.Find-the-Maximum-Sum-of-Node-Values.cpp b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/3068.Find-the-Maximum-Sum-of-Node-Values.cpp new file mode 100644 index 000000000..9baa02703 --- /dev/null +++ b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/3068.Find-the-Maximum-Sum-of-Node-Values.cpp @@ -0,0 +1,32 @@ +using LL = long long; +class Solution { +public: + long long maximumValueSum(vector& nums, int k, vector>& edges) + { + vector>diff; + for (int x: nums) + { + diff.push_back({(x^k)-x, x}); + } + + sort(diff.rbegin(), diff.rend()); + + LL max_diff = 0; + LL total_diff = 0; + for (int i=0; i+1 max_diff) + { + max_diff = total_diff; + } + } + + LL total = 0; + for (int x: nums) total += x; + + return total + max_diff; + + } +}; From c82c7692c075cb92151026817a957f42a4fe709b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 15:41:12 -0800 Subject: [PATCH 2436/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7ffb0cb2d..133db6c32 100644 --- a/Readme.md +++ b/Readme.md @@ -1501,6 +1501,7 @@ [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) +[3068.Find-the-Maximum-Sum-of-Node-Values](https://github.com/wisdompeak/LeetCode/tree/master/Others/3068.Find-the-Maximum-Sum-of-Node-Values) (M+) * ``公式变形`` [2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` From 1f30eab797bb6568b769c61cf5b3b13d9c95e63f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 15:46:48 -0800 Subject: [PATCH 2437/2729] Create Readme.md --- Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md diff --git a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md new file mode 100644 index 000000000..cdf26c9b0 --- /dev/null +++ b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md @@ -0,0 +1,5 @@ +### 3068.Find-the-Maximum-Sum-of-Node-Values + +此题本质和树的结构没有任何关系。题意是在数组nums里,每次可以选取两个元素同时与k进行异或操作。问最终可以得到的最大的数组之和是多少。 + +考虑到任何一个元素,对k进行偶数次的异或操作,等同于没有进行操作。所以我们只会对每个元素进行最多一次操作。显然,我们会选择那些“增量”更大的元素进行操作。所以我们将每个元素的增量`(x^k)-x`按照从大到小的顺序排序,理论上将所有增量为正的元素进行操作,得到的和肯定最大。但是题意要求每次同时对两个元素进行操作,所以我们依次尝试前2个、前4个、前6个...所有取前偶数个元素的方案进行尝试。挑选其中“增量之和”最大的。最终的答案,就是sum(nums)加上最大的“增量之和”。 From 31fd39db3245e9361c16d4005a9bae9621397ba1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 16:07:43 -0800 Subject: [PATCH 2438/2729] Update Readme.md --- Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md index cdf26c9b0..f18e3312a 100644 --- a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md +++ b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md @@ -1,5 +1,5 @@ ### 3068.Find-the-Maximum-Sum-of-Node-Values -此题本质和树的结构没有任何关系。题意是在数组nums里,每次可以选取两个元素同时与k进行异或操作。问最终可以得到的最大的数组之和是多少。 +此题本质和树的结构没有任何关系,假设a与b相连,b与c相连。那么我们对a-b和b-c同时操作的话,就相当于直接对(a,c),而b没有变化。故题意转换一下,就是在数组nums里,每次可以任意选取两个元素同时与k进行异或操作(不用考虑edge的关系)。问最终可以得到的最大的数组之和是多少。 考虑到任何一个元素,对k进行偶数次的异或操作,等同于没有进行操作。所以我们只会对每个元素进行最多一次操作。显然,我们会选择那些“增量”更大的元素进行操作。所以我们将每个元素的增量`(x^k)-x`按照从大到小的顺序排序,理论上将所有增量为正的元素进行操作,得到的和肯定最大。但是题意要求每次同时对两个元素进行操作,所以我们依次尝试前2个、前4个、前6个...所有取前偶数个元素的方案进行尝试。挑选其中“增量之和”最大的。最终的答案,就是sum(nums)加上最大的“增量之和”。 From b1434b00ee14e264accc109d170072055e69a6f5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 16:08:04 -0800 Subject: [PATCH 2439/2729] Update Readme.md --- Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md index f18e3312a..824bc4941 100644 --- a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md +++ b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md @@ -1,5 +1,5 @@ ### 3068.Find-the-Maximum-Sum-of-Node-Values -此题本质和树的结构没有任何关系,假设a与b相连,b与c相连。那么我们对a-b和b-c同时操作的话,就相当于直接对(a,c),而b没有变化。故题意转换一下,就是在数组nums里,每次可以任意选取两个元素同时与k进行异或操作(不用考虑edge的关系)。问最终可以得到的最大的数组之和是多少。 +此题本质和树的结构没有任何关系,假设a与b相连,b与c相连。那么我们对(a,b)和(b,c)同时操作的话,就相当于直接对(a,c),而b没有变化。故题意转换一下,就是在数组nums里,每次可以任意选取两个元素同时与k进行异或操作(不用考虑edge的关系)。问最终可以得到的最大的数组之和是多少。 考虑到任何一个元素,对k进行偶数次的异或操作,等同于没有进行操作。所以我们只会对每个元素进行最多一次操作。显然,我们会选择那些“增量”更大的元素进行操作。所以我们将每个元素的增量`(x^k)-x`按照从大到小的顺序排序,理论上将所有增量为正的元素进行操作,得到的和肯定最大。但是题意要求每次同时对两个元素进行操作,所以我们依次尝试前2个、前4个、前6个...所有取前偶数个元素的方案进行尝试。挑选其中“增量之和”最大的。最终的答案,就是sum(nums)加上最大的“增量之和”。 From e70dd716676b7fb2f1f65a708aa1505edf23c9a0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Mar 2024 21:44:51 -0800 Subject: [PATCH 2440/2729] Create 3072.Distribute-Elements-Into-Two-Arrays-II.cpp --- ...Distribute-Elements-Into-Two-Arrays-II.cpp | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.cpp diff --git a/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.cpp b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.cpp new file mode 100644 index 000000000..645189786 --- /dev/null +++ b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.cpp @@ -0,0 +1,171 @@ +using LL = long long; +LL M = 1e9+7; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + LL delta; + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info += delta * (left->end - left->start + 1); + left->delta += delta; + right->info += delta * (right->end - right->start + 1); + right->delta += delta; + left->tag = 1; + right->tag = 1; + tag = 0; + delta = 0; + } + } + + void updateRangeBy(int a, int b, int val) // increase range [a,b] by val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info += val * (end-start+1); + delta += val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRangeBy(a, b, val+delta); + right->updateRangeBy(a, b, val+delta); + delta = 0; + tag = 0; + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +class Solution { +public: + vector resultArray(vector& nums) + { + setSet(nums.begin(), nums.end()); + int idx = 0; + unordered_mapMap; + for (int x: Set) + { + Map[x] = idx; + idx++; + } + int n = Set.size(); + + SegTreeNode* root1 = new SegTreeNode(0, n-1, 0); + int k = Map[nums[0]]; + root1->updateRangeBy(k, k , 1); + + SegTreeNode* root2 = new SegTreeNode(0, n-1, 0); + k = Map[nums[1]]; + root2->updateRangeBy(k, k , 1); + + vectorarr1({nums[0]}); + vectorarr2({nums[1]}); + for (int i=2; iqueryRange(k+1, n-1); + int y = root2->queryRange(k+1, n-1); + if (x>y) + { + arr1.push_back(nums[i]); + root1->updateRangeBy(k, k, 1); + } + else if (xupdateRangeBy(k, k, 1); + } + else + { + if (arr1.size() <= arr2.size()) + { + arr1.push_back(nums[i]); + root1->updateRangeBy(k, k, 1); + } + else + { + arr2.push_back(nums[i]); + root2->updateRangeBy(k, k, 1); + } + } + } + + vectorrets; + for (int x: arr1) rets.push_back(x); + for (int x: arr2) rets.push_back(x); + return rets; + } +}; From b447f97e34323abfd6212f3695aaa3ce42f84b9e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Mar 2024 21:45:24 -0800 Subject: [PATCH 2441/2729] Create 3072.Distribute-Elements-Into-Two-Arrays-II.py --- ....Distribute-Elements-Into-Two-Arrays-II.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.py diff --git a/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.py b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.py new file mode 100644 index 000000000..b41d13c5d --- /dev/null +++ b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.py @@ -0,0 +1,21 @@ +from sortedcontainers import SortedList +class Solution: + def resultArray(self, nums: List[int]) -> List[int]: + s1 = SortedList([nums[0]]) + s2 = SortedList([nums[1]]) + arr1 = [nums[0]] + arr2 = [nums[1]] + + for i in range(2, len(nums)): + x = len(s1)-s1.bisect_right(nums[i]) + y = len(s2)-s2.bisect_right(nums[i]) + if (x>y) or (x==y and len(arr1)<=len(arr2)): + arr1.append(nums[i]) + s1.add(nums[i]) + else: + arr2.append(nums[i]) + s2.add(nums[i]) + + return arr1+arr2 + + From 45a7119ec72efda4451e7a78b6d7a50549745b9d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Mar 2024 21:45:56 -0800 Subject: [PATCH 2442/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 133db6c32..c1e8a82a0 100644 --- a/Readme.md +++ b/Readme.md @@ -350,6 +350,7 @@ [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) +[3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 745d40813dc2c3d89b445d77c53afc3c7816e971 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Mar 2024 22:01:56 -0800 Subject: [PATCH 2443/2729] Create Readme.md --- .../3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md diff --git a/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md new file mode 100644 index 000000000..ced5d5bb5 --- /dev/null +++ b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md @@ -0,0 +1,5 @@ +### 3072.Distribute-Elements-Into-Two-Arrays-II + +此题如果用python的SortedList来做的话,秒杀。 + +用C++的话,得用线段树或者树状数组。将nums里面的元素按照从小到大离散化,按照数值从小到大映射成编号(即第x号元素)。建立两棵线段树,叶子节点的容量与编号的上限相同(记做M),叶子节点的初始数值都是零。然后就模拟题意,对于nums[i],我们得到它对应的编号k,那么我们就分别查询两棵线段树里[k+1,M-1]范围内叶子节点之和,即为`greaterCount(arr, nums[i])`. 然后对应需要插入的那棵线段树,将第i个叶子节点增1. 不断模拟,由此得到最终的分配方案。 From ffe3adf2afd135e837824ecfb3215fe9f4b3dd12 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Mar 2024 12:26:17 -0700 Subject: [PATCH 2444/2729] Create 3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp --- ...ximum-Strength-of-K-Disjoint-Subarrays.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp diff --git a/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp new file mode 100644 index 000000000..32a4afe90 --- /dev/null +++ b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { +public: + long long maximumStrength(vector& nums, int k) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + vector>>dp(n+1, vector>(k+1, vector(2, LLONG_MIN/3))); + + for (int i=0; i<=n; i++) + { + dp[i][0][0] = 0; + } + + for (int i=1; i<=n; i++) + for (int j=1; j<=k; j++) + { + if (j%2==0) + { + dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]); + dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) - (LL)nums[i]*(k+1-j); + } + else + { + dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]); + dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) + (LL)nums[i]*(k+1-j); + } + } + + return max(dp[n][k][0],dp[n][k][1]); + + } +}; From 0f3501148253ffb1b4d50fb26b8b935620af0adb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Mar 2024 12:27:43 -0700 Subject: [PATCH 2445/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c1e8a82a0..172a622a0 100644 --- a/Readme.md +++ b/Readme.md @@ -856,6 +856,7 @@ [2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) [2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) [2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H-) +[3077.Maximum-Strength-of-K-Disjoint-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays) (M+) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From fc84d480a1bd05fa9b15e8982ec924fb75b154b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Mar 2024 12:45:16 -0700 Subject: [PATCH 2446/2729] Create Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md diff --git a/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md new file mode 100644 index 000000000..6da7ffd55 --- /dev/null +++ b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md @@ -0,0 +1,18 @@ +### 3077.Maximum-Strength-of-K-Disjoint-Subarrays + +我们令dp[i][j]表示前i个元素里找出j个subarray的最优解。注意,我们认为k是个常数,即`dp[i][j] = sum[1]*k - sum[2]*(k-1) + ...`,而不是`dp[i][j] = sum[1]*j - sum[2]*(j-1) + ...`. + +显然,我们在考虑dp[i][j]时,会思考对于nums[i]的决策。如果nums[i]不加入任何subarray,那么就有`dp[i][j] = dp[i-1][j]`. 如果nums[i]加入subarray,那么它就是属于sum[j]。但是此时有一个问题,它是加入已有的sum[j]呢,还是自己独创一个sum[j]。前者的话就是`dp[i-1][j]+nums[i]`,后者就是`dp[i-1][j-1]+nums[i]`. 但是注意到,前者要求`dp[i-1][j]`中的sum[j]必须结尾在第i-1个元素,才能将nums[i]顺利接在sum[j]里,而我们的dp定义并没有这个约束。 + +为了解决这个问题,我们重新定义dp,加入第三个维度表示“最后一个subarray是否以当前元素结尾”。即dp[i][j][0]表示前i个元素分成j个subarray,且nums[i]不参与最后一个subarray;类似dp[i][j][1]表示前i个元素分成j个subarray,且nums[i]参与了最后一个subarray。于是我们容易写出新的转移方程。以j是偶数为例,对于dp[i][j][0],由于nums[i]不起作用,完全取决于dp[i-1][j],不用考虑它的第三个维度: +``` +dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]); +``` +对于dp[i][j][1],我们需要考虑nums[i]是否是接在nums[i-1]后面属于同一个subarray,还是自己新成立一个subarray。如果是前者,我们考虑的前驱状态是dp[i-1][j][1]; 如果是后者,我们考虑的前驱状态是dp[i-1][j-1][x] +``` +dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) - (LL)nums[i]*(k+1-j); +``` +最终返回的答案是`max(dp[n][k][0], dp[n][k][1])`. + +初始状态是对于所有的dp[i][0][0]赋值为零,其他都设为负无穷大。 + From aba4b1efffa24b5555064bfdaf7787c4f7256ffc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Mar 2024 12:45:29 -0700 Subject: [PATCH 2447/2729] Update Readme.md --- .../3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md index 6da7ffd55..3380b64cc 100644 --- a/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md +++ b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md @@ -10,7 +10,7 @@ dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]); ``` 对于dp[i][j][1],我们需要考虑nums[i]是否是接在nums[i-1]后面属于同一个subarray,还是自己新成立一个subarray。如果是前者,我们考虑的前驱状态是dp[i-1][j][1]; 如果是后者,我们考虑的前驱状态是dp[i-1][j-1][x] ``` -dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) - (LL)nums[i]*(k+1-j); +dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) - (LL)nums[i]*(k+1-j); ``` 最终返回的答案是`max(dp[n][k][0], dp[n][k][1])`. From 9168298e492450cad93eeda5dcf63826a3c7b4e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 11:15:31 -0700 Subject: [PATCH 2448/2729] Create 3093.Longest-Common-Suffix-Queries.cpp --- .../3093.Longest-Common-Suffix-Queries.cpp | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Trie/3093.Longest-Common-Suffix-Queries/3093.Longest-Common-Suffix-Queries.cpp diff --git a/Trie/3093.Longest-Common-Suffix-Queries/3093.Longest-Common-Suffix-Queries.cpp b/Trie/3093.Longest-Common-Suffix-Queries/3093.Longest-Common-Suffix-Queries.cpp new file mode 100644 index 000000000..4c2104612 --- /dev/null +++ b/Trie/3093.Longest-Common-Suffix-Queries/3093.Longest-Common-Suffix-Queries.cpp @@ -0,0 +1,71 @@ +class TrieNode +{ + public: + TrieNode* next[26]; + int idx; + TrieNode() + { + for (int i=0; i<26; i++) + next[i] = NULL; + idx = -1; + } +}; + +class Solution { + TrieNode* root = new TrieNode(); +public: + vector stringIndices(vector& wordsContainer, vector& wordsQuery) + { + vector>arr; + for (int i=0; i&a, const pair&b) + { + if (a.first.size() != b.first.size()) + return a.first.size() < b.first.size(); + else + return a.second < b.second; + }); + + for (int i=arr.size()-1; i>=0; i--) + { + TrieNode* node = root; + string s = arr[i].first; + for (int j=s.size()-1; j>=0; j--) + { + if (node->next[s[j]-'a']==NULL) + node->next[s[j]-'a'] = new TrieNode(); + node = node->next[s[j]-'a']; + node->idx = arr[i].second; + } + } + + root->idx = arr[0].second; + vectorrets; + for (auto& query: wordsQuery) + { + TrieNode* node = root; + int ans = -1; + for (int i=query.size()-1; i>=0; i--) + { + if (node->next[query[i]-'a']!=NULL) + node = node->next[query[i]-'a']; + else + { + ans = node->idx; + break; + } + } + if (ans==-1) + ans = node->idx; + + rets.push_back(ans); + + } + + return rets; + } +}; From 9a84eb42c923c0972577b720240bc8a6fc5c7915 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 11:16:21 -0700 Subject: [PATCH 2449/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 172a622a0..3d70780b6 100644 --- a/Readme.md +++ b/Readme.md @@ -667,6 +667,7 @@ [1858.Longest-Word-With-All-Prefixes](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1858.Longest-Word-With-All-Prefixes) (M) [2416.Sum-of-Prefix-Scores-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2416.Sum-of-Prefix-Scores-of-Strings) (M) [2977.Minimum-Cost-to-Convert-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2977.Minimum-Cost-to-Convert-String-II) (H) +[3093.Longest-Common-Suffix-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Trie/3093.Longest-Common-Suffix-Queries) (H-) * ``Trie and XOR`` [421.Maximum-XOR-of-Two-Numbers-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/421.Maximum-XOR-of-Two-Numbers-in-an-Array) (H-) [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) From 324334a3caaf6ef456e56591398be066d135fddd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 11:27:09 -0700 Subject: [PATCH 2450/2729] Create Readme.md --- Trie/3093.Longest-Common-Suffix-Queries/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Trie/3093.Longest-Common-Suffix-Queries/Readme.md diff --git a/Trie/3093.Longest-Common-Suffix-Queries/Readme.md b/Trie/3093.Longest-Common-Suffix-Queries/Readme.md new file mode 100644 index 000000000..1f07cba79 --- /dev/null +++ b/Trie/3093.Longest-Common-Suffix-Queries/Readme.md @@ -0,0 +1,9 @@ +### 3093.Longest-Common-Suffix-Queries + +在一堆字符串里面高效地寻找一个字符串(或它的前缀/后缀),显然我们会使用字典树的数据结构。 + +本题里面,我们在字典树里游走时,对于所处的节点,它可能被多个wordsContainer里面的字符串共享。那么对于每个节点,它究竟属于哪个字符串呢?根据题意,我们的选择依据是:先看总长度更小、再看出现的序号更小。因此,我们需要依据这个规则,给每个节点标记idx这个属性。所以对wordsQuery的某个后缀在字典树里游走完之后,它停留的节点的idx就是答案。 + +如果高效地给字典树的每个节点赋值idx呢?其实很简单,我们先将总长度更大的字符串加入字典树,再将总长度更小的字符串加入字典树。每次加入字符串时,idx的值就按加入字符串的index来。这样我们就发现,字符串长度小的自动会override每个节点的idx属性。同理,我们将wordsContainer序号更大的字符串先加入字典树,再将序号更小的字符串后加入字典树,这样每个节点的idx就会更新为相对更小的wordsContainer index。 + +综上,我们只需要将wordsContainer排序,按照“先看总长度更小、再看出现的序号更小”的原则排序,然后反序,按照后缀加入字典树。然后将wordsQuery的每个字符串按后缀在字典树里游走,最终停留在哪个节点,该节点的idx属性就是答案。 From ef695728c36a7b1c0df928faf9052a3c50d76d1e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 21:19:35 -0700 Subject: [PATCH 2451/2729] Update Readme.md --- Graph/2699.Modify-Graph-Edge-Weights/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Graph/2699.Modify-Graph-Edge-Weights/Readme.md b/Graph/2699.Modify-Graph-Edge-Weights/Readme.md index f1bd2a819..aa7ec6d09 100644 --- a/Graph/2699.Modify-Graph-Edge-Weights/Readme.md +++ b/Graph/2699.Modify-Graph-Edge-Weights/Readme.md @@ -7,3 +7,9 @@ 我们再审视一下我们的Dijkstra算法。注意当我们每次从PQ里弹出一个已经确定最短距离的的点,会尝试通过其邻接的边将一个新点加入PQ,如果我们所用到的所有的边都是不可修改的,那么我们弹出的点及其最短路径也都是不可修改的。但是当我们需要用到一条可修改的边时,比如说已知从起点到a的最短路径,然后a与b有一条可修改的边,此时我们在将b加入PQ时就会有所顾虑。如果“起点到a的最短距离”+“ab之间的边权1”+“b到终点的最短距离”小于target的话,那么我们就违反了题意。所以我们可以贪心地更改这条可修改边,使得三段距离之和变成target。这就意味着我们需要提前计算“b到终点的最短距离”。这样,当b收录进入PQ的时候,我们就保证了这条到达b的路径,不会造成任何“起点到终点的最短路径小于target”,我们可以放心地加入PQ共后续使用。 所以依据上面的算法,可以在一次的Dijkstra的过程中不断地贪心地设置可修改边的边权。知道我们发现终点从PQ里弹出时,意味着我们已经确定了起点到终点的最短距离。如果这个距离不为target,那么就是无解。 + +=========== + +Q: 当边P-Q为可编辑边时,则需考虑`dist[S-P] + weight(P, Q) + dist1[Q-D] < target`,但为何我们能够笃定dist1[Q-D]未经过任何我们已经修改过的可编辑边呢? 因为如果dist1[Q-D]有经过已修改过的可编辑边,现阶段的dist1[Q-D]其实已经比当时纪录的还大了,那上面的条件式可能会给出错误的判定结果。 + +A: 假设如你所说,当从优先队列弹出P点时,在Q到D的最短路径有一条已经修改过的可编辑边,假设为AB。既然AB已经修改过,那么AB必然是从起点S到某个点(假设是C)的最短距离(已经早于P点从优先队列里处理过)的一部分。于是即存在这样一条路径S-A-B-C,它是短于S-P的(这是因为Dijkstra算法会会按从小到大输出各个点的最短路径)。OK,既然 S-A-B-C Date: Sun, 24 Mar 2024 21:21:05 -0700 Subject: [PATCH 2452/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3d70780b6..78368c215 100644 --- a/Readme.md +++ b/Readme.md @@ -849,7 +849,7 @@ [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H) [813.Largest-Sum-of-Averages](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/813.Largest-Sum-of-Averages) (H-) [1278.Palindrome-Partitioning-III](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1278.Palindrome-Partitioning-III) (H) -[1335.Minimum-Difficulty-of-a-Job-Schedule](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1335.Minimum-Difficulty-of-a-Job-Schedule) (M+) +[1335.Minimum-Difficulty-of-a-Job-Schedule](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1335.Minimum-Difficulty-of-a-Job-Schedule) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) [1977.Number-of-Ways-to-Separate-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1977.Number-of-Ways-to-Separate-Numbers) (H) [2463.Minimum-Total-Distance-Traveled](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled) (M+) From a867ade045a54f6e8569a49657a78fcbb62e0485 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 21:22:27 -0700 Subject: [PATCH 2453/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 78368c215..a27e6cf4b 100644 --- a/Readme.md +++ b/Readme.md @@ -1193,7 +1193,7 @@ [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` -[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) +[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) From 0e9a159a12edbd6dfd6d98cbf2807aa4a9907916 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 21:25:35 -0700 Subject: [PATCH 2454/2729] Create 3086.Minimum-Moves-to-Pick-K-Ones.cpp --- .../3086.Minimum-Moves-to-Pick-K-Ones.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp new file mode 100644 index 000000000..ccdfeff79 --- /dev/null +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp @@ -0,0 +1,58 @@ +using LL = long long; +class Solution { +public: + long long minimumMoves(vector& nums, int k, int maxChanges) + { + vectorarr; + for (int i=0; i= k-task) + ret = min(ret, helper(arr, task) + (k-task)*2); + + task = min(m, k-maxChanges+1); + if (maxChanges >= k-task && k-task>=0) + ret = min(ret, helper(arr, task) + (k-task)*2); + + task = min(m, k-maxChanges+2); + if (maxChanges >= k-task && k-task>=0) + ret = min(ret, helper(arr, task) + (k-task)*2); + + task = min(m, k-maxChanges+3); + if (maxChanges >= k-task && k-task>=0) + ret = min(ret, helper(arr, task) + (k-task)*2); + + return ret; + } + + LL helper(vector&arr, int k) + { + if (k==0) return 0; + + int m = arr.size(); + + LL sum = 0; + for (int i=0; i Date: Sun, 24 Mar 2024 21:26:07 -0700 Subject: [PATCH 2455/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a27e6cf4b..588d09e1b 100644 --- a/Readme.md +++ b/Readme.md @@ -56,6 +56,7 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) +[3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 19112124b4d06e628698857ff8cf7475cffc8076 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 21:29:16 -0700 Subject: [PATCH 2456/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 588d09e1b..898ab2af2 100644 --- a/Readme.md +++ b/Readme.md @@ -1208,6 +1208,7 @@ [1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) [2967.Minimum-Cost-to-Make-Array-Equalindromic](https://github.com/wisdompeak/LeetCode/tree/master/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic) (H-) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) +[3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) From 438538e5bb755c8c8adfd12f8551e8e1d59dc16b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 18:38:35 -0700 Subject: [PATCH 2457/2729] Create 3098.Find-the-Sum-of-Subsequence-Powers.cpp --- ...098.Find-the-Sum-of-Subsequence-Powers.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/3098.Find-the-Sum-of-Subsequence-Powers.cpp diff --git a/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/3098.Find-the-Sum-of-Subsequence-Powers.cpp b/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/3098.Find-the-Sum-of-Subsequence-Powers.cpp new file mode 100644 index 000000000..3360df7b3 --- /dev/null +++ b/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/3098.Find-the-Sum-of-Subsequence-Powers.cpp @@ -0,0 +1,55 @@ +using LL = long long; +class Solution { + LL M = 1e9+7; + int n; +public: + int sumOfPowers(vector& nums, int K) + { + n = nums.size(); + sort(nums.begin(), nums.end()); + nums.insert(nums.begin(), 0); + + LL ret = 0; + for (int i=1; i<=n; i++) + for (int j=i+1; j<=n; j++) + { + int d = nums[j]-nums[i]; + ret = (ret + helper(nums, K, d, i, j)) % M; + } + return ret; + } + + LL helper(vector& nums, int K, int d, int a, int b) + { + vector>dp1(n+2, vector(n+2)); + vector>dp2(n+2, vector(n+2)); + + for (int i=1; i<=n; i++) + { + dp1[i][1] = 1; + dp2[i][1] = 1; + } + + for (int i=1; i<=a; i++) + for (int j=2; j<=K; j++) + { + for (int k=1; nums[i]-nums[k]>d && k=b; i--) + for (int j=2; j<=K; j++) + { + for (int k=n; nums[k]-nums[i]>=d && k>i; k--) + dp2[i][j] = (dp2[i][j] + dp2[k][j-1]) % M; + } + + LL ret = 0; + for (int t=1; t Date: Sat, 30 Mar 2024 18:39:04 -0700 Subject: [PATCH 2458/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 898ab2af2..f54d82f96 100644 --- a/Readme.md +++ b/Readme.md @@ -750,6 +750,7 @@ [2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) [2979.Most-Expensive-Item-That-Can-Not-Be-Bought](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought) (M+) [3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification) (H-) +[3098.Find-the-Sum-of-Subsequence-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 90c28367fa88df009d63e8344f8a0720ea3c4da1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 18:53:16 -0700 Subject: [PATCH 2459/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/Readme.md diff --git a/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/Readme.md b/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/Readme.md new file mode 100644 index 000000000..c4503a788 --- /dev/null +++ b/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/Readme.md @@ -0,0 +1,13 @@ +### 3098.Find-the-Sum-of-Subsequence-Powers + +表面上求的是“子序列”,其实求的是“子集”,对于顺序没有要求。所以我们会将nums先排序。此时任何“子序列”里的最小元素之差,必然出现在所按顺序选取的两个元素之间。 + +考虑到n=50不大,可以枚举出所有的元素之差,比如元素a和元素b,约定它们是子序列里的“最小元素之差”(记做d),求这样的长度为k的子序列有多少个。这可以判断出至少有n^3的解法。而事实上,很意外地,本题可以容忍n^5的复杂度。所以这个思路是可行的。 + +接下来我们就解决上面提出的问题:在一个有序数组nums里,对于元素a和元素b,约定它们是子序列里的“最小元素之差”(记做d),求这样的长度为K的子序列有多少个。事实上,我们可以用DP求出在[1,a]区间内有多少相邻元素之差大于d的子序列。我们令dp1[i][j]表示以i结尾的、长度为j、且相邻元素跨度大于d的子序列个数。我们只需要找到前一个符合条件的位置k,满足`nums[i]-nums[k]>d`,就有`dp1[i][j] += dp1[k][j-1]`,将所有符合条件的j遍历一遍,就可以求出dp[i][j]. + +同理,我们从后往前进行DP,求出在[b,n]区间里有多少相邻元素之差大于d的子序列。可以求解dp2[i][j]表示以i开头的、长度为j、且相邻元素跨度大于等于d的子序列个数。 + +这样,我们只需要将期望长度K分配给[a,b]的前后两段,假设分别是t和K-t,就可以得到组合数`dp[a][t]*dp[b][K-t]`,对应的就是包含a和b的、符合条件的子序列的个数。我们对于所有t=1,2,...K-1,将组合数求和即可。 + +特别注意,dp1和dp2的定义略有不同,前者要求跨度大于d,后者要求跨度大于等于d。这是因为一个子序列里可能有多个最小跨度d,我们约定只认为第一个出现的最小跨度d是我们的枚举对象。所以在[1,a]区间内,我们不接受相邻元素跨度恰好为d的情况。 From 0883a9bb6b2b418b91d9756768d06f996f603eb8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 20:18:58 -0700 Subject: [PATCH 2460/2729] Create 3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp --- ...hortest-Subarray-With-OR-at-Least-K-II.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp diff --git a/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp b/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp new file mode 100644 index 000000000..8df5624a5 --- /dev/null +++ b/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int minimumSubarrayLength(vector& nums, int k) + { + int n = nums.size(); + int left = 1, right = n; + while (left < right) + { + int mid = left + (right-left)/2; + if (isOK(nums, k, mid)) + right = mid; + else + left = mid+1; + } + if (!isOK(nums, k, left)) return -1; + else return left; + } + + bool isOK(vector&nums, int k, int len) + { + vectorcount(31); + for (int i=0; i>j)&1); + } + + for (int i=len-1; i>j)&1); + + int sum = 0; + for (int j=0; j<31; j++) + if (count[j]>0) sum += (1<= k) return true; + + for (int j=0; j<31; j++) + count[j] -= ((nums[i-len+1]>>j)&1); + } + + return false; + } +}; From 1cb2e31cd2145b2047f343613aa11f339ebf008f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 20:19:27 -0700 Subject: [PATCH 2461/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f54d82f96..323f0ebbf 100644 --- a/Readme.md +++ b/Readme.md @@ -143,6 +143,7 @@ [2861.Maximum-Number-of-Alloys](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2861.Maximum-Number-of-Alloys) (M+) [3048.Earliest-Second-to-Mark-Indices-I](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I) (M+) [3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) +[3097.Shortest-Subarray-With-OR-at-Least-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II) (M) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 509cf8b137df293aa04f34c524778beb7f7cbf05 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 20:23:29 -0700 Subject: [PATCH 2462/2729] Create Readme.md --- .../3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md diff --git a/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md b/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md new file mode 100644 index 000000000..c9088556d --- /dev/null +++ b/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md @@ -0,0 +1,5 @@ +### 3097.Shortest-Subarray-With-OR-at-Least-K-II + +对于bitwise OR的操作,最大的特点是,OR的对象越多,答案越大。于是本题的答案显然具有单调性,越长的subarray越容易得到超过K的结果。所以我们只需要二分搜索长度即可。 + +于是本题就转化成了,对于一个固定长度L,判断是否存在这样长度的滑窗,使得里面元素的bitwise OR的结果大于等于K。我们只需要在滑窗移动的过程中,记录每个bit位上出现过多少次1即可。只要存在至少一个1,那么bitwise OR的结果在该位上就是1. From adcda59be998895097ceef90bfaa7ba1052c4f2d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 00:00:39 -0700 Subject: [PATCH 2463/2729] Create 3102.Minimize-Manhattan-Distances.cpp --- .../3102.Minimize-Manhattan-Distances.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Math/3102.Minimize-Manhattan-Distances/3102.Minimize-Manhattan-Distances.cpp diff --git a/Math/3102.Minimize-Manhattan-Distances/3102.Minimize-Manhattan-Distances.cpp b/Math/3102.Minimize-Manhattan-Distances/3102.Minimize-Manhattan-Distances.cpp new file mode 100644 index 000000000..fea4f8e9a --- /dev/null +++ b/Math/3102.Minimize-Manhattan-Distances/3102.Minimize-Manhattan-Distances.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int minimumDistance(vector>& points) + { + vector>arr(4); + + for (auto& p: points) + { + arr[0].insert(p[0]+p[1]); + arr[1].insert(p[0]-p[1]); + arr[2].insert(-p[0]+p[1]); + arr[3].insert(-p[0]-p[1]); + } + + int ret = INT_MAX/2; + for (auto& p: points) + { + arr[0].erase(arr[0].find(p[0]+p[1])); + arr[1].erase(arr[1].find(p[0]-p[1])); + arr[2].erase(arr[2].find(-p[0]+p[1])); + arr[3].erase(arr[3].find(-p[0]-p[1])); + + int ans = 0; + ans = max(ans, *prev(arr[0].end()) - *arr[0].begin()); + ans = max(ans, *prev(arr[1].end()) - *arr[1].begin()); + ans = max(ans, *prev(arr[2].end()) - *arr[2].begin()); + ans = max(ans, *prev(arr[3].end()) - *arr[3].begin()); + + ret = min(ret, ans); + + arr[0].insert(p[0]+p[1]); + arr[1].insert(p[0]-p[1]); + arr[2].insert(-p[0]+p[1]); + arr[3].insert(-p[0]-p[1]); + } + + return ret; + } +}; From 530b370152ed3ad609054da6843c417035860423 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 00:08:08 -0700 Subject: [PATCH 2464/2729] Create Readme.md --- Math/3102.Minimize-Manhattan-Distances/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Math/3102.Minimize-Manhattan-Distances/Readme.md diff --git a/Math/3102.Minimize-Manhattan-Distances/Readme.md b/Math/3102.Minimize-Manhattan-Distances/Readme.md new file mode 100644 index 000000000..16a0ec2b2 --- /dev/null +++ b/Math/3102.Minimize-Manhattan-Distances/Readme.md @@ -0,0 +1,7 @@ +### 3102.Minimize-Manhattan-Distances + +此题的本质就是1131.Maximum-of-Absolute-Value-Expression,求二维点集里的最大曼哈顿距离。 + +我们需要维护四个有序容器,分别盛装所有点的(x+y), (x-y), (-x+y), (-x-y)。记每个容器中的最大值减去最小值为t,那么四个t中的最大值就是二维点集里的最大曼哈顿距离。 + +根据上述原理,我们遍历所有的点,每次从容器里面将一个点去除,再求此时的最大曼哈顿距离,只需要logN的时间。这样遍历N个点之后,用NlogN的时间就可以求出最优解。 From 6bb20d914ad1be8388044301a8231581715b6163 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 00:11:33 -0700 Subject: [PATCH 2465/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 323f0ebbf..3821d6339 100644 --- a/Readme.md +++ b/Readme.md @@ -1196,12 +1196,13 @@ [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` -[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) -[1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) +[1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) +[3102.Minimize-Manhattan-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Math/3102.Minimize-Manhattan-Distances) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) * ``Median Theorem`` +[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) From 65acab585c8ac9a776bf83a3ddf335da9e0d1935 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 00:15:56 -0700 Subject: [PATCH 2466/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3821d6339..ca0f542d0 100644 --- a/Readme.md +++ b/Readme.md @@ -1197,7 +1197,7 @@ [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) -[1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) +[1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) [3102.Minimize-Manhattan-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Math/3102.Minimize-Manhattan-Distances) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) From 03e25f4512a62631eec05b1c992e67eaf8a1813a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 23:55:27 -0700 Subject: [PATCH 2467/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index ca0f542d0..9e7f812ad 100644 --- a/Readme.md +++ b/Readme.md @@ -56,7 +56,6 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) -[3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) @@ -1520,7 +1519,8 @@ * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) -[2615.Sum-of-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Others/2615.Sum-of-Distances) (M+) +[2615.Sum-of-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Others/2615.Sum-of-Distances) (M+) +[3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) * ``Count Subarray by Element`` [828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) From f85855ca708e839104c77c58218bc426e7e77ac1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Apr 2024 00:07:03 -0700 Subject: [PATCH 2468/2729] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Math/3086.Minimum-Moves-to-Pick-K-Ones/Readme.md diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/Readme.md b/Math/3086.Minimum-Moves-to-Pick-K-Ones/Readme.md new file mode 100644 index 000000000..c9bce9a4e --- /dev/null +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/Readme.md @@ -0,0 +1,22 @@ +### 3086.Minimum-Moves-to-Pick-K-Ones + +如果不考虑第一种操作,仅考虑第二种操作,那么题意就是说找一个位置,然后将临近的k个1移动到该位置,求最少的移动数。显然,我们会将nums里所有是1的index都拿出来放入一个数组arr,那么我们需要在arr里找一个长度为k的滑窗,使得“将它们聚拢至一处”的移动最少:显然我们会将1都聚拢到滑窗里最中间的位置(中位数)。有了以上的结论,我们只需要将滑窗在arr里面走一遍,就能找到某处滑窗位置,使得移动的次数最少。 + +接下来考虑第一种操作。我们发现它其实“很好用”,我们只需要额外操作两次就可以得到一分:在终点位置旁边的0翻转成1,再将1移动到终点位置。相比于将nums里已有的1“长途搬运”过来,这必然是很合算。所以理论上来说,第一种操作的maxChangs都应该尽量用掉,这样使用第二种操作时,我们只需要将`k-maxChanges`个1聚拢到一处即可。 + +但是以上的这个结论有几个例外:那就是如果在“终点”位置本身就是1,或者左边/右边有一个1,或者两边都有一个1,那么得到那些1带来的分数所需要的操作,显然会更少。所以实际上,我们使用第一种操作的次数,还可能是`maxChanges-1`,或者`maxChanges-2`,或者是`maxChanges-3`。但是注意,没有其他理由可以更少地使用第一种操作了。 + +所以,我们将第二种操作写成一个helper函数,那么我们最终的答案就是以下三种中的最小值: +``` +maxChanges*2 + helper(k-maxChanges) +(maxChanges-1)*2 + helper(k-maxChanges+1) +(maxChanges-2)*2 + helper(k-maxChanges+2) +(maxChanges-3)*2 + helper(k-maxChanges+3) +``` +当然,计算上述表达式的时候,要保证每种操作的数目不能为负数。 + +至于如何用线性时间来实现helper函数,这类似于`1685.Sum-of-Absolute-Differences-in-a-Sorted-Array`. 假设[0:k-1]里所有元素到其中位数位置的距离之和是s,那么[1:k]里所有元素到其中位数位置的距离之和是:`s + d * (k/2+1) - d * (k - (k/2+1)) - abs(arr[k/2+1]-arr[0]) + abs(arr[k/2+1]-arr[k])```,其中`d=arr[k/2+1]-arr[k/2]`. +``` +0 ... k/2 ... k-1 + 1 ... k/2+1 ... k +``` From d2c26845c6ca321443f8b48f5c1c721be991ab0f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Apr 2024 00:11:12 -0700 Subject: [PATCH 2469/2729] Update 3086.Minimum-Moves-to-Pick-K-Ones.cpp --- .../3086.Minimum-Moves-to-Pick-K-Ones.cpp | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp index ccdfeff79..330fb4874 100644 --- a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp @@ -15,22 +15,18 @@ class Solution { LL ret = LLONG_MAX; maxChanges = min(k, maxChanges); + + if (k-maxChanges <= m && maxChanges>=0) + ret = min(ret, helper(arr, k-maxChanges) + maxChanges*2); - int task = min(m, k-maxChanges); - if (maxChanges >= k-task) - ret = min(ret, helper(arr, task) + (k-task)*2); - - task = min(m, k-maxChanges+1); - if (maxChanges >= k-task && k-task>=0) - ret = min(ret, helper(arr, task) + (k-task)*2); + if (k-maxChanges+1 <= m && maxChanges-1>=0) + ret = min(ret, helper(arr, k-maxChanges+1) + (maxChanges-1)*2); - task = min(m, k-maxChanges+2); - if (maxChanges >= k-task && k-task>=0) - ret = min(ret, helper(arr, task) + (k-task)*2); + if (k-maxChanges+2 <= m && maxChanges-2>=0) + ret = min(ret, helper(arr, k-maxChanges+2) + (maxChanges-2)*2); - task = min(m, k-maxChanges+3); - if (maxChanges >= k-task && k-task>=0) - ret = min(ret, helper(arr, task) + (k-task)*2); + if (k-maxChanges+3 <= m && maxChanges-3>=0) + ret = min(ret, helper(arr, k-maxChanges+3) + (maxChanges-3)*2); return ret; } @@ -46,10 +42,10 @@ class Solution { sum += abs(arr[i]-arr[k/2]); LL ret = sum; - for (int i=1; i+k-1 Date: Mon, 1 Apr 2024 23:47:57 -0700 Subject: [PATCH 2470/2729] Update 3086.Minimum-Moves-to-Pick-K-Ones.cpp --- .../3086.Minimum-Moves-to-Pick-K-Ones.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp index 330fb4874..b8f3c195f 100644 --- a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp @@ -38,7 +38,7 @@ class Solution { int m = arr.size(); LL sum = 0; - for (int i=0; i Date: Wed, 3 Apr 2024 00:04:21 -0700 Subject: [PATCH 2471/2729] Create 3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp --- ...e-Sum-of-the-Power-of-All-Subsequences.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp diff --git a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp new file mode 100644 index 000000000..f48c15590 --- /dev/null +++ b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { + LL dp[105][105][105]; + LL M = 1e9+7; +public: + int sumOfPower(vector& nums, int k) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + for (int i=0; i<=n; i++) + dp[i][0][0] = 1; + + for (int i=1; i<=n; i++) + for (int s=0; s<=k; s++) + for (int j=0; j<=i; j++) + { + dp[i][s][j] = dp[i-1][s][j]; + if (s>=nums[i] && j>0) + dp[i][s][j] += dp[i-1][s-nums[i]][j-1]; + dp[i][s][j] %= M; + } + + vectorpower(10005); + power[0] = 1; + for (int i=1; i<=n; i++) + power[i] = power[i-1]*2%M; + + LL ret = 0; + for (int j=1; j<=n; j++) + { + LL t = dp[n][k][j]; + ret = (ret + t*power[n-j]%M) % M; + } + + return ret; + } +}; From 21768e7b903f685263b0ebee4e559eefcc9c6d3e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 00:04:53 -0700 Subject: [PATCH 2472/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9e7f812ad..74e43f899 100644 --- a/Readme.md +++ b/Readme.md @@ -750,6 +750,7 @@ [2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) [2979.Most-Expensive-Item-That-Can-Not-Be-Bought](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought) (M+) [3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification) (H-) +[3082.Find-the-Sum-of-the-Power-of-All-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences) (H-) [3098.Find-the-Sum-of-Subsequence-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) From 94fd39f4dbf3ebf04a6d008d6dad0feb65efa7b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 00:14:00 -0700 Subject: [PATCH 2473/2729] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md diff --git a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md new file mode 100644 index 000000000..4671c4ad1 --- /dev/null +++ b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md @@ -0,0 +1,12 @@ +### 3082.Find-the-Sum-of-the-Power-of-All-Subsequences + +“子序列的子序列”思考起来比较费劲,但是如果只是求“和为k的子序列的个数”,这个看上去就是典型的DP。然后我们再思考一下,本题其实就是求每个“和为k的子序列”有多少个超序列(super sequence)。 + +举个列子,假设总元素个数是n。如果有一个子序列q的长度是m,它的和是k,那么nums里就有`(n-m)^2`个序列包含q,这些序列的都有这么一个子序列q满足条件,所以q本质上给最终答案贡献了`(n-m)^2`。 + +所以我们只需要求出所有不同长度的、和为k的子序列个数。这个只不过在前述DP的基础上,再增加一个变量/下标记录已经选取元素的个数。即令dp[i][s][j]表示在前i个元素里、选取j个元素、和为s的子序列有多少个。显然它的转移方程就取决于第i个元素是否选取: +```cpp +dp[i][s][j] += dp[i-1][s][j]; // no select nums[i] +dp[i][s][j] += dp[i-1][s-nums[i]][j-1], if (s>=nums[i] && j>=1); // select nums[i] +``` +最终考察完整个nums之后,我们遍历子序列的长度j,就可以知道存在有dp[n][k][j]个符合要求的子序列,并且其长度是j。那么它的超序列就有`(n-j)^2`个。 From 924a7c81f790dec6737c368f4384b637baf9a9a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 00:18:21 -0700 Subject: [PATCH 2474/2729] Update 3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp --- .../3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp index f48c15590..60b9dccc8 100644 --- a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp +++ b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp @@ -8,8 +8,7 @@ class Solution { int n = nums.size(); nums.insert(nums.begin(), 0); - for (int i=0; i<=n; i++) - dp[i][0][0] = 1; + dp[0][0][0] = 1; for (int i=1; i<=n; i++) for (int s=0; s<=k; s++) From 62f0e31772474da48e73d4e5596f77873c381166 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 23:04:28 -0700 Subject: [PATCH 2475/2729] Update 2615.Sum-of-Distances.cpp --- .../2615.Sum-of-Distances.cpp | 43 ++++++++----------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp b/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp index ad7c6abdd..730e8a291 100644 --- a/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp +++ b/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp @@ -8,33 +8,24 @@ class Solution { for (int i=0; ians; - unordered_mapidx; - for (auto& [k,v]: Map) + vectorrets(n); + for (auto& [_, arr]: Map) { - idx[k] = 0; - LL sum = 0; - for (int p: v) - sum += abs(p - v[0]); - ans[k] = sum; + int m = arr.size(); + LL sum = 0; + for (int x: arr) + sum += abs(x - arr[0]); + rets[arr[0]] = sum; + + for (int i=0; i+1rets; - for (int x: nums) - { - rets.push_back(ans[x]); - int i = idx[x]; - if (i==Map[x].size()-1) continue; - LL temp = ans[x]; - int m = Map[x].size(); - temp += (Map[x][i+1]-Map[x][i])*(i+1); - temp -= (Map[x][i+1]-Map[x][i])*(m-1-i); - ans[x] = temp; - idx[x] = i+1; - } - + return rets; - - } + } }; From 42ea1beb438c28a8a3dbd2ff9cc1b32b6a196cc5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 23:25:37 -0700 Subject: [PATCH 2476/2729] Create Readme.md --- Others/2615.Sum-of-Distances/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2615.Sum-of-Distances/Readme.md diff --git a/Others/2615.Sum-of-Distances/Readme.md b/Others/2615.Sum-of-Distances/Readme.md new file mode 100644 index 000000000..8162d97b6 --- /dev/null +++ b/Others/2615.Sum-of-Distances/Readme.md @@ -0,0 +1,5 @@ +### 2615.Sum-of-Distances + +首先,我们会将所有相同元素的index收集起来放入一个数组,记做arr。那么对于arr[i]而言,我们需要求的就是arr里其他元素与arr[i]的绝对差值之和。对于这类题目,我们可以用线性的时间求出arr里每个元素的答案。 + +假设我们已经求出所有元素与arr[i]的绝对差值之和sum,那么rets[arr[i]]的答案就是sum。然后我们右移一格,考察arr[i+1]作为参考点,所有元素与其的差值之和。令`d=|arr[i+1]-arr[i]|`,且arr的长度是m。我们发现将参考点右移一位之后,前0~i号元素离新的基准点的差值都增加了d,而后面i+1到m-1好元素里新的基准点都减少了d。所以我们只需要更新`sum = sum + (i+1)*d - (m-i-1)*d`,就可以得到rets[arr[i+1]]的答案。依次类推,每次右移一位,就可以用o(1)时间来得到下一个参考点的答案。 From 4d9a942ccafee4e0de39b398c4b16a371805a571 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 23:27:47 -0700 Subject: [PATCH 2477/2729] Update Readme.md --- Others/2615.Sum-of-Distances/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2615.Sum-of-Distances/Readme.md b/Others/2615.Sum-of-Distances/Readme.md index 8162d97b6..39621a517 100644 --- a/Others/2615.Sum-of-Distances/Readme.md +++ b/Others/2615.Sum-of-Distances/Readme.md @@ -2,4 +2,4 @@ 首先,我们会将所有相同元素的index收集起来放入一个数组,记做arr。那么对于arr[i]而言,我们需要求的就是arr里其他元素与arr[i]的绝对差值之和。对于这类题目,我们可以用线性的时间求出arr里每个元素的答案。 -假设我们已经求出所有元素与arr[i]的绝对差值之和sum,那么rets[arr[i]]的答案就是sum。然后我们右移一格,考察arr[i+1]作为参考点,所有元素与其的差值之和。令`d=|arr[i+1]-arr[i]|`,且arr的长度是m。我们发现将参考点右移一位之后,前0~i号元素离新的基准点的差值都增加了d,而后面i+1到m-1好元素里新的基准点都减少了d。所以我们只需要更新`sum = sum + (i+1)*d - (m-i-1)*d`,就可以得到rets[arr[i+1]]的答案。依次类推,每次右移一位,就可以用o(1)时间来得到下一个参考点的答案。 +假设我们已经求出所有元素与arr[i]的绝对差值之和sum,那么arr[i]的答案就是sum。然后我们右移一格,考察arr[i+1]作为参考点,所有元素与新参考点的差值之和。这里,我们记`d=|arr[i+1]-arr[i]|`,且arr的长度是m。我们发现随着参考点的移动,前0~i号元素离新的参考点的差值都增加了d,而后面i+1到m-1号元素离新参考点的差值都减少了d。所以我们只需要更新`sum = sum + (i+1)*d - (m-i-1)*d`,就可以得到arr[i+1]的答案。依次类推,每次右移一位,就可以用o(1)时间来得到下一个参考点的答案。 From 321d6f1aee589580cbfaec9c6a82a7ee2f566488 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Apr 2024 20:39:44 -0700 Subject: [PATCH 2478/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md index 4671c4ad1..6f27c5469 100644 --- a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md +++ b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md @@ -9,4 +9,4 @@ dp[i][s][j] += dp[i-1][s][j]; // no select nums[i] dp[i][s][j] += dp[i-1][s-nums[i]][j-1], if (s>=nums[i] && j>=1); // select nums[i] ``` -最终考察完整个nums之后,我们遍历子序列的长度j,就可以知道存在有dp[n][k][j]个符合要求的子序列,并且其长度是j。那么它的超序列就有`(n-j)^2`个。 +最终考察完整个nums之后,我们遍历子序列的长度j,就可以知道存在有dp[n][k][j]个符合要求的子序列,并且其长度是j。那么它的超序列就有`2^(n-j)`个。 From e9affec17294c77694a04560de51afb5c9c80491 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Apr 2024 00:31:04 -0700 Subject: [PATCH 2479/2729] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 1d74c5ce8..e0d6fe36c 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -40,7 +40,7 @@ class SegTreeNode { left = new SegTreeNode(a, mid, val); right = new SegTreeNode(mid+1, b, val); - info = left->info + right->info; // check with your own logic + info = max(left->info, right->info); // check with your own logic } } From 2ae0acc96f8554e9d801eab1f9dee978580c8475 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Apr 2024 00:36:36 -0700 Subject: [PATCH 2480/2729] Create range_min.cpp --- Template/SegmentTree/range_min.cpp | 117 +++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 Template/SegmentTree/range_min.cpp diff --git a/Template/SegmentTree/range_min.cpp b/Template/SegmentTree/range_min.cpp new file mode 100644 index 000000000..5d39bde09 --- /dev/null +++ b/Template/SegmentTree/range_min.cpp @@ -0,0 +1,117 @@ +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = min(left->info, right->info); // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + info = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = min(left->info, right->info); // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = min(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MAX/2; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = min(left->queryRange(a, b), right->queryRange(a, b)); + info = min(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + +int main() +{ + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. + + for (auto& update: updates) + { + int start = update[0], end = update[1], val = update[2]; + root->updateRange(start, end ,val); // set the range [start, end] with val + } + + vectorrets(length); + for (int i=0; iqueryRange(i, i); // get single node val + return rets; +} From 3a1ea523981225159dc8bb7c7de0021d2d09a750 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 10:31:39 -0700 Subject: [PATCH 2481/2729] Create 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp --- ...ys-Where-Boundary-Elements-Are-Maximum.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp new file mode 100644 index 000000000..9c528e2e9 --- /dev/null +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp @@ -0,0 +1,29 @@ +using LL = long long; +class Solution { +public: + long long numberOfSubarrays(vector& nums) + { + int n = nums.size(); + vectorprevGreater(n, -1); + + stackstk; + for (int i=0; i>Map; + LL ret = 0; + for (int i=0; i Date: Sat, 20 Apr 2024 10:32:17 -0700 Subject: [PATCH 2482/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 74e43f899..531e6eddb 100644 --- a/Readme.md +++ b/Readme.md @@ -423,6 +423,7 @@ [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) [2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) +[3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum](https://github.com/wisdompeak/LeetCode/tree/master/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum) (M) * ``monotonic stack: other usages`` [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) From fcd7e7ef942d939266770ab9b8f2667edbb87598 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 10:39:22 -0700 Subject: [PATCH 2483/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md new file mode 100644 index 000000000..016dcbbc4 --- /dev/null +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md @@ -0,0 +1,5 @@ +### 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum + +我们考虑以i为结尾的subarray,那么该subarray的首位置必然是在i之前、且数值与nums[i]相同的那些元素。这些我们是容易准备好的。 + +同时,因为要求nums[i]是subarray里最大的元素,所以首元素的位置不能太靠前,越靠前的话就越容易包含进大于nums[i]的数。所以我们提前用单调栈计算出每个i的prev greater的位置。那么在所有与nums[i]相同的元素里,我们只会挑选位置在prevGreater[i]之后的那些,都可以作为subarray的首元素。 From db864345846e48391f0930a99d424e1f957164e9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 19:27:24 -0700 Subject: [PATCH 2484/2729] Update 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp --- ...-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp index 9c528e2e9..413f3da6b 100644 --- a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp @@ -20,7 +20,7 @@ class Solution { for (int i=0; i Date: Sat, 20 Apr 2024 19:29:22 -0700 Subject: [PATCH 2485/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md index 016dcbbc4..081b59150 100644 --- a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md @@ -1,5 +1,5 @@ ### 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum -我们考虑以i为结尾的subarray,那么该subarray的首位置必然是在i之前、且数值与nums[i]相同的那些元素。这些我们是容易准备好的。 +我们考虑以i为结尾的subarray,那么该subarray的首位置必然是在i之前、且数值与nums[i]相同的那些元素。这些我们是容易用hash准备好的。 同时,因为要求nums[i]是subarray里最大的元素,所以首元素的位置不能太靠前,越靠前的话就越容易包含进大于nums[i]的数。所以我们提前用单调栈计算出每个i的prev greater的位置。那么在所有与nums[i]相同的元素里,我们只会挑选位置在prevGreater[i]之后的那些,都可以作为subarray的首元素。 From ce94d2e3f23c371051e5a80687433f5ae2819ae9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:23:43 -0700 Subject: [PATCH 2486/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md index 081b59150..97e30b5cf 100644 --- a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md @@ -2,4 +2,4 @@ 我们考虑以i为结尾的subarray,那么该subarray的首位置必然是在i之前、且数值与nums[i]相同的那些元素。这些我们是容易用hash准备好的。 -同时,因为要求nums[i]是subarray里最大的元素,所以首元素的位置不能太靠前,越靠前的话就越容易包含进大于nums[i]的数。所以我们提前用单调栈计算出每个i的prev greater的位置。那么在所有与nums[i]相同的元素里,我们只会挑选位置在prevGreater[i]之后的那些,都可以作为subarray的首元素。 +同时,因为要求nums[i]是subarray里最大的元素,所以首元素的位置不能太靠前,越靠前的话subarray就越容易包含大于nums[i]的数。所以我们提前用单调栈计算出每个`i`的prev greater的位置。那么在所有与nums[i]相同的元素里,我们只会挑选位置在prevGreater[i]之后的那些,都可以作为subarray的首元素。 From 2d1b592e06533245b9a0196945df11169c5a50e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:29:11 -0700 Subject: [PATCH 2487/2729] Update 2359.Find-Closest-Node-to-Given-Two-Nodes.cpp --- .../2359.Find-Closest-Node-to-Given-Two-Nodes.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp b/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp index 7acab1c41..aea7c61a8 100644 --- a/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp +++ b/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp @@ -34,8 +34,6 @@ class Solution { ret = max(dist1[i], dist2[i]); ans = i; } - else if (max(dist1[i], dist2[i]) == ret) - ans = min(ans, i); } } if (ret!=INT_MAX) From 0ee91bf1b11ae4cb061c026b8b2c8a51b87ffcdd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:45:02 -0700 Subject: [PATCH 2488/2729] Create 3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp --- ...nimum-Time-to-Visit-Disappearing-Nodes.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp diff --git a/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp b/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp new file mode 100644 index 000000000..e256c94f3 --- /dev/null +++ b/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp @@ -0,0 +1,35 @@ +using PII = pair; +class Solution { + vectornext[50005]; +public: + vector minimumTime(int n, vector>& edges, vector& disappear) + { + vectorrets(n, -1); + + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], w = edge[2]; + next[a].push_back({b,w}); + next[b].push_back({a,w}); + } + + priority_queue, greater<>>pq; + pq.push({0, 0}); + while (!pq.empty()) + { + auto [dist, cur] = pq.top(); + pq.pop(); + if (rets[cur]!=-1) continue; + rets[cur] = dist; + + for (auto [nxt, len]: next[cur]) + { + if (rets[nxt]!=-1) continue; + if (dist + len >= disappear[nxt]) continue; + pq.push({dist + len, nxt}); + } + } + + return rets; + } +}; From 11bc613a6e5d3a65af829397e91c9692a7597272 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:45:37 -0700 Subject: [PATCH 2489/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 531e6eddb..db291974e 100644 --- a/Readme.md +++ b/Readme.md @@ -422,7 +422,7 @@ [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) -[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) +[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) [3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum](https://github.com/wisdompeak/LeetCode/tree/master/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum) (M) * ``monotonic stack: other usages`` [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) @@ -1156,6 +1156,7 @@ * ``Dijkstra`` [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) +[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From c467f47891dcc136ad6f47324defcf54807d230a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:48:42 -0700 Subject: [PATCH 2490/2729] Create Readme.md --- .../3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md diff --git a/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md b/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md new file mode 100644 index 000000000..e5b0c07c6 --- /dev/null +++ b/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md @@ -0,0 +1,5 @@ +### 3112.Minimum-Time-to-Visit-Disappearing-Nodes + +非常典型的单源最短路径问题,使用Dijkstra算法毋庸置疑。 + +我们只需要在Dikstra更新每个节点的最短时间时,判断一下此时的最短时间和该点disappear的时间。如果时间disappear更早,那么说明这个点无法出现在任何路径上,将其略过不加入Dijkstra的后续计算。 From e4b155b8b3b3665a2e6d1087d9f41c58f65dede5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 21:13:21 -0700 Subject: [PATCH 2491/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index db291974e..1a8ca00ad 100644 --- a/Readme.md +++ b/Readme.md @@ -1149,13 +1149,13 @@ [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) -[2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) [3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II) (H) * ``Dijkstra`` [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) +[2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) [3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) From 2cd3a0544e63c5b81b3af44f044ddcc193265ba1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 21:17:47 -0700 Subject: [PATCH 2492/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 1a8ca00ad..e714adb26 100644 --- a/Readme.md +++ b/Readme.md @@ -633,7 +633,6 @@ [2503.Maximum-Number-of-Points-From-Grid-Queries](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries) (H-) [505.The-Maze-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/505.The-Maze-II) (H-) [499.The-Maze-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/499.The-Maze-III) (H) -[787.CSorted_Containerest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.CSorted_Containerest-Flights-Within-K-Stops) (H) [882.Reachable-Nodes-In-Subdivided-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/882.Reachable-Nodes-In-Subdivided-Graph ) (H) [1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) [1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid) (H) @@ -1152,7 +1151,8 @@ [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) [3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II) (H) -* ``Dijkstra`` +* ``Dijkstra`` +[787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) From 09e5d3a43165c7c20b13d680e555d4e6d920d979 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 21:18:39 -0700 Subject: [PATCH 2493/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index e714adb26..3daa2f06f 100644 --- a/Readme.md +++ b/Readme.md @@ -1151,7 +1151,7 @@ [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) [3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II) (H) -* ``Dijkstra`` +* ``Dijkstra`` [787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) From f7e72c1f5592e71e3351177a0600dccb9ce0a9b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 09:49:43 -0700 Subject: [PATCH 2494/2729] Create 3123.Find-Edges-in-Shortest-Paths.cpp --- .../3123.Find-Edges-in-Shortest-Paths.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp diff --git a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp new file mode 100644 index 000000000..3216877f4 --- /dev/null +++ b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp @@ -0,0 +1,60 @@ +using PII = pair; + +class Solution { + vector>next[50005]; +public: + vector findAnswer(int n, vector>& edges) + { + int m = edges.size(); + vectorrets(m, false); + + for (int i=0; i, greater<>>pq; + + pq.push({0, 0}); + vectord1(n, INT_MAX/2); + while (!pq.empty()) + { + auto [dist, cur] = pq.top(); + pq.pop(); + if (d1[cur]!= INT_MAX/2) continue; + d1[cur] = dist; + + for (auto [nxt, len, idx]: next[cur]) + { + if (d1[nxt]!= INT_MAX/2) continue; + pq.push({dist + len, nxt}); + } + } + + while (!pq.empty()) pq.pop(); + pq.push({0, n-1}); + vectord2(n, INT_MAX/2); + while (!pq.empty()) + { + auto [dist, cur] = pq.top(); + pq.pop(); + if (d2[cur]!= INT_MAX/2) continue; + d2[cur] = dist; + + for (auto [nxt, len, idx]: next[cur]) + { + if (d2[nxt]!= INT_MAX/2) continue; + pq.push({dist + len, nxt}); + + if (dist+len + d1[nxt] == d1[n-1]) + rets[idx] = true; + } + } + + return rets; + + } +}; From 132fe3d1725c8577bcc1b50dae6da58aba222692 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 09:50:10 -0700 Subject: [PATCH 2495/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3daa2f06f..521a64352 100644 --- a/Readme.md +++ b/Readme.md @@ -1156,7 +1156,8 @@ [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) -[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) +[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) +[3123.Find-Edges-in-Shortest-Paths])(https://github.com/wisdompeak/LeetCode/tree/master/Graph/3123.Find-Edges-in-Shortest-Paths) (H-) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From 4a937a74c2726bd8d20b5561623a6e7fc0bfd6f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 09:58:09 -0700 Subject: [PATCH 2496/2729] Create Readme.md --- Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md diff --git a/Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md b/Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md new file mode 100644 index 000000000..24b24e353 --- /dev/null +++ b/Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md @@ -0,0 +1,10 @@ +### 3123.Find-Edges-in-Shortest-Paths + +本题需要去除图中不在起点与终点最短路径上的边。 + +首先,我最容易想到的是“去除图中不在起点与终点最短路径上的点”。这个只需要跑两遍Dijkstra,求出所有点到起点的最短距离d1,和到终点的最短距离d2.如果`d1[i]+d2[i]!=d1[n-1]`,那么点`i`一定不在起讫点的最短路径上,称作“冗余点”;反之叫“关键点”。 + +那么如果判定“冗余边”和“关键边”呢?关键边的两个端点a和b必须都是关键点,并且自身的边一定要在最短路径上,显然我们可以通过如下判定即可。 +``` +d1[a] + w + d2[b] == d1[n-1] +``` From 157c95cdc3aec941041cfb9c8271031a54e8f57f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 10:01:18 -0700 Subject: [PATCH 2497/2729] Update 3123.Find-Edges-in-Shortest-Paths.cpp --- .../3123.Find-Edges-in-Shortest-Paths.cpp | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp index 3216877f4..3e94fe001 100644 --- a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp +++ b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp @@ -1,60 +1,63 @@ using PII = pair; class Solution { - vector>next[50005]; + vectornext[50005]; public: vector findAnswer(int n, vector>& edges) { int m = edges.size(); vectorrets(m, false); - for (int i=0; i, greater<>>pq; pq.push({0, 0}); - vectord1(n, INT_MAX/2); + vectord1(n, INT_MAX/3); while (!pq.empty()) { auto [dist, cur] = pq.top(); pq.pop(); - if (d1[cur]!= INT_MAX/2) continue; + if (d1[cur]!= INT_MAX/3) continue; d1[cur] = dist; - for (auto [nxt, len, idx]: next[cur]) + for (auto [nxt, len]: next[cur]) { - if (d1[nxt]!= INT_MAX/2) continue; + if (d1[nxt]!= INT_MAX/3) continue; pq.push({dist + len, nxt}); } } while (!pq.empty()) pq.pop(); pq.push({0, n-1}); - vectord2(n, INT_MAX/2); + vectord2(n, INT_MAX/3); while (!pq.empty()) { auto [dist, cur] = pq.top(); pq.pop(); - if (d2[cur]!= INT_MAX/2) continue; + if (d2[cur]!= INT_MAX/3) continue; d2[cur] = dist; - for (auto [nxt, len, idx]: next[cur]) + for (auto [nxt, len]: next[cur]) { - if (d2[nxt]!= INT_MAX/2) continue; + if (d2[nxt]!= INT_MAX/3) continue; pq.push({dist + len, nxt}); - - if (dist+len + d1[nxt] == d1[n-1]) - rets[idx] = true; } } + + for (int i=0; i Date: Sun, 21 Apr 2024 10:50:16 -0700 Subject: [PATCH 2498/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 521a64352..d84e8c4fd 100644 --- a/Readme.md +++ b/Readme.md @@ -1156,8 +1156,8 @@ [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) -[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) -[3123.Find-Edges-in-Shortest-Paths])(https://github.com/wisdompeak/LeetCode/tree/master/Graph/3123.Find-Edges-in-Shortest-Paths) (H-) +[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) +[3123.Find-Edges-in-Shortest-Paths](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3123.Find-Edges-in-Shortest-Paths) (H-) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From 2c00648bb44125308852e376d371941227f8cacf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:13:29 -0700 Subject: [PATCH 2499/2729] Create 3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp --- ...er-of-Operations-to-Satisfy-Conditions.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp diff --git a/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp b/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp new file mode 100644 index 000000000..c3cff6617 --- /dev/null +++ b/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp @@ -0,0 +1,36 @@ +class Solution { + int dp[1005][10]; +public: + int minimumOperations(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + + for (int i=0; i Date: Sun, 21 Apr 2024 11:15:25 -0700 Subject: [PATCH 2500/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d84e8c4fd..e63b2a559 100644 --- a/Readme.md +++ b/Readme.md @@ -785,6 +785,7 @@ [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) [2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) [2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) +[3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp) (M+) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From 000275646e7f0d652552f5e0c72a9cba38d5869f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:23:05 -0700 Subject: [PATCH 2501/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/Readme.md diff --git a/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/Readme.md b/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/Readme.md new file mode 100644 index 000000000..69d2da794 --- /dev/null +++ b/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/Readme.md @@ -0,0 +1,9 @@ +### 3122.Minimum-Number-of-Operations-to-Satisfy-Conditions + +考虑到填充数值的类型是有0-9,所以可以枚举每一列的填充可能。令dp[i][p]表示在前`i`列里填充,并且第`i`列填充数字`p`的最小操作。 + +转移方程非常直观,我们只需要在dp[i-1][q]且`q!=p`的状态里选择一个最小的即可。然后加上将第i列全部填充为p的操作。 + +所以总的时间复杂度是`n*10*10`。 + +事实上,对于每一列而言,我们不需要全部枚举0-9的填充可能。我们只需要考虑三种可能:填充为该列频次最多的元素、填充为该列频次第二多的元素、填充为该列频次第三多的元素。因为这三种方式中的某一种,就一定可以满足不与左右两列冲突的条件。而将该列填充为其他的元素,需要的操作肯定更高。 From 11fed699ccb3721b049ec01e6ee1670f74e08726 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:27:22 -0700 Subject: [PATCH 2502/2729] Update 3123.Find-Edges-in-Shortest-Paths.cpp --- .../3123.Find-Edges-in-Shortest-Paths.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp index 3e94fe001..c1b10ddd1 100644 --- a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp +++ b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp @@ -33,7 +33,6 @@ class Solution { } } - while (!pq.empty()) pq.pop(); pq.push({0, n-1}); vectord2(n, INT_MAX/3); while (!pq.empty()) From 4b326824b8329ef870b3c4d278b6706b59041e18 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:55:07 -0700 Subject: [PATCH 2503/2729] Create 3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp --- ...t-With-Single-Denomination-Combination.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp diff --git a/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp new file mode 100644 index 000000000..462b782ea --- /dev/null +++ b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp @@ -0,0 +1,51 @@ +using LL = long long; +class Solution { +public: + long long findKthSmallest(vector& coins, int k) + { + LL left = 1, right = 51e9; + while (left < right) + { + LL mid = left+(right-left)/2; + if (isOK(coins, mid, k)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(vector& coins, LL A, int t) + { + int m = coins.size(); + + int sign = 1; + LL ret = 0; + + for (int k=1; k<=m; k++) + { + LL sum = 0; + int state = (1 << k) - 1; + while (state < (1 << m)) + { + LL product = 1; + for (int i=0; i>i)&1) + product = product * coins[i] / gcd(product, coins[i]); + } + sum += A / product; + + int c = state & - state; + int r = state + c; + state = (((r ^ state) >> 2) / c) | r; + } + + ret += sum * sign; + sign *= -1; + } + + return ret >= t; + + } +}; From 7e370a640ce1ed6168662ff80ad7f41e6574ee4f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:56:38 -0700 Subject: [PATCH 2504/2729] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e63b2a559..cfcaae5eb 100644 --- a/Readme.md +++ b/Readme.md @@ -157,7 +157,8 @@ [793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) [1201.Ugly-Number-III](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1201.Ugly-Number-III) (H-) [1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) -[2387.Median-of-a-Row-Wise-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix) (H-) +[2387.Median-of-a-Row-Wise-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix) (H-) +[3116.Kth-Smallest-Amount-With-Single-Denomination-Combination](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination) (H) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) @@ -977,7 +978,8 @@ [1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) (M) [2151.Maximum-Good-People-Based-on-Statements](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements) (M+) -[2397.Maximum-Rows-Covered-by-Columns](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns) (M) +[2397.Maximum-Rows-Covered-by-Columns](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns) (M) +[3116.Kth-Smallest-Amount-With-Single-Denomination-Combination](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination) (H) * ``Meet in the Middle`` [1755.Closest-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1755.Closest-Subsequence-Sum) (H) [2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) From f82425944446620b575cea777cc68fa552ee4958 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 22 Apr 2024 01:25:04 -0700 Subject: [PATCH 2505/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/Readme.md diff --git a/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/Readme.md b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/Readme.md new file mode 100644 index 000000000..78f967265 --- /dev/null +++ b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/Readme.md @@ -0,0 +1,9 @@ +### 3116.Kth-Smallest-Amount-With-Single-Denomination-Combination + +本题就是求第k个能被coins里任意一个元素整除的自然数。 + +因为我们无法枚举每个符合条件的自然数直至第k个,我们只能用二分搜值的框架。猜测一个M,计算M以内符合条件的自然数有多少,多了就降低M,少了就抬升M,直至找到恰好的M。 + +那么如何计算M以内、能被coins里任意一个元素整除的自然数的个数呢?显然我们会用容斥原理。`能被任意一个元素整除的个数 = sum(能被每一个元素整除的个数) - sum(能被每两个元素同时整除的个数) + sum(能被每三个元素同时整除的个数) - sum(能被每四个元素同时整除的个数) + ...` + +举个例子,能被a,b,c三个元素同时整除的个数,是 `M / lcm(a,b,c)`,其中lcm是三者的最小公倍数。如果想在m个元素里,枚举任意三个元素的组合,那么我们会用gospher's hack,高效枚举中一个长度为m的二进制数里含有三个bit 1的mask。 From 541f07786574cba327c7986510b3ed73a203662f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 22 Apr 2024 20:58:13 -0700 Subject: [PATCH 2506/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cfcaae5eb..429771696 100644 --- a/Readme.md +++ b/Readme.md @@ -786,7 +786,7 @@ [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) [2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) [2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) -[3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp) (M+) +[3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions) (M+) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From c6729b5faa855fd67544ee43403156d88e0414f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:10:52 -0700 Subject: [PATCH 2507/2729] Create 3133.Minimum-Array-End.cpp --- .../3133.Minimum-Array-End.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp diff --git a/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp b/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp new file mode 100644 index 000000000..62c8498f4 --- /dev/null +++ b/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp @@ -0,0 +1,44 @@ +using LL = long long; +class Solution { +public: + long long minEnd(int n, int x) + { + LL m = n-1; + vectorarr; + while (m>0) + { + arr.push_back(m%2); + m/=2; + } + + vectorbits; + while (x>0) + { + bits.push_back(x%2); + x/=2; + } + + int j = 0; + for (int i=0; i=0; j--) + ret = ret*2+bits[j]; + + return ret; + + } +}; From b469bfdbb3952634832d0f7c4121d3922325afa2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:11:27 -0700 Subject: [PATCH 2508/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 429771696..292cb15a1 100644 --- a/Readme.md +++ b/Readme.md @@ -959,6 +959,7 @@ [2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) [2802.Find-The-K-th-Lucky-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number) (M+) [2992.Number-of-Self-Divisible-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations) (M+) +[3133.Minimum-Array-End](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3133.Minimum-Array-End) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 8ffe0c2d7416edc9972e7c427631c060ebbdd520 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:41:38 -0700 Subject: [PATCH 2509/2729] Create Readme.md --- Bit_Manipulation/3133.Minimum-Array-End/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Bit_Manipulation/3133.Minimum-Array-End/Readme.md diff --git a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md new file mode 100644 index 000000000..b3eaa9d1c --- /dev/null +++ b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md @@ -0,0 +1,7 @@ +### 3133.Minimum-Array-End + +本题要求构造一个严格递增的、长度为n的序列,使得其bitwise AND的结果是x。问序列的最大元素可以是多少。 + +因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。同时为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。 + +总结算法:我们将x进行二进制分解。保持那些属于1的bit位不变。这样我们可以构造长度为n的最小序列:0,1,2,...,n-1。其中将最大元素n-1进行二进制拆解,但是填充在x的那些属于0的bit位上。这样就得到了答案。 From 5969426e9ba82813e1c34296c908b8123e6dbbc9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:42:19 -0700 Subject: [PATCH 2510/2729] Update Readme.md --- Bit_Manipulation/3133.Minimum-Array-End/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md index b3eaa9d1c..eb2b37bd9 100644 --- a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md +++ b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md @@ -2,6 +2,6 @@ 本题要求构造一个严格递增的、长度为n的序列,使得其bitwise AND的结果是x。问序列的最大元素可以是多少。 -因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。同时为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。 +因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。同时为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。我们唯一能自由操作的就是那些属于0的bit位。 总结算法:我们将x进行二进制分解。保持那些属于1的bit位不变。这样我们可以构造长度为n的最小序列:0,1,2,...,n-1。其中将最大元素n-1进行二进制拆解,但是填充在x的那些属于0的bit位上。这样就得到了答案。 From c128d4b32bdc0a1b861d63421cf08095b8e89b95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:45:18 -0700 Subject: [PATCH 2511/2729] Create 3134.Find-the-Median-of-the-Uniqueness-Array.cpp --- ...ind-the-Median-of-the-Uniqueness-Array.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp diff --git a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp new file mode 100644 index 000000000..726c7c48a --- /dev/null +++ b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp @@ -0,0 +1,47 @@ +using LL = long long; +class Solution { +public: + int medianOfUniquenessArray(vector& nums) + { + int n = nums.size(); + int left = 1, right = n; + while (left < right) + { + int mid = left + (right-left)/2; + if (isOK(nums, mid)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(vector&nums, int k) + { + LL n = nums.size(); + LL total = n*(n-1)/2+n; + return atMostK(nums, k) >= (total+1)/2; + } + + LL atMostK(vector& A, int K) + { + unordered_mapMap; + LL count=0; + LL i = 0; + + for (LL j=0; jK) + { + Map[A[i]]--; + if (Map[A[i]]==0) + Map.erase(A[i]); + i++; + } + count+= j-i+1; + } + return count; + } +}; From 223b43ce34fc931f1a6e6695940df620599f6f46 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:47:29 -0700 Subject: [PATCH 2512/2729] Update 3133.Minimum-Array-End.cpp --- .../3133.Minimum-Array-End.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp b/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp index 62c8498f4..c9f7746bb 100644 --- a/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp +++ b/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp @@ -4,10 +4,10 @@ class Solution { long long minEnd(int n, int x) { LL m = n-1; - vectorarr; + vectornum; while (m>0) { - arr.push_back(m%2); + num.push_back(m%2); m/=2; } @@ -22,15 +22,15 @@ class Solution { for (int i=0; i Date: Sun, 28 Apr 2024 12:28:50 -0700 Subject: [PATCH 2513/2729] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 292cb15a1..ff85303a0 100644 --- a/Readme.md +++ b/Readme.md @@ -61,7 +61,8 @@ [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) [159.Longest-Substring-with-At-Most-Two-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/159.Longest-Substring-with-At-Most-Two-Distinct-Characters)(H-) [340.Longest-Substring-with-At-Most-K-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/340.Longest-Substring-with-At-Most-K-Distinct-Characters) (H) -[992.Subarrays-with-K-Different-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/992.Subarrays-with-K-Different-Integers) (H-) +[992.Subarrays-with-K-Different-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/992.Subarrays-with-K-Different-Integers) (H-) +[3134.Find-the-Median-of-the-Uniqueness-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array) (H-) [2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K) (M) [2537.Count-the-Number-of-Good-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays) (M+) * ``Two pointers for two sequences`` @@ -159,6 +160,7 @@ [1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) [2387.Median-of-a-Row-Wise-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix) (H-) [3116.Kth-Smallest-Amount-With-Single-Denomination-Combination](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination) (H) +[3134.Find-the-Median-of-the-Uniqueness-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array) (H-) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From 5fd1db9041be15bebd02e99606fa27bb9fe9bc71 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 12:38:31 -0700 Subject: [PATCH 2514/2729] Update Readme.md --- Bit_Manipulation/3133.Minimum-Array-End/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md index eb2b37bd9..e5a924d50 100644 --- a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md +++ b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md @@ -2,6 +2,8 @@ 本题要求构造一个严格递增的、长度为n的序列,使得其bitwise AND的结果是x。问序列的最大元素可以是多少。 -因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。同时为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。我们唯一能自由操作的就是那些属于0的bit位。 +因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以首元素不可能比x更小,否则总的bitwise AND不可能是x。最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。 + +为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。我们唯一能自由操作的就是那些属于0的bit位。 总结算法:我们将x进行二进制分解。保持那些属于1的bit位不变。这样我们可以构造长度为n的最小序列:0,1,2,...,n-1。其中将最大元素n-1进行二进制拆解,但是填充在x的那些属于0的bit位上。这样就得到了答案。 From 335e1433453fd6604aff83b885afa579b2b72bb8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 17:29:39 -0700 Subject: [PATCH 2515/2729] Create Readme.md --- .../3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md diff --git a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md new file mode 100644 index 000000000..63912e8a2 --- /dev/null +++ b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md @@ -0,0 +1,7 @@ +### 3134.Find-the-Median-of-the-Uniqueness-Array + +数组的subarray总数有`N = n(n-1)/2+n`个,直接求所有subarray的中位数肯定不现实。此题几乎肯定需要用二分搜值来解。 + +假设一个数字x,怎么判定它是否是所有subarray的distinct number的中位数,也就是第N/2个呢?显然,我们只需要判定distinct number大于等于x的subarray是否有N/2个即可。有的话,我们就往小调整,否则就往大调整。 + +求“distinct number大于等于x的subarray”个数,可以用滑动窗口来解决。固定左端点,移动右端点到恰好包含x个distinct number,那么右端点从此时的位置到数组末尾都可以构成valid subarray. From 3d62847c35a2ddd20e251e3907289fe4c45e2fc4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 18:32:37 -0700 Subject: [PATCH 2516/2729] Update Readme.md --- .../3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md index 63912e8a2..205179dc2 100644 --- a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md +++ b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md @@ -2,6 +2,6 @@ 数组的subarray总数有`N = n(n-1)/2+n`个,直接求所有subarray的中位数肯定不现实。此题几乎肯定需要用二分搜值来解。 -假设一个数字x,怎么判定它是否是所有subarray的distinct number的中位数,也就是第N/2个呢?显然,我们只需要判定distinct number大于等于x的subarray是否有N/2个即可。有的话,我们就往小调整,否则就往大调整。 +假设一个数字K,怎么判定它是否是所有subarray的distinct number的中位数,也就是第N/2个呢?显然,我们只需要判定`subarray with at most K distinct number`的个数是否有N/2个即可。有的话,我们就往小调整,否则就往大调整。 -求“distinct number大于等于x的subarray”个数,可以用滑动窗口来解决。固定左端点,移动右端点到恰好包含x个distinct number,那么右端点从此时的位置到数组末尾都可以构成valid subarray. +求“subarray with at most K distinct number”个数,可以用滑动窗口来解决。类似于340,992. From 668ce0d101f22343f52b3d0899ba72fa9d7f6ffd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 18:34:19 -0700 Subject: [PATCH 2517/2729] Update 3134.Find-the-Median-of-the-Uniqueness-Array.cpp --- ...3134.Find-the-Median-of-the-Uniqueness-Array.cpp | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp index 726c7c48a..f3305cbed 100644 --- a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp +++ b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp @@ -3,12 +3,14 @@ class Solution { public: int medianOfUniquenessArray(vector& nums) { - int n = nums.size(); + LL n = nums.size(); + LL total = n*(n-1)/2+n; + LL half = (total+1)/2; int left = 1, right = n; while (left < right) { int mid = left + (right-left)/2; - if (isOK(nums, mid)) + if (atMostK(nums, mid)>=half) right = mid; else left = mid+1; @@ -16,13 +18,6 @@ class Solution { return left; } - bool isOK(vector&nums, int k) - { - LL n = nums.size(); - LL total = n*(n-1)/2+n; - return atMostK(nums, k) >= (total+1)/2; - } - LL atMostK(vector& A, int K) { unordered_mapMap; From 5124a2efdf2e1fdf2f15bca0549cf1c0e7567f49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 20:56:10 -0700 Subject: [PATCH 2518/2729] Create 3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp --- ...ll-Possible-Stable-Binary-Arrays-II_v2.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp new file mode 100644 index 000000000..3face3ad0 --- /dev/null +++ b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { + LL dp0[205][205]; + LL dp1[205][205]; + LL presum0[205][205]; + LL presum1[205][205]; + LL M = 1e9+7; +public: + int numberOfStableArrays(int zero, int one, int limit) + { + dp0[0][0]=1; + dp1[0][0]=1; + presum0[0][0] = 1; + presum1[0][0] = 1; + + for (int i=0; i<=zero; i++) + for (int j=0; j<=one; j++) + { + if (i==0 && j==0) continue; + + // 1<=k<=min(i,limit) + dp0[i][j] = (i-1<0?0:presum1[j][i-1]) - (i-min(i,limit)-1<0?0:presum1[j][i-min(i,limit)-1]); + + + // 1<=k<=min(j,limit) + dp1[i][j] = (j-1<0?0:presum0[i][j-1]) - (j-min(j,limit)-1<0?0:presum0[i][j-min(j,limit)-1]); + + dp0[i][j] = (dp0[i][j] + M) %M; + dp1[i][j] = (dp1[i][j] + M) %M; + + presum0[i][j] = (j<1?0:presum0[i][j-1]) + dp0[i][j]; + presum1[j][i] = (i<1?0:presum1[j][i-1]) + dp1[i][j]; + + presum0[i][j] %= M; + presum1[j][i] %= M; + } + + return (dp0[zero][one]+dp1[zero][one]) % M; + } +}; From fb33de18dd23f431aa2a194adcf214000929e7d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 20:57:16 -0700 Subject: [PATCH 2519/2729] Create 3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp --- ...ll-Possible-Stable-Binary-Arrays-II_v1.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp new file mode 100644 index 000000000..fe7cdde55 --- /dev/null +++ b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp @@ -0,0 +1,28 @@ +using LL = long long; +class Solution { + LL dp0[205][205]; + LL dp1[205][205]; + LL M = 1e9+7; +public: + int numberOfStableArrays(int zero, int one, int limit) + { + dp0[0][0]=1; + dp1[0][0]=1; + + for (int i=0; i<=zero; i++) + for (int j=0; j<=one; j++) + { + if (i==0 && j==0) continue; + + for (int k=1; k<=limit; k++) + { + if (i-k>=0) dp0[i][j] += dp1[i-k][j]; + if (j-k>=0) dp1[i][j] += dp0[i][j-k]; + dp0[i][j] %= M; + dp1[i][j] %= M; + } + } + + return (dp0[zero][one]+dp1[zero][one]) % M; + } +}; From 6f57651384b68207a51fa71845c85d4f830a2f2c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 20:59:03 -0700 Subject: [PATCH 2520/2729] Delete Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp --- ...ll-Possible-Stable-Binary-Arrays-II_v1.cpp | 28 ------------------- 1 file changed, 28 deletions(-) delete mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp deleted file mode 100644 index fe7cdde55..000000000 --- a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp +++ /dev/null @@ -1,28 +0,0 @@ -using LL = long long; -class Solution { - LL dp0[205][205]; - LL dp1[205][205]; - LL M = 1e9+7; -public: - int numberOfStableArrays(int zero, int one, int limit) - { - dp0[0][0]=1; - dp1[0][0]=1; - - for (int i=0; i<=zero; i++) - for (int j=0; j<=one; j++) - { - if (i==0 && j==0) continue; - - for (int k=1; k<=limit; k++) - { - if (i-k>=0) dp0[i][j] += dp1[i-k][j]; - if (j-k>=0) dp1[i][j] += dp0[i][j-k]; - dp0[i][j] %= M; - dp1[i][j] %= M; - } - } - - return (dp0[zero][one]+dp1[zero][one]) % M; - } -}; From 4ffb1e69f9ac5c86641e26f33633adbec8099005 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 20:59:24 -0700 Subject: [PATCH 2521/2729] Create 3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp --- ...ll-Possible-Stable-Binary-Arrays-II_v1.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp new file mode 100644 index 000000000..fe7cdde55 --- /dev/null +++ b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp @@ -0,0 +1,28 @@ +using LL = long long; +class Solution { + LL dp0[205][205]; + LL dp1[205][205]; + LL M = 1e9+7; +public: + int numberOfStableArrays(int zero, int one, int limit) + { + dp0[0][0]=1; + dp1[0][0]=1; + + for (int i=0; i<=zero; i++) + for (int j=0; j<=one; j++) + { + if (i==0 && j==0) continue; + + for (int k=1; k<=limit; k++) + { + if (i-k>=0) dp0[i][j] += dp1[i-k][j]; + if (j-k>=0) dp1[i][j] += dp0[i][j-k]; + dp0[i][j] %= M; + dp1[i][j] %= M; + } + } + + return (dp0[zero][one]+dp1[zero][one]) % M; + } +}; From 537ef0f509bafcac0b5cb1fbdff4c1e4d6f7a238 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 21:01:04 -0700 Subject: [PATCH 2522/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index ff85303a0..0e787b8eb 100644 --- a/Readme.md +++ b/Readme.md @@ -946,6 +946,8 @@ [152.Maximum-Product-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/152.Maximum-Product-Subarray) (M+) [2272.Substring-With-Largest-Variance](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2272.Substring-With-Largest-Variance) (H-) [2321.Maximum-Score-Of-Spliced-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array) (H-) +* ``前缀和辅助`` +[3130.Find-All-Possible-Stable-Binary-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II) (H) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From 2a0ffc14a0bbc11c099e39af84d19ac82cdd2032 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 23:48:56 -0700 Subject: [PATCH 2523/2729] Create Readme.md --- .../Readme.md | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/Readme.md diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/Readme.md b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/Readme.md new file mode 100644 index 000000000..69c9a9c37 --- /dev/null +++ b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/Readme.md @@ -0,0 +1,40 @@ +### 3130.Find-All-Possible-Stable-Binary-Arrays-II + +#### 解法1: +对于每一步决策而言,我们需要考虑的因素无非就是:已经用了几个0,已经用了几个1,当前最后一步是0还是1. 事实上,我们就用这些状态作为变量,即可定义动态规划。令dp0[i][j]表示已经用了i个0、j个1,并且最后一个数字填写的是0时,可以构造的stable binary array的个数。类似地,令dp1[i][j]表示已经用了i个0、j个1,并且最后一个数字填写的是1时,可以构造的stable binary array的个数。 + +如何计算dp0[i][j]呢?因为最后一步填0,且唯一的限制就是不能有连续超过limit+1个0,所以它之前最后一次出现的1,必须在`i+j-limit, i+j-limit+1, ..., i+j-1`中间的一处。所以就有 +``` +dp0[i][j] = dp1[i-limit][j] + dp1[i-limit+1][j] + ... + dp1[i-1][j] +``` +同理,dp1[i][j]的前趋状态取决于最后一次出现0的位置, +``` +dp1[i][j] = dp0[i][j-limit] + dp1[i][j-limit+1] + ... + dp1[i][j-1] +``` +综上,我们用三层循环就可以求出dp0和dp1。最终答案就是将所有的0和1用完,但结尾的元素可以是0或1,即`dp0[zero][one]+dp1[zero][one]`. +```cpp +for (int i=0; i<=zero; i++) + for (int j=0; j<=one; j++) + { + for (int k=1; k<=limit; k++) + { + if (i>=k) dp0[i][j] += dp1[i-k][j]; + if (j>=k) dp1[i][j] += dp0[i][j-k]; + } + } +``` + +#### 解法2: +注意到上述解法的最内层循环,其实dp0[i][j]是累加了dp1[...][j]的一段区间,区间范围是[i-min(i,limit), i-1]. 同理,dp1[i][j]是累加了dp0[i][...]的一段区间,区间范围是[j-min(j,limit), j-1]. 为了节省这层循环,我们想到可以用前缀和。 + +令`presum0[i][...]`表示`dp0[i][...]`的前缀和,`presum1[j][...]`表示`dp1[...][j]`的前缀和。于是区间之和就可以表示成前缀和之差: +``` +dp0[i][j] = presum1[j][i-1] - presum1[j][i-min(i,limit)-1] +dp1[i][j] = presum0[i][j-1] - presum0[i][j-min(j,limit)-1] +``` +用完之后,记得将新算出的dp0[i][j]和dp1[i][j]来更新presum0与presum1 +``` +presum0[i][j] = presum0[i][j-1] + dp0[i][j] +presum1[j][i] = presum1[j][i-1] + dp1[i][j] +``` +就这样在i与j的双层循环里,不断滚动更新dp0[i][j]、dp1[i][j]、presum0[i][j]与presum1[j][i]. From cbb096314d8b9f6747f01c9b119aacd7d8c4229f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 May 2024 16:55:01 -0700 Subject: [PATCH 2524/2729] Update 3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp --- ...t-With-Single-Denomination-Combination.cpp | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp index 462b782ea..ca17274ca 100644 --- a/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp +++ b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp @@ -7,45 +7,44 @@ class Solution { while (left < right) { LL mid = left+(right-left)/2; - if (isOK(coins, mid, k)) + if (countNumber(mid, coins) >= k) right = mid; else left = mid+1; } return left; } - - bool isOK(vector& coins, LL A, int t) + + LL countNumber(LL M, vector& coins) { int m = coins.size(); - - int sign = 1; + LL ret = 0; - + int sign = 1; + for (int k=1; k<=m; k++) { LL sum = 0; int state = (1 << k) - 1; while (state < (1 << m)) { - LL product = 1; + LL LCM = 1; for (int i=0; i>i)&1) - product = product * coins[i] / gcd(product, coins[i]); + LCM = lcm(LCM, coins[i]); } - sum += A / product; + sum += M / LCM; int c = state & - state; int r = state + c; state = (((r ^ state) >> 2) / c) | r; } - + ret += sum * sign; sign *= -1; } - - return ret >= t; - + + return ret; } }; From 8c0e5b0beea246d45f95792020a7ca34da91f1cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 May 2024 23:19:37 -0700 Subject: [PATCH 2525/2729] Create 3139.Minimum-Cost-to-Equalize-Array.cpp --- .../3139.Minimum-Cost-to-Equalize-Array.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp diff --git a/Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp b/Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp new file mode 100644 index 000000000..3e8fea5c5 --- /dev/null +++ b/Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp @@ -0,0 +1,41 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int minCostToEqualizeArray(vector& nums, int cost1, int cost2) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + if (n<=2) + { + return (LL)(nums[n-1]-nums[0])*cost1%M; + } + + LL total = accumulate(nums.begin(), nums.end(), 0LL); + + cost2 = min(cost1*2, cost2); + int m = nums.back(); + LL ret = LLONG_MAX; + for (int limit = m; limit <= 2*m; limit++) + { + LL diff0 = limit - nums[0]; + LL diff_all = (LL)limit*n - total; + + LL ans; + if (diff0 <= diff_all/2) + { + ans = diff_all/2*cost2 + (diff_all%2==1?cost1:0); + } + else + { + ans = (diff_all - diff0)*cost2 + (diff0 - (diff_all - diff0))*cost1; + } + + ret = min(ret, ans); + } + + return ret%M; + + } +}; From fb1f805ffb51924b0e87f181352d0f574fbb89a8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 May 2024 23:20:09 -0700 Subject: [PATCH 2526/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0e787b8eb..317c0a76b 100644 --- a/Readme.md +++ b/Readme.md @@ -1592,6 +1592,7 @@ [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) +[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/3139.Minimum-Cost-to-Equalize-Array) (H) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From f5494a4713d966bde141cd0e957a4b6bafe4ef92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:09:02 -0700 Subject: [PATCH 2527/2729] Create Readme.md --- Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md diff --git a/Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md b/Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md new file mode 100644 index 000000000..f31f8ec32 --- /dev/null +++ b/Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md @@ -0,0 +1,11 @@ +### 3139.Minimum-Cost-to-Equalize-Array + +首先,我们令cost2=min(cost1*2, cost2),保证使用第二种操作不会比第一种操作更亏。这样变换之后,我们知道应该尽量使用cost2更合算。 + +其次要注意,并不是操作的次数越少,付出的代价就越少。比如说nums=[1,4,4],我们可以使用三次cost1,使得所有元素最终变为4;也可以使用六次cost2,使得最终所有元素变成7. 哪种方案更好,取决于cost1和cost2的大小关系。因此本题的最优策略,不一定是将所有的元素都变成max(nums),而是可能一个很大的数字,我们记做limit。假如limit是已知量,我们如何计算需要用的最小代价呢? + +既然我们需要将所有元素都增至limit,那么将数组排序后,每个元素离目标还差{diff0, diff1, diff2, ...., 0}。记所有的diff之和为`diff_all`。我们容易理解这样一个结论,如果在所有的diff里面存在一个超过`diff_all`一半的绝对多数,那它必然就是diff0. 我们为了尽可能多地利用第二种操作,必然是每增加nums0的同时搭配一个增加其他的元素。最终我们会做cost2的操作共`diff_all-diff0`次。剩下来还没增至limit的只是nums0,还差`limit-(diff_all-diff0)`,这就需要用cost1来实现。于是总共的代价为`(diff_all-diff0)*cost2 + (limit-(diff_all-diff0))*cost1`. + +相反,如果{diff}里面不存在一个绝对多数,根据Boyer-Moore Majority Voting的原理,那么我们必然可以持续找到一对pair进行增一操作,且它们来自两个不同的元素。最终直至所有元素都增至limit,或者只差一次增一操作故无法找到pair了。这种情况下,我们的cost2操作了`diff_all/2`次,并且根据diff_all的奇偶性,可能再增加一次cost1的操作。 + + From ac79f231c82447f87e7cf675a15eb65c13b86b36 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:09:29 -0700 Subject: [PATCH 2528/2729] Rename 3139.Minimum-Cost-to-Equalize-Array.cpp to 3139.Minimum-Cost-to-Equalize-Array.cpp --- .../3139.Minimum-Cost-to-Equalize-Array.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Others => Greedy}/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp (100%) diff --git a/Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp b/Greedy/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp similarity index 100% rename from Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp rename to Greedy/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp From fa0ef1be0cc67c66b99180c42688021465f79f0f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:10:11 -0700 Subject: [PATCH 2529/2729] Rename Readme.md to Readme.md --- {Others => Greedy}/3139.Minimum-Cost-to-Equalize-Array/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Others => Greedy}/3139.Minimum-Cost-to-Equalize-Array/Readme.md (100%) diff --git a/Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md b/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md similarity index 100% rename from Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md rename to Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md From 3225ec68fe648761bfd8032db6926d1925661251 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:10:39 -0700 Subject: [PATCH 2530/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 317c0a76b..65540cde9 100644 --- a/Readme.md +++ b/Readme.md @@ -1351,6 +1351,7 @@ * ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) +[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/3139.Minimum-Cost-to-Equalize-Array) (H) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) @@ -1592,7 +1593,6 @@ [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) -[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/3139.Minimum-Cost-to-Equalize-Array) (H) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From d2bedf12d3c0abb4e0aff761c07cb3185ce3138c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:26:27 -0700 Subject: [PATCH 2531/2729] Update Readme.md --- Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md b/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md index f31f8ec32..aadc62ecb 100644 --- a/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md +++ b/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md @@ -2,10 +2,14 @@ 首先,我们令cost2=min(cost1*2, cost2),保证使用第二种操作不会比第一种操作更亏。这样变换之后,我们知道应该尽量使用cost2更合算。 -其次要注意,并不是操作的次数越少,付出的代价就越少。比如说nums=[1,4,4],我们可以使用三次cost1,使得所有元素最终变为4;也可以使用六次cost2,使得最终所有元素变成7. 哪种方案更好,取决于cost1和cost2的大小关系。因此本题的最优策略,不一定是将所有的元素都变成max(nums),而是可能一个很大的数字,我们记做limit。假如limit是已知量,我们如何计算需要用的最小代价呢? +其次要注意,并不是操作的次数越少,付出的代价就越少。比如说nums=[1,4,4],我们可以使用三次cost1,使得所有元素最终变为4;也可以使用六次cost2,使得最终所有元素变成7. 哪种方案更好,取决于cost1和cost2的大小关系。因此本题的最优策略,不一定是将所有的元素都变成max(nums),而是可能一个更大的数字,我们记做limit。假如limit是已知量,我们如何计算需要用的最小代价呢? -既然我们需要将所有元素都增至limit,那么将数组排序后,每个元素离目标还差{diff0, diff1, diff2, ...., 0}。记所有的diff之和为`diff_all`。我们容易理解这样一个结论,如果在所有的diff里面存在一个超过`diff_all`一半的绝对多数,那它必然就是diff0. 我们为了尽可能多地利用第二种操作,必然是每增加nums0的同时搭配一个增加其他的元素。最终我们会做cost2的操作共`diff_all-diff0`次。剩下来还没增至limit的只是nums0,还差`limit-(diff_all-diff0)`,这就需要用cost1来实现。于是总共的代价为`(diff_all-diff0)*cost2 + (limit-(diff_all-diff0))*cost1`. +既然我们需要将所有元素都增至limit,那么将数组排序后,每个元素离目标还差{diff0, diff1, diff2, ...., 0}。记所有的diff之和为`diff_all`。我们容易理解这样一个结论:如果在所有的diff里面存在一个超过`diff_all`一半的绝对多数,那它必然就是diff0. 我们为了尽可能多地利用第二种操作,必然是每增加nums0的同时搭配一个增加其他的元素。最终我们会进行cost2的操作共`diff_all-diff0`次。剩下来还没增至limit的只是nums0,还差`limit-(diff_all-diff0)`,这就需要用cost1来实现。于是总共的代价为`(diff_all-diff0)*cost2 + (limit-(diff_all-diff0))*cost1`. 相反,如果{diff}里面不存在一个绝对多数,根据Boyer-Moore Majority Voting的原理,那么我们必然可以持续找到一对pair进行增一操作,且它们来自两个不同的元素。最终直至所有元素都增至limit,或者只差一次增一操作故无法找到pair了。这种情况下,我们的cost2操作了`diff_all/2`次,并且根据diff_all的奇偶性,可能再增加一次cost1的操作。 +以上我们知道当limit已知时,如何计算最小代价。但是limit该如何确定呢?我们发现,随着limit的增长,{diff}数组整体变大,越来越不可能出现第一种情况。而一旦{diff}进入第二种情况时,就已经将cost2用到了极致(即只会用最多一次cost1),再增长limit就没有意义。那什么时候{diff}会进入第二种情况呢?显然,至少当limit变成`2*max(nums)`,{diff}里面肯定不会出现绝对多数了(当n>=3时):这是因为diff0小于2m,而其他每个diff都大于m。 + +所以我们只需要穷举limit的范围`[m, 2m]`,对于给定的limit我们计算最小代价,全局再取最小即可。考虑到m是1e6,这是可以暴力实现的。 + From be76dfd92295a9456700df3813e29ecdc0335999 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 May 2024 23:29:26 -0700 Subject: [PATCH 2532/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 65540cde9..089b5da30 100644 --- a/Readme.md +++ b/Readme.md @@ -1351,7 +1351,7 @@ * ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) -[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/3139.Minimum-Cost-to-Equalize-Array) (H) +[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3139.Minimum-Cost-to-Equalize-Array) (H) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From df8cd20055f1e3455083669b2e57790ae9b5722a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 May 2024 11:28:25 -0700 Subject: [PATCH 2533/2729] Create 3161.Block-Placement-Queries.cpp --- .../3161.Block-Placement-Queries.cpp | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp diff --git a/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp b/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp new file mode 100644 index 000000000..002d4af55 --- /dev/null +++ b/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp @@ -0,0 +1,148 @@ +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + info = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MIN/2; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + + +class Solution { +public: + vector getResults(vector>& queries) + { + setSet; + int n = min(50000, (int)queries.size()*3)+5; + SegTreeNode* root = new SegTreeNode(0, n, 0); // Set the leaf nodes with initVals. + vectorrets; + + Set.insert(0); + + for (auto q: queries) + { + if (q[0]==1) + { + int x = q[1]; + Set.insert(x); + auto iter = Set.lower_bound(x); + int a = *prev(iter); + root->updateRange(x, x, x-a); + + if (next(iter)!=Set.end()) + { + int b = *next(iter); + root->updateRange(b, b, b-x); + } + } + else + { + int x = q[1], sz = q[2]; + int len = root->queryRange(0, x); + + if (Set.find(x)==Set.end()) + { + auto iter = Set.lower_bound(x); + int a = *prev(iter); + len = max(len, x-a); + } + rets.push_back(len >= sz); + } + } + + return rets; + } +}; From 02f903d3ab2aae8743b2ffb91dc821e71ee250f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 May 2024 11:33:11 -0700 Subject: [PATCH 2534/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 089b5da30..86a12e1ef 100644 --- a/Readme.md +++ b/Readme.md @@ -354,7 +354,8 @@ [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) -[3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) +[3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) +[3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From c3f620b076ef87a0702cb1af5282841c253df805 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 May 2024 12:03:42 -0700 Subject: [PATCH 2535/2729] Create Readme.md --- Segment_Tree/3161.Block-Placement-Queries/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Segment_Tree/3161.Block-Placement-Queries/Readme.md diff --git a/Segment_Tree/3161.Block-Placement-Queries/Readme.md b/Segment_Tree/3161.Block-Placement-Queries/Readme.md new file mode 100644 index 000000000..3f9e3eb41 --- /dev/null +++ b/Segment_Tree/3161.Block-Placement-Queries/Readme.md @@ -0,0 +1,9 @@ +### 3161.Block-Placement-Queries + +本题的第一类query会在数轴上不断插入block,通常情况下每插入一个block,就会隔出两个区间。当遇到第二类query时,我们只需要在[0,x]范围内查看这些区间,找出最大的区间长度,再与sz比较即可。此时我们只需要把每个区间的长度,作为该区间右端点的一个属性,就可以发现就是在[0,x]里求最大值。所以我们容易想到,只需要构造一棵线段树,其中queryRange是求任意一段区间内的最大值。初始状态每个点的值是0. + +更具体的,对于第一类操作,我们在x处插入一个block时,找到它之前已经存在的block位置记做a,之后已经存在的block位置记做b,那么我们只需要对线段树进行单点更新:在x处更新属性x-a,在b处更新数值b-x(前提是b存在)。 + +对于第二类操作,我们只需要在线段树的[0,x]范围里找最大值。特别注意,如果x处本身并没有block,我们还需要考察x之前的那个block(记做a)到x这段空间长度。 + +最后,对于一个x,如果找到它之前和之后的block呢?只需要维护一个有序容器set即可,不断将x插入其中,并且用lower_bound和upper_bound找到其在Set里的前后元素。 From be91e6a66bd4526eeaca8056bc8831fddb77d080 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 02:06:46 -0700 Subject: [PATCH 2536/2729] Update 3161.Block-Placement-Queries.cpp --- .../3161.Block-Placement-Queries.cpp | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp b/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp index 002d4af55..888d5c421 100644 --- a/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp +++ b/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp @@ -105,44 +105,45 @@ class Solution { public: vector getResults(vector>& queries) { + int n = min(50000, (int)queries.size()*3) + 5; + SegTreeNode* root = new SegTreeNode(0, n, 0); + setSet; - int n = min(50000, (int)queries.size()*3)+5; - SegTreeNode* root = new SegTreeNode(0, n, 0); // Set the leaf nodes with initVals. - vectorrets; - Set.insert(0); - - for (auto q: queries) + + vectorrets; + + for (auto q:queries) { if (q[0]==1) { - int x = q[1]; + int x = q[1]; Set.insert(x); - auto iter = Set.lower_bound(x); - int a = *prev(iter); - root->updateRange(x, x, x-a); - + auto iter = Set.find(x); + int a = *prev(iter); + root->updateRange(x,x,x-a); + if (next(iter)!=Set.end()) { int b = *next(iter); - root->updateRange(b, b, b-x); + root->updateRange(b,b,b-x); } } else { int x = q[1], sz = q[2]; int len = root->queryRange(0, x); - + if (Set.find(x)==Set.end()) { auto iter = Set.lower_bound(x); - int a = *prev(iter); + int a = *prev(iter); len = max(len, x-a); - } - rets.push_back(len >= sz); - } + } + rets.push_back(len >= sz); + } } - return rets; + return rets; } }; From b392eb8e7c4c3d89edc3417549b091d6cd6e83e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 13:21:13 -0700 Subject: [PATCH 2537/2729] Create 3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp --- ...Subsequence-With-Non-adjacent-Elements.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp diff --git a/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp b/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp new file mode 100644 index 000000000..d0d504a54 --- /dev/null +++ b/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp @@ -0,0 +1,66 @@ +using LL = long long; +LL M = 1e9+7; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info00, info11, info10, info01; + + SegTreeNode(int a, int b, vector& vals) // init for range [a,b] with val + { + start = a, end = b; + if (a==b) + { + info11 = vals[start], info01 = -1e18, info10 = -1e18, info00 = 0; + return; + } + int mid = (a+b)/2; + + left = new SegTreeNode(a, mid, vals); + right = new SegTreeNode(mid+1, b, vals); + info11 = max({left->info10 + right->info01, left->info11 + right->info01, left->info10 + right->info11}); + info00 = max({left->info00 + right->info00, left->info01 + right->info00, left->info00 + right->info10}); + info10 = max({left->info10 + right->info00, left->info10 + right->info10, left->info11 + right->info00}); + info01 = max({left->info00 + right->info01, left->info01 + right->info01, left->info00 + right->info11}); + } + + void updateRange(int a, int val) // set range [a,b] with val + { + if (a < start || a > end ) // not covered by [a,b] at all + return; + if (start==end) // completely covered within [a,b] + { + info00 = 0; + info11 = val; + return; + } + + left->updateRange(a, val); + right->updateRange(a, val); + info11 = max({left->info10 + right->info01, left->info11 + right->info01, left->info10 + right->info11}); + info00 = max({left->info00 + right->info00, left->info01 + right->info00, left->info00 + right->info10}); + info10 = max({left->info10 + right->info00, left->info10 + right->info10, left->info11 + right->info00}); + info01 = max({left->info00 + right->info01, left->info01 + right->info01, left->info00 + right->info11}); + } +}; + + +class Solution { +public: + int maximumSumSubsequence(vector& nums, vector>& queries) + { + int n = nums.size(); + SegTreeNode* root = new SegTreeNode(0, n-1, nums); + + LL ret = 0; + for (auto q: queries) + { + root->updateRange(q[0], q[1]); + ret += max({root->info00,root->info01,root->info10,root->info11}); + ret%=M; + } + return ret; + } +}; From ae6b725b48d0cc033e260fc2fe727e39dc1e775d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 13:21:49 -0700 Subject: [PATCH 2538/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 86a12e1ef..354e48430 100644 --- a/Readme.md +++ b/Readme.md @@ -355,7 +355,8 @@ [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) [3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) -[3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) +[3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) +[3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From be79f179bd686761177e5863a1f9a83cf77341bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 13:55:10 -0700 Subject: [PATCH 2539/2729] Create Readme.md --- .../Readme.md | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/Readme.md diff --git a/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/Readme.md b/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/Readme.md new file mode 100644 index 000000000..1f35afc4b --- /dev/null +++ b/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/Readme.md @@ -0,0 +1,70 @@ +### 3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements + +本题的基础是经典的house robber,但是如果从house robber的常规解法去思考,那么本题是做不下去的。事实上,house robber有另一种适合拓展的做法,即递归分治。 + +我们令dp00[i][j]表示[i:j]区间内的最大收益,并且要求左右端点都不取到。同理,定义dp11[i][j]为区间[i:j]两个端点都取到时的最大收益,定义dp10[i][j]为区间[i:j]仅左端点都取到时的最大收益,定义dp01[i][j]为区间[i:j]仅右端点都取到时的最大收益。 + +我们不难发现,对于[i:j]内的任意一个点k,我们可以将[i:j]的收益分为[i:k]和[k+1:j]两端区间的收益之和。更具体地,要满足“不同时取相邻节点”的原则,针对分割处取或不取的决策,我们可以有对dp00[i][j]的三种分解 +``` +dp00[i][j] = max{dp00[i][k]+dp00[k+1][j], dp01[i][k]+dp00[k+1][j], dp00[i][k]+dp10[k+1][j],} +``` +同理,我们可以写出dp01,dp10,dp11的分解。 + +至此我们可以发现这是一个可以自上而下分治解决的问题。边界条件就是`dp00[i][i]=0, dp11[i][i]=1, dp01[i][i]=dp10[i][i]=-inf`. + +写成这样分治的结构,我们明显可以搞成线段树,它有两个好处: +1. 线段树可以用log(n)的时间求任意一段区间内的最大收益。 +2. 对于任何单点的变动后,我们依然可以用log(n)的时间更新整棵线段树。 + +注意,这样的线段树,懒标记是不能用的。每次单点的变动,必须将更新传播到最底层,再把区间最大收益反向传播上去。 + +本题的线段树不需要queryRange方法,最终只需要返回`root->info00,root->info10,root->info01,root->info11`的最大值即可。 + +数据结构如下: +```cpp +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info00, info11, info10, info01; + + SegTreeNode(int a, int b, vector& vals) // init for range [a,b] with val + { + start = a, end = b; + if (a==b) + { + info11 = vals[start], info01 = -1e18, info10 = -1e18, info00 = 0; + return; + } + int mid = (a+b)/2; + + left = new SegTreeNode(a, mid, vals); + right = new SegTreeNode(mid+1, b, vals); + info11 = max({left->info10 + right->info01, left->info11 + right->info01, left->info10 + right->info11}); + info00 = max({left->info00 + right->info00, left->info01 + right->info00, left->info00 + right->info10}); + info10 = max({left->info10 + right->info00, left->info10 + right->info10, left->info11 + right->info00}); + info01 = max({left->info00 + right->info01, left->info01 + right->info01, left->info00 + right->info11}); + } + + void updateRange(int a, int val) // set range [a,b] with val + { + if (a < start || a > end ) // not covered by [a,b] at all + return; + if (start==end) // completely covered within [a,b] + { + info00 = 0; + info11 = val; + return; + } + + left->updateRange(a, val); + right->updateRange(a, val); + info11 = max({left->info10 + right->info01, left->info11 + right->info01, left->info10 + right->info11}); + info00 = max({left->info00 + right->info00, left->info01 + right->info00, left->info00 + right->info10}); + info10 = max({left->info10 + right->info00, left->info10 + right->info10, left->info11 + right->info00}); + info01 = max({left->info00 + right->info01, left->info01 + right->info01, left->info00 + right->info11}); + } +}; +``` From 9cf4d8626f1b157a49ba6fdf55979675739b8929 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 15:03:00 -0700 Subject: [PATCH 2540/2729] Create 3164.Find-the-Number-of-Good-Pairs-II.cpp --- .../3164.Find-the-Number-of-Good-Pairs-II.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Math/3164.Find-the-Number-of-Good-Pairs-II/3164.Find-the-Number-of-Good-Pairs-II.cpp diff --git a/Math/3164.Find-the-Number-of-Good-Pairs-II/3164.Find-the-Number-of-Good-Pairs-II.cpp b/Math/3164.Find-the-Number-of-Good-Pairs-II/3164.Find-the-Number-of-Good-Pairs-II.cpp new file mode 100644 index 000000000..12f85d9e4 --- /dev/null +++ b/Math/3164.Find-the-Number-of-Good-Pairs-II/3164.Find-the-Number-of-Good-Pairs-II.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + long long numberOfPairs(vector& nums1, vector& nums2, int k) + { + vectornums; + for (int x: nums1) + if (x%k==0) + nums.push_back(x/k); + + unordered_map count; + for (int num : nums2) { + count[num]++; + } + long long ret = 0; + + for (int x : nums) + { + for (int d = 1; d * d <= x; ++d) + { + if (x % d == 0) + { + if (count.find(d) != count.end()) { + ret += count[d]; + } + if (d != x / d && count.find(x / d) != count.end()) { + ret += count[x / d]; + } + } + } + } + + return ret; + } +}; From 47945dbf06294241f0db2d1f370aa5f7141449dc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 15:07:34 -0700 Subject: [PATCH 2541/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 354e48430..2b15c572b 100644 --- a/Readme.md +++ b/Readme.md @@ -1274,7 +1274,8 @@ [2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) [2344.Minimum-Deletions-to-Make-Array-Divisible](https://github.com/wisdompeak/LeetCode/tree/master/Math/2344.Minimum-Deletions-to-Make-Array-Divisible) (E) [2543.Check-if-Point-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Math/2543.Check-if-Point-Is-Reachable) (H) -[2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) +[2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) +[3164.Find-the-Number-of-Good-Pairs-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3164.Find-the-Number-of-Good-Pairs-II) (M+) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) From 03d00480a0780bbc0d909a381f3fef5899439f48 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 15:13:10 -0700 Subject: [PATCH 2542/2729] Create Readme.md --- Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md diff --git a/Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md b/Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md new file mode 100644 index 000000000..3ba3a7b96 --- /dev/null +++ b/Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md @@ -0,0 +1,5 @@ +### 3164.Find-the-Number-of-Good-Pairs-II + +首先,我们必然将nums1里不能被k整除的去除掉。 + +接下来,我们就是要寻找有多少个pair,使得nums1的元素能被nums2里的元素整除。看上去似乎没有比o(MN)更好的方法了。但是我们可以换一个角度就豁然开朗。我们可以枚举nums1[i]的约数,只需要sqrt(V)次。对于每个约数我们只需要在hash表里查看是否存在这样的nums2元素即可。这样时间复杂度就是`N*sqrt(V)`. From 0020bbcbc4f5e985bbda4fb237ede89a709dc7e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 1 Jun 2024 20:45:29 -0700 Subject: [PATCH 2543/2729] Create range_bitwise_and.cpp --- Template/SegmentTree/range_bitwise_and.cpp | 107 +++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 Template/SegmentTree/range_bitwise_and.cpp diff --git a/Template/SegmentTree/range_bitwise_and.cpp b/Template/SegmentTree/range_bitwise_and.cpp new file mode 100644 index 000000000..941d06313 --- /dev/null +++ b/Template/SegmentTree/range_bitwise_and.cpp @@ -0,0 +1,107 @@ +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + bool lazy_tag; + LL lazy_val; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info & right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info & right->info; // check with your own logic + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + lazy_tag = 1; + lazy_val = val; + return; + } + + if (left) + { + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = left->info & right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum over range [a,b] + { + if (b < start || a > end ) + { + return INT_MAX; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + LL ret = left->queryRange(a, b) & right->queryRange(a, b); + info = left->info & right->info; + return ret; + } + + return info; // should not reach here + } +}; + +int main() +{ + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. + + for (auto& update: updates) + { + int start = update[0], end = update[1], val = update[2]; + root->updateRange(start, end ,val); // set the range [start, end] with val + } + + for (auto& query: queries) + { + int start = query[0], end = query[1]; + ret[i] = root->queryRange(start, end); // get the range bitwise-and sum over [start, end] + } +} From daa8fa6b42ebfe73f3814d3e694d5c87c07a7a6b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jun 2024 18:12:16 -0700 Subject: [PATCH 2544/2729] Create 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp --- ...Subarray-With-Bitwise-AND-Closest-to-K.cpp | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp new file mode 100644 index 000000000..b158ac478 --- /dev/null +++ b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp @@ -0,0 +1,73 @@ +class SegmentTree { +private: + vector tree; + int n; + + void build(vector& nums, int node, int start, int end) { + if (start == end) { + tree[node] = nums[start]; + } else { + int mid = (start + end) / 2; + build(nums, 2 * node, start, mid); + build(nums, 2 * node + 1, mid + 1, end); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } + } + + int query(int node, int start, int end, int L, int R) { + if (R < start || end < L) { + return INT_MAX; // Identity for AND operation (all bits set) + } + if (L <= start && end <= R) { + return tree[node]; + } + int mid = (start + end) / 2; + int leftAnd = query(2 * node, start, mid, L, R); + int rightAnd = query(2 * node + 1, mid + 1, end, L, R); + return leftAnd & rightAnd; + } + +public: + SegmentTree(vector& nums) { + n = nums.size(); + tree.resize(4 * n, 0); + build(nums, 1, 0, n - 1); + } + + int rangeAnd(int L, int R) { + return query(1, 0, n - 1, L, R); + } +}; + +class Solution { +public: + int minimumDifference(vector& nums, int k) + { + int n = nums.size(); + SegmentTree segTree(nums); + int ret = INT_MAX; + + for (int i = 0; i < n; ++i) + { + int low = i, high = n - 1; + while (low < high) + { + int mid = high - (high - low)/2; + if (segTree.rangeAnd(i, mid) >= k) + low = mid; + else + high = mid-1; + } + + int ret1 = abs(segTree.rangeAnd(i, low) - k); + int ret2 = INT_MAX; + if (low+1 Date: Sun, 2 Jun 2024 18:26:57 -0700 Subject: [PATCH 2545/2729] Update 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp --- ...Subarray-With-Bitwise-AND-Closest-to-K.cpp | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp index b158ac478..db5e8b020 100644 --- a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp +++ b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp @@ -3,7 +3,8 @@ class SegmentTree { vector tree; int n; - void build(vector& nums, int node, int start, int end) { + void build(vector& nums, int node, int start, int end) + { if (start == end) { tree[node] = nums[start]; } else { @@ -13,8 +14,24 @@ class SegmentTree { tree[node] = tree[2 * node] & tree[2 * node + 1]; } } + + void update(int node, int start, int end, int L, int R, int val) + { + if (R < start || end < L) { + return; + } + if (L <= start && end <= R) { + tree[node] = val; + return; + } + int mid = (start + end) / 2; + update(2 * node, start, mid, L, R, val); + update(2 * node + 1, mid + 1, end, L, R, val); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } - int query(int node, int start, int end, int L, int R) { + int query(int node, int start, int end, int L, int R) + { if (R < start || end < L) { return INT_MAX; // Identity for AND operation (all bits set) } @@ -34,6 +51,10 @@ class SegmentTree { build(nums, 1, 0, n - 1); } + void rangeUpdate(int L, int R, int val) { + update(1, 0, n - 1, L, R, val); + } + int rangeAnd(int L, int R) { return query(1, 0, n - 1, L, R); } From 061c80cbf2e3795718f48c86191c785035448910 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jun 2024 18:27:02 -0700 Subject: [PATCH 2546/2729] Update range_bitwise_and.cpp --- Template/SegmentTree/range_bitwise_and.cpp | 147 ++++++++------------- 1 file changed, 54 insertions(+), 93 deletions(-) diff --git a/Template/SegmentTree/range_bitwise_and.cpp b/Template/SegmentTree/range_bitwise_and.cpp index 941d06313..ccc023344 100644 --- a/Template/SegmentTree/range_bitwise_and.cpp +++ b/Template/SegmentTree/range_bitwise_and.cpp @@ -1,107 +1,68 @@ -using LL = long long; -class SegTreeNode -{ - public: - SegTreeNode* left = NULL; - SegTreeNode* right = NULL; - int start, end; - LL info; // the sum value over the range - bool lazy_tag; - LL lazy_val; - - SegTreeNode(int a, int b, int val) // init for range [a,b] with val - { - lazy_tag = 0; - lazy_val = 0; - start = a, end = b; - if (a==b) - { - info = val; - return; - } - int mid = (a+b)/2; - if (left==NULL) - { - left = new SegTreeNode(a, mid, val); - right = new SegTreeNode(mid+1, b, val); - info = left->info & right->info; // check with your own logic - } - } +class SegmentTree { +private: + vector tree; + int n; - SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val - { - lazy_tag = 0; - lazy_val = 0; - start = a, end = b; - if (a==b) - { - info = val[a]; - return; - } - int mid = (a+b)/2; - if (left==NULL) - { - left = new SegTreeNode(a, mid, val); - right = new SegTreeNode(mid+1, b, val); - info = left->info & right->info; // check with your own logic - } + void build(vector& nums, int node, int start, int end) + { + if (start == end) { + tree[node] = nums[start]; + } else { + int mid = (start + end) / 2; + build(nums, 2 * node, start, mid); + build(nums, 2 * node + 1, mid + 1, end); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } } - void updateRange(int a, int b, int val) // set range [a,b] with val - { - if (b < start || a > end ) // not covered by [a,b] at all - return; - if (a <= start && end <=b) // completely covered within [a,b] - { - info = val; - lazy_tag = 1; - lazy_val = val; + void update(int node, int start, int end, int L, int R, int val) + { + if (R < start || end < L) { return; } - - if (left) - { - left->updateRange(a, b, val); - right->updateRange(a, b, val); - info = left->info & right->info; // write your own logic - } + if (L <= start && end <= R) { + tree[node] = val; + return; + } + int mid = (start + end) / 2; + update(2 * node, start, mid, L, R, val); + update(2 * node + 1, mid + 1, end, L, R, val); + tree[node] = tree[2 * node] & tree[2 * node + 1]; } - - LL queryRange(int a, int b) // query the sum over range [a,b] + + int query(int node, int start, int end, int L, int R) { - if (b < start || a > end ) - { - return INT_MAX; // check with your own logic + if (R < start || end < L) { + return INT_MAX; // Identity for AND operation (all bits set) } - if (a <= start && end <=b) - { - return info; // check with your own logic - } - - if (left) - { - LL ret = left->queryRange(a, b) & right->queryRange(a, b); - info = left->info & right->info; - return ret; + if (L <= start && end <= R) { + return tree[node]; } - - return info; // should not reach here - } + int mid = (start + end) / 2; + int leftAnd = query(2 * node, start, mid, L, R); + int rightAnd = query(2 * node + 1, mid + 1, end, L, R); + return leftAnd & rightAnd; + } + +public: + SegmentTree(vector& nums) { + n = nums.size(); + tree.resize(4 * n, 0); + build(nums, 1, 0, n - 1); + } + + void rangeUpdate(int L, int R, int val) { + update(1, 0, n - 1, L, R, val); + } + + int rangeAnd(int L, int R) { + return query(1, 0, n - 1, L, R); + } }; int main() { - SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. - - for (auto& update: updates) - { - int start = update[0], end = update[1], val = update[2]; - root->updateRange(start, end ,val); // set the range [start, end] with val - } - - for (auto& query: queries) - { - int start = query[0], end = query[1]; - ret[i] = root->queryRange(start, end); // get the range bitwise-and sum over [start, end] - } + int n = nums.size(); + SegmentTree segTree(nums); + int ret = segTree.rangeAnd(a, b); } From 71a6f79231c2a6c943afc9faf9e24d99dcb17dde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jun 2024 18:28:00 -0700 Subject: [PATCH 2547/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 2b15c572b..d311943b1 100644 --- a/Readme.md +++ b/Readme.md @@ -357,6 +357,7 @@ [3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) [3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) [3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) +[3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 13598e1f6b1f3657b75a6e45824c4cc91bb0d78f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jun 2024 18:34:47 -0700 Subject: [PATCH 2548/2729] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md new file mode 100644 index 000000000..b15e631d1 --- /dev/null +++ b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md @@ -0,0 +1,5 @@ +### 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K + +暴力解法的时间复杂度是o(N^2),即枚举所有的subarray。我们发现一旦确定了subarray的首元素,在移动尾指针的时候,bitwsie AND的值是单调递减的。所以我们很容易想到用二分的方法来确定答案最接近k的右端点。这就需要我们提前知道任何两点之间的区间bitwise AND的值。这个需求显然与求任意区间内的range sum一样,用线段树可以解决。 + +所以本题是先写好查询区间和“bitwise AND”的线段树模板。然后暴力枚举subarray的首元素i,再大于等于i处用二分寻找右端点位置j,使得区间和最接近k。 From 29107b22f3f619fd3a3113c19cf15e9138d86816 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jun 2024 00:17:15 -0700 Subject: [PATCH 2549/2729] Create 3169.Count-Days-Without-Meetings.cpp --- .../3169.Count-Days-Without-Meetings.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Others/3169.Count-Days-Without-Meetings/3169.Count-Days-Without-Meetings.cpp diff --git a/Others/3169.Count-Days-Without-Meetings/3169.Count-Days-Without-Meetings.cpp b/Others/3169.Count-Days-Without-Meetings/3169.Count-Days-Without-Meetings.cpp new file mode 100644 index 000000000..a208395fd --- /dev/null +++ b/Others/3169.Count-Days-Without-Meetings/3169.Count-Days-Without-Meetings.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int countDays(int days, vector>& meetings) + { + mapMap; + for (auto& meeting: meetings) + { + int a = meeting[0], b = meeting[1]; + Map[a]++; + Map[b+1]--; + } + Map[days+1]+=1; + + int sum = 0; + int cur = 1; + int total = 0; + for (auto [k,v]:Map) + { + if (sum==0 && sum+v>0) + { + total += k-cur; + } + else if (sum>0 && sum+v==0) + { + cur = k; + } + + sum += v; + } + + return total; + } +}; From b4a979c2ee0e1e3483eafd28462105a50f05c313 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jun 2024 00:17:42 -0700 Subject: [PATCH 2550/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d311943b1..33bfac566 100644 --- a/Readme.md +++ b/Readme.md @@ -1580,6 +1580,7 @@ [2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero) (H-) [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) [3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) +[3169.Count-Days-Without-Meetings](https://github.com/wisdompeak/LeetCode/tree/master/Others/3169.Count-Days-Without-Meetings) (M) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 6def3b9daf0cacff549ca88d9b47a2817ff74478 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jun 2024 00:21:56 -0700 Subject: [PATCH 2551/2729] Create Readme.md --- Others/3169.Count-Days-Without-Meetings/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/3169.Count-Days-Without-Meetings/Readme.md diff --git a/Others/3169.Count-Days-Without-Meetings/Readme.md b/Others/3169.Count-Days-Without-Meetings/Readme.md new file mode 100644 index 000000000..71ed74e6c --- /dev/null +++ b/Others/3169.Count-Days-Without-Meetings/Readme.md @@ -0,0 +1,7 @@ +### 3169.Count-Days-Without-Meetings + +很明显这是一道扫描线的题目。对于每个区间[s,e]的会议,我们记录`Map[s]++`和`Map[e+1]--`. 最后我们将Map里的所有key按照时间顺序走一遍,累加差分值至count。 + +当count从正数降为零时,说明没有任何会议,此时记录当前日期cur。当count从零变成正数时,说明出现了会议,那么就将当前日期减去cur,即为最近一段没有会议的时长。 + +最终统计所有无会议的时长之和。 From d7b12383305e403d73eedd6944ebfc46079fac3c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jun 2024 22:32:34 -0700 Subject: [PATCH 2552/2729] Create 3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp --- ...mum-Length-of-a-Good-Subsequence-II_v2.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp diff --git a/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp new file mode 100644 index 000000000..02fc5b52f --- /dev/null +++ b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp @@ -0,0 +1,35 @@ +class Solution { + int dp[5005][55]; +public: + int maximumLength(vector& nums, int k) + { + int n = nums.size(); + vector>max_value(55); + vectormax_all(55); + + int ret = 1; + + for (int i=0; i=1) + ans = max(ans, max_all[t-1]+1); + + dp[i][t] = ans; + ret = max(ret, ans); + } + + for (int t=0; t<=k; t++) + { + max_value[t][nums[i]] = max(max_value[t][nums[i]], dp[i][t]); + max_all[t] = max(max_all[t], dp[i][t]); + } + } + + return ret; + } +}; From e2e66bedc0e247891e55a398becd26695a3d422e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jun 2024 22:34:39 -0700 Subject: [PATCH 2553/2729] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 33bfac566..7d81387ee 100644 --- a/Readme.md +++ b/Readme.md @@ -951,6 +951,8 @@ [2321.Maximum-Score-Of-Spliced-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array) (H-) * ``前缀和辅助`` [3130.Find-All-Possible-Stable-Binary-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II) (H) +* ``遍历优化`` +[3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II)](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II)) (H) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From 354e2019eff90bf2acb341246253cbbfecc1453b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jun 2024 22:37:05 -0700 Subject: [PATCH 2554/2729] Create 3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp --- ...mum-Length-of-a-Good-Subsequence-II_v1.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp diff --git a/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp new file mode 100644 index 000000000..62a19d259 --- /dev/null +++ b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp @@ -0,0 +1,31 @@ +class Solution { + int dp[505][26]; +public: + int maximumLength(vector& nums, int k) + { + int n = nums.size(); + + int ret = 1; + + for (int i=0; i=1) + ans = max(ans, dp[j][t-1]+1); + } + + dp[i][t] = ans; + ret = max(ret, ans); + } + } + + return ret; + } +}; From 1ec04e722e3c0b2e473dcc7bab3cd42b7dba6d4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jun 2024 23:13:14 -0700 Subject: [PATCH 2555/2729] Create Readme.md --- .../Readme.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/Readme.md diff --git a/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/Readme.md b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/Readme.md new file mode 100644 index 000000000..6e055fbf6 --- /dev/null +++ b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/Readme.md @@ -0,0 +1,59 @@ +### 3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II + +#### 解法1:For 3176 +对于常规的DP解法,我们容易设置状态变量dp[i][t]表示前i个元素里、我们已经出现了t次相邻元素不等的情况下,能够得到的goode subsequence的最大长度。 + +显然转移的突破口就在于nums[i]是否与sequence的前一个元素相同。我们枚举j=1) + ans = max(ans, dp[j][t-1]+1); + } + dp[i][t] = ans; + ret = max(ret, ans); + } + } +``` + +#### 解法2: +上述解法的时间复杂度是o(N^2*K)。如何优化呢?事实上我们可以对最内层的j循环优化。首先看else分支,它的本质是在dp[j][t]中取最大值。这个其实我们可以在之前计算dp的过程中顺便维护一下dp[j][t]的最大值即可。即`max_all[t] = max(dp[j][t]) j=0,1,2..i-1`. + +再看if分支,它的本质就是在dp[j][t-1]中、对于那些nums[j]==nums[i]的dp值取最大值。这其实也可以用一个hash,以nums[i]为key,来维护这个最大值。即`max_value[t][v] = max(dp[j][t][v]) j=0,1,2..i-1 and nums[j]==v`. + +有人会说,else分支是只有在nums[j]!=nums[i]时才跑的,所以`max_all[t]`的定义有缺陷,应该剔除掉一些元素。其实我们可以不在意。因为逻辑上一定有`dp[j][t]>dp[j][t-1]`,所以对于那些nums[j]==nums[i]的元素j,走if分支会比走else分支更合算。所以`max_all[t]`不剔除与nums[i]相同的那些dp值也没有关系。 + +于是解法1就可以变成如下。注意我们在t循环计算完dp[i][t]之后,再进行一次循环更新max_valuet[t][nums[i]和max_all[t]. +```cpp + for (int i=0; i Date: Sun, 23 Jun 2024 18:03:25 -0700 Subject: [PATCH 2556/2729] Create 3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp --- ...-the-Minimum-Area-to-Cover-All-Ones-II.cpp | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp new file mode 100644 index 000000000..4ca3aa9ad --- /dev/null +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp @@ -0,0 +1,101 @@ +class Solution { +public: + int minimumSum(vector>& grid) + { + int ret = INT_MAX; + + int m = grid.size(), n = grid[0].size(); + + /*************************/ + 1. 2. 3. + + ┌-┐ ┌┐┌┐ ┌-┐ + └-┘ └┘└┘ └-┘ + ┌-┐ ┌-┐ ┌┐┌┐ + └-┘ └-┘ └┘└┘ + ┌-┐ + └-┘ + + 4. 5. 6. + ┌┐┌┐┌┐ ┌ ┐┌┐ ┌┐┌ ┐ + └┘└┘└┘ │ │└┘ └┘│ │ + │ │┌┐ ┌┐│ │ + └ ┘└┘ └┘└ ┘ + /*************************/ + + for (int i=1; i>& grid, int a, int b, int c, int d) + { + if (a>c || b>d) return INT_MAX/3; + int left = INT_MAX, top = INT_MAX, bottom = INT_MIN, right = INT_MIN; + for (int i=a; i<=c; i++) + for (int j=b; j<=d; j++) + { + if (grid[i][j]==0) continue; + left = min(left, j); + right = max(right, j); + top = min(top, i); + bottom = max(bottom, i); + } + if (bottom>=top && right>=left) + return (bottom-top+1)*(right-left+1); + else + return INT_MAX/3; + } +}; From 87262c9dc147aad6649ce099ad02a059836259bf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 18:04:36 -0700 Subject: [PATCH 2557/2729] Create 3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp --- ...-the-Minimum-Area-to-Cover-All-Ones-II.cpp | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp diff --git a/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp b/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp new file mode 100644 index 000000000..4ca3aa9ad --- /dev/null +++ b/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp @@ -0,0 +1,101 @@ +class Solution { +public: + int minimumSum(vector>& grid) + { + int ret = INT_MAX; + + int m = grid.size(), n = grid[0].size(); + + /*************************/ + 1. 2. 3. + + ┌-┐ ┌┐┌┐ ┌-┐ + └-┘ └┘└┘ └-┘ + ┌-┐ ┌-┐ ┌┐┌┐ + └-┘ └-┘ └┘└┘ + ┌-┐ + └-┘ + + 4. 5. 6. + ┌┐┌┐┌┐ ┌ ┐┌┐ ┌┐┌ ┐ + └┘└┘└┘ │ │└┘ └┘│ │ + │ │┌┐ ┌┐│ │ + └ ┘└┘ └┘└ ┘ + /*************************/ + + for (int i=1; i>& grid, int a, int b, int c, int d) + { + if (a>c || b>d) return INT_MAX/3; + int left = INT_MAX, top = INT_MAX, bottom = INT_MIN, right = INT_MIN; + for (int i=a; i<=c; i++) + for (int j=b; j<=d; j++) + { + if (grid[i][j]==0) continue; + left = min(left, j); + right = max(right, j); + top = min(top, i); + bottom = max(bottom, i); + } + if (bottom>=top && right>=left) + return (bottom-top+1)*(right-left+1); + else + return INT_MAX/3; + } +}; From c697d06dd809dd31a7da21f6b4326d5296b0b4c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 18:05:14 -0700 Subject: [PATCH 2558/2729] Delete Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II directory --- ...-the-Minimum-Area-to-Cover-All-Ones-II.cpp | 101 ------------------ 1 file changed, 101 deletions(-) delete mode 100644 Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp deleted file mode 100644 index 4ca3aa9ad..000000000 --- a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp +++ /dev/null @@ -1,101 +0,0 @@ -class Solution { -public: - int minimumSum(vector>& grid) - { - int ret = INT_MAX; - - int m = grid.size(), n = grid[0].size(); - - /*************************/ - 1. 2. 3. - - ┌-┐ ┌┐┌┐ ┌-┐ - └-┘ └┘└┘ └-┘ - ┌-┐ ┌-┐ ┌┐┌┐ - └-┘ └-┘ └┘└┘ - ┌-┐ - └-┘ - - 4. 5. 6. - ┌┐┌┐┌┐ ┌ ┐┌┐ ┌┐┌ ┐ - └┘└┘└┘ │ │└┘ └┘│ │ - │ │┌┐ ┌┐│ │ - └ ┘└┘ └┘└ ┘ - /*************************/ - - for (int i=1; i>& grid, int a, int b, int c, int d) - { - if (a>c || b>d) return INT_MAX/3; - int left = INT_MAX, top = INT_MAX, bottom = INT_MIN, right = INT_MIN; - for (int i=a; i<=c; i++) - for (int j=b; j<=d; j++) - { - if (grid[i][j]==0) continue; - left = min(left, j); - right = max(right, j); - top = min(top, i); - bottom = max(bottom, i); - } - if (bottom>=top && right>=left) - return (bottom-top+1)*(right-left+1); - else - return INT_MAX/3; - } -}; From 9a3830bffeece5a2cb0f2c2590fbca7abc4d6218 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 18:05:52 -0700 Subject: [PATCH 2559/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7d81387ee..6e501680d 100644 --- a/Readme.md +++ b/Readme.md @@ -1228,6 +1228,7 @@ [2967.Minimum-Cost-to-Make-Array-Equalindromic](https://github.com/wisdompeak/LeetCode/tree/master/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic) (H-) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) [3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) +[3197.Find-the-Minimum-Area-to-Cover-All-Ones-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II) (H-) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) From 7042b9068c626f371144fa05e72dd278cc04006e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 22:34:34 -0700 Subject: [PATCH 2560/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/Readme.md diff --git a/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/Readme.md b/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/Readme.md new file mode 100644 index 000000000..c791a7e39 --- /dev/null +++ b/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/Readme.md @@ -0,0 +1,21 @@ +### 3197.Find-the-Minimum-Area-to-Cover-All-Ones-II + +事实上将一个矩阵分成三个互不相交的子矩形,只有如下六种形式: +``` + 1. 2. 3. + + ┌-┐ ┌┐┌┐ ┌-┐ + └-┘ └┘└┘ └-┘ + ┌-┐ ┌-┐ ┌┐┌┐ + └-┘ └-┘ └┘└┘ + ┌-┐ + └-┘ + + 4. 5. 6. + ┌┐┌┐┌┐ ┌ ┐┌┐ ┌┐┌ ┐ + └┘└┘└┘ │ │└┘ └┘│ │ + │ │┌┐ ┌┐│ │ + └ ┘└┘ └┘└ ┘ +``` +对于每种形式,只有两条分割线。我们可以用o(MN)的时间遍历分割线的位置,就可以确定三个子矩阵的边界。对于每一个子矩阵,我们再遍历其中的元素,确定包含所有元素1的最小矩阵即可(同3135)。 + From 63d9d115cb1aeed68401c0f5a4bc6336c66b5121 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 23:35:48 -0700 Subject: [PATCH 2561/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 6e501680d..e0c1a9e8c 100644 --- a/Readme.md +++ b/Readme.md @@ -1228,7 +1228,6 @@ [2967.Minimum-Cost-to-Make-Array-Equalindromic](https://github.com/wisdompeak/LeetCode/tree/master/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic) (H-) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) [3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) -[3197.Find-the-Minimum-Area-to-Cover-All-Ones-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II) (H-) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) @@ -1239,7 +1238,8 @@ [1401.Circle-and-Rectangle-Overlapping](https://github.com/wisdompeak/LeetCode/tree/master/Math/1401.Circle-and-Rectangle-Overlapping) (H) [1453.Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard](https://github.com/wisdompeak/LeetCode/tree/master/Math/1453.Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard) (H) [1610.Maximum-Number-of-Visible-Points](https://github.com/wisdompeak/LeetCode/tree/master/Math/1610.Maximum-Number-of-Visible-Points) (H) -[2280.Minimum-Lines-to-Represent-a-Line-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart) (M) +[2280.Minimum-Lines-to-Represent-a-Line-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart) (M) +[3197.Find-the-Minimum-Area-to-Cover-All-Ones-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II) (H-) * ``Random Pick`` [382.Linked-List-Random-Node](https://github.com/wisdompeak/LeetCode/tree/master/Math/382.Linked-List-Random-Node) (H) [470.Implement-Rand10()-Using-Rand7()](https://github.com/wisdompeak/LeetCode/tree/master/Math/470.Implement-Rand10--Using-Rand7) (M+) From 9462473d8aab0b81b9698686a160f103fd573336 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 23:41:25 -0700 Subject: [PATCH 2562/2729] Create 3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp --- ...ze-Total-Cost-of-Alternating-Subarrays.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp diff --git a/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp b/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp new file mode 100644 index 000000000..7b7ac7b8d --- /dev/null +++ b/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp @@ -0,0 +1,20 @@ +using LL = long long; +class Solution { + LL dp[100005][2]; +public: + long long maximumTotalCost(vector& nums) + { + int n = nums.size(); + + dp[0][1] = nums[0]; + dp[0][0] = LLONG_MIN/2; + + for (int i=1; i Date: Sun, 23 Jun 2024 23:41:56 -0700 Subject: [PATCH 2563/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index e0c1a9e8c..60987321c 100644 --- a/Readme.md +++ b/Readme.md @@ -853,7 +853,8 @@ [487.Max-Consecutive-Ones-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/487.Max-Consecutive-Ones-II) (H-) [1186.Maximum-Subarray-Sum-with-One-Deletion](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1186.Maximum-Subarray-Sum-with-One-Deletion) (H-) [1187.Make-Array-Strictly-Increasing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1187.Make-Array-Strictly-Increasing) (H-) -[1909.Remove-One-Element-to-Make-the-Array-Strictly-Increasing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1909.Remove-One-Element-to-Make-the-Array-Strictly-Increasing) (H-) +[1909.Remove-One-Element-to-Make-the-Array-Strictly-Increasing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1909.Remove-One-Element-to-Make-the-Array-Strictly-Increasing) (H-) +[3196.Maximize-Total-Cost-of-Alternating-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays) (M) * ``区间型 I`` [132.Palindrome-Partitioning-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/132.Palindrome-Partitioning-II) (H-) [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H) From 036a143f59fac39bfcfdc0e657d914307d8ebef4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 23:46:38 -0700 Subject: [PATCH 2564/2729] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/Readme.md diff --git a/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/Readme.md b/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/Readme.md new file mode 100644 index 000000000..1822877aa --- /dev/null +++ b/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/Readme.md @@ -0,0 +1,10 @@ +### 3196.Maximize-Total-Cost-of-Alternating-Subarrays + +本题的本质就是,每个元素可以更改它的符号,但是不能连着两个元素都更改符号。求所有元素和的最大值。这就是house robber。 + +令dp[i][1]表示第i个元素更改符号时、前i个元素的最大收益;令dp[i][0]表示第i个元素不更改符号时、前i个元素的最大收益。则有转移方程: +```cpp +dp[i][1] = dp[i-1][0] - nums[i]; +dp[i][0] = max(dp[i-1][1],dp[i-1][0])+nums[i]; +``` +最终答案就是查看最后一个元素对应的dp[n-1][0或1]的最大值。 From 094e24056835492bdbec242bd310dfa18642d2aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Jun 2024 00:09:11 -0700 Subject: [PATCH 2565/2729] Create 3193.Count-the-Number-of-Inversions.cpp --- .../3193.Count-the-Number-of-Inversions.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Dynamic_Programming/3193.Count-the-Number-of-Inversions/3193.Count-the-Number-of-Inversions.cpp diff --git a/Dynamic_Programming/3193.Count-the-Number-of-Inversions/3193.Count-the-Number-of-Inversions.cpp b/Dynamic_Programming/3193.Count-the-Number-of-Inversions/3193.Count-the-Number-of-Inversions.cpp new file mode 100644 index 000000000..c07e9f516 --- /dev/null +++ b/Dynamic_Programming/3193.Count-the-Number-of-Inversions/3193.Count-the-Number-of-Inversions.cpp @@ -0,0 +1,54 @@ +using LL = long long; +class Solution { + LL dp[305][405]; + LL M = 1e9+7; +public: + int numberOfPermutations(int n, vector>& requirements) + { + dp[0][0] = 1; + + mapMap; + for (auto req: requirements) + { + int end = req[0] + 1; + int cnt = req[1]; + Map[end] = cnt; + } + + int cur = 0; + for (int i=1; i<=n; i++) + { + if (Map.find(i)!=Map.end()) + cur = Map[i]; + + auto iter = Map.lower_bound(i); + LL limit = iter->second; + for (int j=cur; j<=limit; j++) + { + for (int k=0; k<=j; k++) + { + if (j-k<=i-1) + { + dp[i][j] += dp[i-1][k]; + dp[i][j] %= M; + } + } + } + + if (Map.upper_bound(i)==Map.end()) + { + LL ret = dp[i][cur]; + return ret * fact(n-i) % M; + } + } + return 0; + } + + LL fact(LL n) + { + LL ret = 1; + for (int i=1; i<=n; i++) + ret = ret * i % M; + return ret; + } +}; From 33def1664982d623992d59ce04116890c68e7600 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Jun 2024 00:09:40 -0700 Subject: [PATCH 2566/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 60987321c..7981f4852 100644 --- a/Readme.md +++ b/Readme.md @@ -941,7 +941,8 @@ * ``Permutation`` [629.K-Inverse-Pairs-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/629.K-Inverse-Pairs-Array) (H) [903.Valid-Permutations-for-DI-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence) (H) -[1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) +[1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) +[3193.Count-the-Number-of-Inversions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3193.Count-the-Number-of-Inversions) (H) * ``Infer future from current`` [2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) [2742.Painting-the-Walls](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2742.Painting-the-Walls) (H) From 9c67ee6e425c588252520d1d454b8043992835b3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Jun 2024 01:14:03 -0700 Subject: [PATCH 2567/2729] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Dynamic_Programming/3193.Count-the-Number-of-Inversions/Readme.md diff --git a/Dynamic_Programming/3193.Count-the-Number-of-Inversions/Readme.md b/Dynamic_Programming/3193.Count-the-Number-of-Inversions/Readme.md new file mode 100644 index 000000000..d0c4a09ff --- /dev/null +++ b/Dynamic_Programming/3193.Count-the-Number-of-Inversions/Readme.md @@ -0,0 +1,22 @@ +### 3193.Count-the-Number-of-Inversions + +对于permutation类型的DP题有着类似的套路。其核心就是,任意一个长度为n的permutation的前i个元素,可以一一对应于一个长度为i的permutation。所以对于长度为n的permutation做动态规划时,对于状态变量dp[i](长度为n的permutation的前i个元素组成的、符合条件的序列个数),都可以等效看做是长度为i的(即1-i组成的)、符合条件的permutation个数。 + +因为本题涉及逆序对的数目,并且题目数据量给出的逆序对数目不超过400,故我们可以将其作为状态变量的一个下标。即我们定义dp[i][j]表示1-i组成的permutation里、逆序对数目是j的排列的个数。 + +对于前i个元素组成的permutation,能允许有多少逆序对呢?这取决于requirements给出的约束。举个例子,如果requirement要求在第p位有a个逆序对,在第q位有b个逆序对,并且恰好有`p<=i<=q`(即p和q是i最贴近的两个约束点),那么对于dp[i][j]而言,j的取值就是`a<=j<=b`. + +如何求解dp[i][j]呢?我们需要寻找它与前驱状态dp[i-1][k]的关系。注意到相对于dp[i-1][],我们在permutation中引入了新元素i,如果将i放在排列的最后,那么它不会引入任何新的逆序对。如果将i放在排列的倒数第二个位置,那么会引入一个逆序对... 依次类推,如果前驱状态dp[i-1][k]已经有k个逆序对,那么相对于j而言,我们需要再引入`j-k`个逆序对。这能否实现呢?其实只需要满足在i-1的排列中至少有j-k个元素即可,即`j-k<=i-1`。故 +```cpp +for (int i=1; i<=n; i++) +{ + int a = ... , b = ... ; + for (int j=a; j<=b; j++) + for (int k=0; k<=j; k++) + { + if (j-k <= i-1) + dp[i][j] += dp[i-1][k]; + } +} +``` +注意到,当处理完requirement的最后一个约束位置i后,此后上限b就不存在了。此时意味还有`t = n-i`个元素没有加入排列。注意这t个元素不能加入前i个元素组成的排列里,否则会违反在i处的约束;但是这t个元素本身可以在排列之后任意混排,不影响之前的requirement。故最终的答案就是`dp[i][r]*t!`,其中r表示requirement在i处的逆序对数目要求。 From e8ce5426abb1a83a1532d96e33827a6afd1940f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 29 Jun 2024 20:55:42 -0700 Subject: [PATCH 2568/2729] Update 1245.Tree-Diameter.cpp --- BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp b/BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp index 579951bb5..8b5f7fc83 100644 --- a/BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp +++ b/BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp @@ -1,25 +1,23 @@ class Solution { - vector>adj; - int V; public: int treeDiameter(vector>& edges) { - V = edges.size()+1; - adj.resize(V); - for (auto edge:edges) + int n = edges.size()+1; + vector>next(n); + for (auto edge: edges) { - adj[edge[0]].push_back(edge[1]); - adj[edge[1]].push_back(edge[0]); + next[edge[0]].push_back(edge[1]); + next[edge[1]].push_back(edge[0]); } - - auto t1 = bfs(0); - auto t2 = bfs(t1.first); + auto t1 = bfs(next, 0); + auto t2 = bfs(next, t1.first); return t2.second; } - - pair bfs(int u) + + pair bfs(vector>&next, int u) { - vectordis(V, -1); + int n = next.size(); + vectordis(n, -1); queue q; q.push(u); @@ -30,7 +28,7 @@ class Solution { int t = q.front(); q.pop(); - for (auto it = adj[t].begin(); it != adj[t].end(); it++) + for (auto it = next[t].begin(); it != next[t].end(); it++) { int v = *it; if (dis[v] == -1) @@ -42,9 +40,9 @@ class Solution { } int maxDis = 0; - int nodeIdx; + int nodeIdx = 0; - for (int i = 0; i < V; i++) + for (int i = 0; i < n; i++) { if (dis[i] > maxDis) { @@ -53,5 +51,5 @@ class Solution { } } return make_pair(nodeIdx, maxDis); - } + } }; From ffff651bd3774b4373c53b116f74e11e97525ba0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 09:40:52 -0700 Subject: [PATCH 2569/2729] Create 3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp --- ...nimum-Diameter-After-Merging-Two-Trees.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp diff --git a/Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp b/Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp new file mode 100644 index 000000000..9039d329e --- /dev/null +++ b/Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp @@ -0,0 +1,63 @@ +class Solution { +public: + int minimumDiameterAfterMerge(vector>& edges1, vector>& edges2) + { + int a = treeDiameter(edges1); + int b = treeDiameter(edges2); + return max({(a+1)/2+(b+1)/2+1, a, b}); + } + + int treeDiameter(vector>& edges) + { + int n = edges.size()+1; + vector>next(n); + for (auto edge: edges) + { + next[edge[0]].push_back(edge[1]); + next[edge[1]].push_back(edge[0]); + } + auto t1 = bfs(next, 0); + auto t2 = bfs(next, t1.first); + return t2.second; + } + + pair bfs(vector>&next, int u) + { + int n = next.size(); + vectordis(n, -1); + queue q; + q.push(u); + + dis[u] = 0; + + while (!q.empty()) + { + int t = q.front(); + q.pop(); + + for (auto it = next[t].begin(); it != next[t].end(); it++) + { + int v = *it; + if (dis[v] == -1) + { + q.push(v); + dis[v] = dis[t] + 1; + } + } + } + + int maxDis = 0; + int nodeIdx = 0; + + for (int i = 0; i < n; i++) + { + if (dis[i] > maxDis) + { + maxDis = dis[i]; + nodeIdx = i; + } + } + return make_pair(nodeIdx, maxDis); + } + +}; From 00f797c978739ccd87fe7f11857b37357a95fdb9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 09:42:00 -0700 Subject: [PATCH 2570/2729] Rename Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp to Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp --- .../3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/{543.Diameter-of-Binary-Tree => }/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp (100%) diff --git a/Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp b/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp similarity index 100% rename from Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp rename to Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp From e7645c9c4ad1dd689e6eeca7663637b8c66e146a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 09:43:31 -0700 Subject: [PATCH 2571/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7981f4852..5fdaae035 100644 --- a/Readme.md +++ b/Readme.md @@ -302,7 +302,8 @@ [1522.Diameter-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1522.Diameter-of-N-Ary-Tree) (M) [2049.Count-Nodes-With-the-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2049.Count-Nodes-With-the-Highest-Score) (M+) [2246.Longest-Path-With-Different-Adjacent-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2246.Longest-Path-With-Different-Adjacent-Characters) (M+) -[2538.Difference-Between-Maximum-and-Minimum-Price-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum) (H) +[2538.Difference-Between-Maximum-and-Minimum-Price-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum) (H) +[3203.Find-Minimum-Diameter-After-Merging-Two-Trees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees) (H-) * ``Serialization & Hashing`` [297.Serialize-and-Deserialize-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/297.Serialize-and-Deserialize-Binary-Tree) (H-) [652.Find-Duplicate-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/652.Find-Duplicate-Subtrees) (H) From b527939f196e18f2c1947b7f96be1d5f748b1c72 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 09:52:52 -0700 Subject: [PATCH 2572/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/Readme.md diff --git a/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/Readme.md b/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/Readme.md new file mode 100644 index 000000000..07ab373b9 --- /dev/null +++ b/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/Readme.md @@ -0,0 +1,9 @@ +### 3203.Find-Minimum-Diameter-After-Merging-Two-Trees + +关于树的最大路径(直径),我们已经有`1245.Tree-Diameter`的做法。 + +在本题中,我们要求联通后的树的直径最小,那么联通的两个点,必定在各自树的直径的中点位置。这可以用简单的反证法推理:假设联通点是树的节点A,那么根据直径定义,我们需要寻找A到树里离它的最远端点。我们可以至少找到这样一条路径:A先到直径的中点M,再从M走到直径的一个端点(固定为d/2长度)。这条路径显然总长于将A点直接设置于M处的方案。故联通点设置在M处,可以最小化A离它最短端点。 + +所以本题的一个解就是 `ceil(d1/2) + ceil(d2/2) + 1`。 + +但是注意,联通树的最大直径不一定要一定同时经过树1和树2。比如,如果树1远远大于树2,那么d1本身就可能是联通树的最大直径。类似的d2也是。所以本题是要在三个可能答案中取最大的那个。 From f34f3c806bd8b0b62f431532524e0efeb168c833 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 16:34:05 -0700 Subject: [PATCH 2573/2729] Create 3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp --- ...Maximum-Length-of-Valid-Subsequence-II.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp diff --git a/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp new file mode 100644 index 000000000..a167847fd --- /dev/null +++ b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp @@ -0,0 +1,27 @@ +class Solution { + int dp[1005][1005]; +public: + int maximumLength(vector& nums, int k) + { + vectorlast(k, -1); + + int ret = 0; + int n = nums.size(); + for (int i=0; i Date: Fri, 5 Jul 2024 16:35:59 -0700 Subject: [PATCH 2574/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5fdaae035..fc4db1162 100644 --- a/Readme.md +++ b/Readme.md @@ -811,7 +811,8 @@ [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) [2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) [2464.Minimum-Subarrays-in-a-Valid-Split](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split) (M) -[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) +[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) +[3202.Find-the-Maximum-Length-of-Valid-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II) (M) * `Interval` [1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) From 6b9cffb808e94d865fca13a14d1b090449c705ae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 16:42:29 -0700 Subject: [PATCH 2575/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/Readme.md diff --git a/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/Readme.md b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/Readme.md new file mode 100644 index 000000000..4b570cc07 --- /dev/null +++ b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/Readme.md @@ -0,0 +1,9 @@ +### 3202.Find-the-Maximum-Length-of-Valid-Subsequence-II + +本题要求找一个最长的子序列,使得相邻两个元素之和对于k的余数相同。 + +考虑到长度n和k都不大,我们可以将其考虑为动态规划的两个下标。令dp[i][r]表示前i个元素里、相邻两个元素之和对于k的余数是r的最长子序列长度。 + +对于nums[i]而言,要使得它与前一个子序列元素之和对于k的余数是r,那么要求前一个子序列元素对于k的于是就是`d=(r-nums[i]%k)%k`。我们只需要用哈希表记录上一个余数为d的位置j即可,就有`dp[i][r]=dp[j][r]+1`. + +最终返回在计算过程中遇到过的最大的dp值。 From a28fd1fd29f3fce7d18f6e7cbfefebcfbfc3a81e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 17:07:19 -0700 Subject: [PATCH 2576/2729] Update 3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp --- ...-Maximum-Length-of-Valid-Subsequence-II.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp index a167847fd..01d999977 100644 --- a/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp +++ b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp @@ -4,24 +4,28 @@ class Solution { int maximumLength(vector& nums, int k) { vectorlast(k, -1); - int ret = 0; + int n = nums.size(); for (int i=0; i Date: Fri, 5 Jul 2024 22:45:32 -0700 Subject: [PATCH 2577/2729] Create 3187.Peaks-in-Array.cpp --- .../3187.Peaks-in-Array.cpp | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp diff --git a/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp b/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp new file mode 100644 index 000000000..ea3080c27 --- /dev/null +++ b/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp @@ -0,0 +1,148 @@ +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + bool lazy_tag; + LL lazy_val; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (lazy_tag==1 && left) + { + left->info = lazy_val * (left->end - left->start + 1); + right->info = lazy_val * (right->end - right->start + 1); + left->lazy_tag = 1; left->lazy_val = lazy_val; + right->lazy_tag = 1; right->lazy_val = lazy_val; + lazy_tag = 0; lazy_val = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val * (end-start+1); + lazy_tag = 1; + lazy_val = val; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum over range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +class Solution { +public: + vector countOfPeaks(vector& nums, vector>& queries) + { + int n = nums.size(); + vectorvals(n, 0); + for (int i=1; inums[i-1] && nums[i]>nums[i+1]) + vals[i] = 1; + } + + SegTreeNode* root = new SegTreeNode(0, n-1, vals); + + vectorrets; + for (auto query: queries) + { + if (query[0]==1) + { + int a = query[1], b = query[2]; + rets.push_back(root->queryRange(a+1, b-1)); + } + else + { + int i = query[1]; + nums[i] = query[2]; + if (i>=1 && i=1 && i-1=1 && i+1&nums, vector&vals) + { + int v = nums[i]>nums[i-1] && nums[i]>nums[i+1]; + if (v==vals[i]) return; + vals[i] = v; + root->updateRange(i,i,v); + } +}; From 7d34fe17670d90684a950554715d1ed89d0a0aeb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 22:46:06 -0700 Subject: [PATCH 2578/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fc4db1162..6b094db59 100644 --- a/Readme.md +++ b/Readme.md @@ -359,6 +359,7 @@ [3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) [3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) [3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) +[3187.Peaks-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3187.Peaks-in-Array) (M+) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 57d523deb56fea2e14426ff518ba318d38ed8b18 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 23:24:01 -0700 Subject: [PATCH 2579/2729] Create Readme.md --- Segment_Tree/3187.Peaks-in-Array/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Segment_Tree/3187.Peaks-in-Array/Readme.md diff --git a/Segment_Tree/3187.Peaks-in-Array/Readme.md b/Segment_Tree/3187.Peaks-in-Array/Readme.md new file mode 100644 index 000000000..78d93ad47 --- /dev/null +++ b/Segment_Tree/3187.Peaks-in-Array/Readme.md @@ -0,0 +1,5 @@ +### 3187.Peaks-in-Array + +高效地求任意一段区间内的peak的数目,显然是用线段树实现。我们构造一棵线段树,叶子节点是一个binary value,表示该元素是否是peak。 + +当我们修改nums[i]时,可能会对i-1,i,i+1三处位置的peak状态产生影响。所以我们需要分别进行考察,相应地修改线段树节点的值。 From d05ee685474f22414e0eaf41810e2d5663ce9f1a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 23:25:02 -0700 Subject: [PATCH 2580/2729] Update 3187.Peaks-in-Array.cpp --- .../3187.Peaks-in-Array.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp b/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp index ea3080c27..a3125ea3a 100644 --- a/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp +++ b/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp @@ -108,14 +108,14 @@ class Solution { vector countOfPeaks(vector& nums, vector>& queries) { int n = nums.size(); - vectorvals(n, 0); + vectorpeaks(n, 0); for (int i=1; inums[i-1] && nums[i]>nums[i+1]) - vals[i] = 1; + peaks[i] = 1; } - SegTreeNode* root = new SegTreeNode(0, n-1, vals); + SegTreeNode* root = new SegTreeNode(0, n-1, peaks); vectorrets; for (auto query: queries) @@ -129,20 +129,20 @@ class Solution { { int i = query[1]; nums[i] = query[2]; - if (i>=1 && i=1 && i-1=1 && i+1=1 && i=1 && i-1=1 && i+1&nums, vector&vals) + void check(SegTreeNode* root, int i, vector&nums, vector&peaks) { int v = nums[i]>nums[i-1] && nums[i]>nums[i+1]; - if (v==vals[i]) return; - vals[i] = v; + if (v==peaks[i]) return; + peaks[i] = v; root->updateRange(i,i,v); } }; From d3b41850f8d794e9ea8cc697b97fbd798b3e5ada Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 23:54:32 -0700 Subject: [PATCH 2581/2729] Create 3186.Maximum-Total-Damage-With-Spell-Casting.cpp --- ...aximum-Total-Damage-With-Spell-Casting.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp diff --git a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp new file mode 100644 index 000000000..0726a6a68 --- /dev/null +++ b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp @@ -0,0 +1,37 @@ +using LL = long long; +class Solution { +public: + long long maximumTotalDamage(vector& power) + { + mapp; + for (int x: power) + p[x]++; + + vector>arr(p.begin(), p.end()); + + vectordp(arr.size()); + + LL ret = 0; + for (int i=0; i=1) ans = max(ans, dp[i-1]); + + if (i>=1 && arr[i-1].first=2 && arr[i-2].first=3 && arr[i-3].first Date: Fri, 5 Jul 2024 23:55:03 -0700 Subject: [PATCH 2582/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 6b094db59..b7a0ac25b 100644 --- a/Readme.md +++ b/Readme.md @@ -764,7 +764,8 @@ [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) [2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (H) -[2638.Count-the-Number-of-K-Free-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets) (M+) +[2638.Count-the-Number-of-K-Free-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets) (M+) +[3186.Maximum-Total-Damage-With-Spell-Casting](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting) (M+) [2320.Count-Number-of-Ways-to-Place-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses) (M+) [1388.Pizza-With-3n-Slices](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1388.Pizza-With-3n-Slices) (H-) [276.Paint-Fence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/276.Paint-Fence) (H-) From 274af012d0368ed684cd9c48698fa77a5d4658f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 00:21:48 -0700 Subject: [PATCH 2583/2729] Create Readme.md --- .../3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md diff --git a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md new file mode 100644 index 000000000..48150fb9e --- /dev/null +++ b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md @@ -0,0 +1,7 @@ +### 3186.Maximum-Total-Damage-With-Spell-Casting + +这非常类似一个house robber的问题。我们将所有的spell按照power的distinct value按从小到大排序,定义dp[i]表示从前i件spell里选取所能构成的最大和,其中题意要求不能选取power值差距在2以内的spell。 + +当我们选取spell[i]的时候,查看spell[i-1]是否与spell[i]的差值在2之外,如果是的话,那么dp[i]就可以在dp[i-1]的基础上加上所有属于spell[i]的power。如果不是的话,我们往前查看spell[i-2]与spell[i]的差值是否在2之外,如果是的话,那么dp[i]就可以在dp[i-2]的基础上加上所有属于spell[i]的power。如果再不是的话,那么dp[i]可以直接在dp[i-3]的基础上加上所有属于spell[i]的power,这是因为spell数值彼此不同,spell[i-3]和spell[i]的差值必然大于2. + +最终答案返回dp[n-1]即可。 From 4f4b5f6b3b7858e8e3167e491624163583d83db8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 01:03:43 -0700 Subject: [PATCH 2584/2729] Update Readme.md --- .../3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md index 48150fb9e..dc3212c0b 100644 --- a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md +++ b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md @@ -1,7 +1,9 @@ ### 3186.Maximum-Total-Damage-With-Spell-Casting -这非常类似一个house robber的问题。我们将所有的spell按照power的distinct value按从小到大排序,定义dp[i]表示从前i件spell里选取所能构成的最大和,其中题意要求不能选取power值差距在2以内的spell。 +这非常类似一个house robber的问题。我们将所有的spell按照power的distinct value按从小到大排序,定义dp[i]表示从前i件spell里选取所能构成的最大和,其中题意要求不能选取power值差距在2以内的spell。特别注意,dp[i]不一定要求必须取第i种spell。 -当我们选取spell[i]的时候,查看spell[i-1]是否与spell[i]的差值在2之外,如果是的话,那么dp[i]就可以在dp[i-1]的基础上加上所有属于spell[i]的power。如果不是的话,我们往前查看spell[i-2]与spell[i]的差值是否在2之外,如果是的话,那么dp[i]就可以在dp[i-2]的基础上加上所有属于spell[i]的power。如果再不是的话,那么dp[i]可以直接在dp[i-3]的基础上加上所有属于spell[i]的power,这是因为spell数值彼此不同,spell[i-3]和spell[i]的差值必然大于2. +当我们考察spell[i]的时候,我们可以不取第i种spell,这样的话就是dp[i]=dp[i-1]. + +如果取第i种spell,那么保底就是仅取第i种药水的收益。其次我们查看spell[i-1]是否与spell[i]的差值在2之外,如果是的话,那么dp[i]就可以在dp[i-1]的基础上加上所有属于spell[i]的power。如果不是的话,我们往前查看spell[i-2]与spell[i]的差值是否在2之外,如果是的话,那么dp[i]就可以在dp[i-2]的基础上加上所有属于spell[i]的power。如果再不是的话,那么dp[i]可以直接在dp[i-3]的基础上加上所有属于spell[i]的power,这是因为spell数值彼此不同,spell[i-3]和spell[i]的差值必然大于2. 最终答案返回dp[n-1]即可。 From 4c4691355fc8e55d2a7c65c20c7ab4a081c5c311 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 01:05:18 -0700 Subject: [PATCH 2585/2729] Update 3186.Maximum-Total-Damage-With-Spell-Casting.cpp --- ...aximum-Total-Damage-With-Spell-Casting.cpp | 49 +++++++++---------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp index 0726a6a68..2ef62fec1 100644 --- a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp +++ b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp @@ -1,37 +1,34 @@ -using LL = long long; class Solution { public: long long maximumTotalDamage(vector& power) { - mapp; + mapMap; for (int x: power) - p[x]++; - - vector>arr(p.begin(), p.end()); - - vectordp(arr.size()); - - LL ret = 0; - for (int i=0; i>spell(Map.begin(), Map.end()); + + vectordp(spell.size()); + + for (int i=0; i=1) ans = max(ans, dp[i-1]); - - if (i>=1 && arr[i-1].first=2 && arr[i-2].first=3 && arr[i-3].first=1) dp[i] = max(dp[i], dp[i-1]); + + // pick the i-th spell along with previous ones + if (i>=1 && p - spell[i-1].first > 2) + dp[i] = max(dp[i], dp[i-1] + p * count); + else if (i>=2 && p - spell[i-2].first > 2) + dp[i] = max(dp[i], dp[i-2] + p * count); + else if (i>=3) + dp[i] = max(dp[i], dp[i-3] + p * count); } - - return ret; + + return dp[spell.size()-1]; } }; From d0a44d0f243f0b5292f43a7b563fe34dccd104c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 15:45:22 -0700 Subject: [PATCH 2586/2729] Update 1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp --- ...-Mysterious-Function-Closest-to-Target.cpp | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp b/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp index f5d4fac4f..d63214a53 100644 --- a/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp +++ b/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp @@ -1,18 +1,22 @@ class Solution { public: - int closestToTarget(vector& arr, int target) { - unordered_sets; + int closestToTarget(vector& arr, int target) + { + setSet, temp; int ret = INT_MAX; - for (int i=0; is2; - for (auto x: s) - s2.insert(x&arr[i]); - s2.insert(arr[i]); - for (auto x: s2) - ret = min(ret, abs(x-target)); - s = s2; + for (auto y: Set) + temp.insert(y&x); + temp.insert(x); + + for (int y: temp) + ret = min(ret, abs(y-target)); + + Set = temp; + temp.clear(); } + return ret; } }; From 917361117e4dec76ce8403241c863b5c8231b033 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:21:45 -0700 Subject: [PATCH 2587/2729] Create 3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp --- ...er-of-Subarrays-With-AND-Value-of-K_v1.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp diff --git a/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp new file mode 100644 index 000000000..e961d8e17 --- /dev/null +++ b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + long long countSubarrays(vector& nums, int k) + { + map mp, temp; + long long ans = 0; + for(int x: nums) + { + for(auto& [k,v]: mp) + temp[k & x] += v; + temp[x]++; + + if(temp.find(k) != temp.end()) + ans += temp[k]; + + mp = temp; + temp.clear(); + } + return ans; + } +}; From c7ee3cb91c073440b5b2bba2547b55013189d535 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:22:30 -0700 Subject: [PATCH 2588/2729] Create 3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp --- ...er-of-Subarrays-With-AND-Value-of-K_v2.cpp | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp diff --git a/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp new file mode 100644 index 000000000..ba13f016e --- /dev/null +++ b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp @@ -0,0 +1,108 @@ +using LL = long long; +class SegmentTree { +private: + vector tree; + int n; + + void build(vector& nums, int node, int start, int end) + { + if (start == end) { + tree[node] = nums[start]; + } else { + int mid = (start + end) / 2; + build(nums, 2 * node, start, mid); + build(nums, 2 * node + 1, mid + 1, end); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } + } + + void update(int node, int start, int end, int L, int R, int val) + { + if (R < start || end < L) { + return; + } + if (L <= start && end <= R) { + tree[node] = val; + return; + } + int mid = (start + end) / 2; + update(2 * node, start, mid, L, R, val); + update(2 * node + 1, mid + 1, end, L, R, val); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } + + int query(int node, int start, int end, int L, int R) + { + if (R < start || end < L) { + return INT_MAX; // Identity for AND operation (all bits set) + } + if (L <= start && end <= R) { + return tree[node]; + } + int mid = (start + end) / 2; + int leftAnd = query(2 * node, start, mid, L, R); + int rightAnd = query(2 * node + 1, mid + 1, end, L, R); + return leftAnd & rightAnd; + } + +public: + SegmentTree(vector& nums) { + n = nums.size(); + tree.resize(4 * n, 0); + build(nums, 1, 0, n - 1); + } + + void rangeUpdate(int L, int R, int val) { + update(1, 0, n - 1, L, R, val); + } + + int rangeAnd(int L, int R) { + return query(1, 0, n - 1, L, R); + } +}; + +class Solution { +public: + long long countSubarrays(vector& nums, int k) + { + int n = nums.size(); + SegmentTree segTree(nums); + LL ret = 0; + + for (int i=0; ik) + left = mid+1; + else + right = mid; + } + if (segTree.rangeAnd(i,left)==k) + a = left; + + left = i, right = n-1; + while (left < right) + { + int mid = right-(right-left)/2; + if (segTree.rangeAnd(i,mid) Date: Sat, 6 Jul 2024 18:25:55 -0700 Subject: [PATCH 2589/2729] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index b7a0ac25b..2768185be 100644 --- a/Readme.md +++ b/Readme.md @@ -358,7 +358,6 @@ [3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) [3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) [3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) -[3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) [3187.Peaks-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3187.Peaks-in-Array) (M+) #### [Binary Index Tree] @@ -969,12 +968,15 @@ [898.Bitwise-ORs-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays) (H-) [957.Prison-Cells-After-N-Days](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/957.Prison-Cells-After-N-Days) (H) 1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K (TBD) -[1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) [2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) [2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) [2802.Find-The-K-th-Lucky-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number) (M+) [2992.Number-of-Self-Divisible-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations) (M+) [3133.Minimum-Array-End](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3133.Minimum-Array-End) (M+) +* ``Prefix Hashing`` +[1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) +[3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) +[3209.Number-of-Subarrays-With-AND-Value-of-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From b8b791e310130e550c1c67ba4198e9a5301cac52 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:26:45 -0700 Subject: [PATCH 2590/2729] Rename Readme.md to Readme.md --- .../3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Segment_Tree => Bit_Manipulation}/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md (100%) diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md similarity index 100% rename from Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md rename to Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md From 3550fbafc05513d021f06c491aa402d6b46decf4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:27:27 -0700 Subject: [PATCH 2591/2729] Rename 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp to 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp --- .../3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Segment_Tree => Bit_Manipulation}/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp (100%) diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp similarity index 100% rename from Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp rename to Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp From f06a9ecb6b160ba6175f9e87d635cff1dea6dbd1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:27:57 -0700 Subject: [PATCH 2592/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2768185be..21ef1b147 100644 --- a/Readme.md +++ b/Readme.md @@ -974,7 +974,7 @@ [2992.Number-of-Self-Divisible-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations) (M+) [3133.Minimum-Array-End](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3133.Minimum-Array-End) (M+) * ``Prefix Hashing`` -[1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) +[1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) [3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) [3209.Number-of-Subarrays-With-AND-Value-of-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K) (M+) * ``XOR`` From f134d1f258caced2352645759cbbaa758a76d7de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:40:35 -0700 Subject: [PATCH 2593/2729] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/Readme.md diff --git a/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/Readme.md b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/Readme.md new file mode 100644 index 000000000..f1f67033f --- /dev/null +++ b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/Readme.md @@ -0,0 +1,15 @@ +### 3209.Number-of-Subarrays-With-AND-Value-of-K + +#### 解法1 +关于bitwise AND subarray的一个套路:对于所有以nums[i]结尾的subarray,无论它最长有多少元素,这些subarray的bitwise AND的数值种类最多只有31种。 + +我们用一个map来存入所有以nums[i-1]结尾的subarray的bitwise AND,就可以更新得到所有以nums[i]结尾的subarray的bitwise AND,只需要将map里的元素都与nums[i]进行AND即可。操作的时间是常数o(31)。 + +由此我们可以得到任何以nums[i]结尾的subarray,查看里面有多少的数值是k即可。 + +类似的题目有1521和3171 + +#### 解法2 +我们可以构造一种线段树,可以高效得到任意区间的bitwise AND。 + +然后对于任意以nums[i]为开始的subarray,我们用线段树的query方法,可以用二分搜索,求得第一个bitwise AND是k的位置a,和最后一个bitwise AND是k的位置b。那么就有b-a+1个subarray满足条件。 From a5dc2090ee606b7f8a45cfe3c6fdd270cfbe935d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:41:52 -0700 Subject: [PATCH 2594/2729] Rename 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp to 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp --- ...pp => 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/{3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp => 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp} (100%) diff --git a/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp similarity index 100% rename from Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp rename to Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp From 24336174f48650df6387ad97074142afd14d8ade Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:46:03 -0700 Subject: [PATCH 2595/2729] Create 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp --- ...array-With-Bitwise-AND-Closest-to-K_v1.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp diff --git a/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp new file mode 100644 index 000000000..2793c6d98 --- /dev/null +++ b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minimumDifference(vector& nums, int k) + { + unordered_setSet, temp; + int ret = INT_MAX; + for (int x: nums) + { + for (int y: Set) + temp.insert(y | x); + temp.insert(x); + + for (int y: temp) + ret = min(ret, abs(y-k)); + + Set = temp; + temp.clear(); + } + return ret; + } +}; From c2ca74afda385801bf42886a5f9022d045310b34 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:50:32 -0700 Subject: [PATCH 2596/2729] Update Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md index b15e631d1..7e1fc6959 100644 --- a/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md +++ b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md @@ -1,5 +1,15 @@ ### 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K +#### 解法1 +此题和1521几乎一样。 + +关于bitwise AND subarray的一个套路:对于所有以nums[i]结尾的subarray,无论它最长有多少元素,这些subarray的bitwise OR的数值种类最多只有31种。 + +我们用一个set来存入所有以nums[i-1]结尾的subarray的bitwise OR,就可以更新得到所有以nums[i]结尾的subarray的bitwise OR,只需要将set里的元素都与nums[i]进行OR即可。操作的时间是常数o(31)。 + +由此我们可以得到任何以nums[i]结尾的subarray,查看里面哪些数值最接近k。 + +#### 解法2 暴力解法的时间复杂度是o(N^2),即枚举所有的subarray。我们发现一旦确定了subarray的首元素,在移动尾指针的时候,bitwsie AND的值是单调递减的。所以我们很容易想到用二分的方法来确定答案最接近k的右端点。这就需要我们提前知道任何两点之间的区间bitwise AND的值。这个需求显然与求任意区间内的range sum一样,用线段树可以解决。 所以本题是先写好查询区间和“bitwise AND”的线段树模板。然后暴力枚举subarray的首元素i,再大于等于i处用二分寻找右端点位置j,使得区间和最接近k。 From dfb91179e867a8dbc5340075c2b912e6155ce077 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 20:26:58 -0700 Subject: [PATCH 2597/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 21ef1b147..75eda25ec 100644 --- a/Readme.md +++ b/Readme.md @@ -975,7 +975,7 @@ [3133.Minimum-Array-End](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3133.Minimum-Array-End) (M+) * ``Prefix Hashing`` [1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) -[3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) +[3171.Find-Subarray-With-Bitwise-OR-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) [3209.Number-of-Subarrays-With-AND-Value-of-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) From b0a362c0cb71f7bb5b3fbb40ee3e61d10787c914 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 Jul 2024 01:17:17 -0700 Subject: [PATCH 2598/2729] Create 3213.Construct-String-with-Minimum-Cost.cpp --- ...213.Construct-String-with-Minimum-Cost.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp diff --git a/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp b/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp new file mode 100644 index 000000000..71fc75c63 --- /dev/null +++ b/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp @@ -0,0 +1,62 @@ +class TrieNode +{ + public: + TrieNode* next[26]; + int cost; + TrieNode() + { + for (int i=0; i<26; i++) + next[i] = NULL; + cost = -1; + } +}; + +class Solution { + TrieNode* root = new TrieNode(); + vectormemo; +public: + int minimumCost(string target, vector& words, vector& costs) + { + memo = vector(target.size(), -1); + + for (int i=0; inext[ch-'a']==NULL) + node->next[ch-'a'] = new TrieNode(); + node = node->next[ch-'a']; + } + if (node->cost==-1) + node->cost = costs[i]; + else + node->cost = min(node->cost, costs[i]); + } + + int ret = dfs(target, 0); + if (ret == INT_MAX/2) return -1; + else return ret; + } + + int dfs(string& target, int cur) + { + if (cur==target.size()) return 0; + if (memo[cur] != -1) return memo[cur]; + + int ans = INT_MAX/2; + TrieNode* node = root; + for (int i=cur; inext[target[i]-'a']==NULL) + break; + node = node->next[target[i]-'a']; + if (node->cost!=-1) + ans = min(ans, node->cost + dfs(target, i+1)); + } + + memo[cur] = ans; + + return ans; + } +}; From f9bae67e31f8fc097a7abd809afc2960477eff6f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 Jul 2024 01:20:01 -0700 Subject: [PATCH 2599/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 75eda25ec..461d1b8f9 100644 --- a/Readme.md +++ b/Readme.md @@ -569,6 +569,7 @@ [1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) [2741.Special-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2741.Special-Permutations) (M+) [2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) +[3213.Construct-String-with-Minimum-Cost](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3213.Construct-String-with-Minimum-Cost) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) [1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) From 77fb1464e54e93834db8a4c43954597e7bd0d7b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 Jul 2024 01:29:41 -0700 Subject: [PATCH 2600/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 DFS/3213.Construct-String-with-Minimum-Cost/Readme.md diff --git a/DFS/3213.Construct-String-with-Minimum-Cost/Readme.md b/DFS/3213.Construct-String-with-Minimum-Cost/Readme.md new file mode 100644 index 000000000..1efcc2929 --- /dev/null +++ b/DFS/3213.Construct-String-with-Minimum-Cost/Readme.md @@ -0,0 +1,13 @@ +### 3213.Construct-String-with-Minimum-Cost + +此题似乎并没有什么特别好的办法。似乎只能暴力搜索,穷举target里的每一段是否适配某些word。 + +为了高效判定一段字符串是否出现在某些给定的words里,显然我们会先将所有word构造成一棵字典树。将word加入字典树的时候,记得在结尾节点附上该word的cost。如果有多个相同的word,我们只保留最小的cost。 + +我们定义dfs(i)表示target从位置i开始到结尾这段后缀成功分解所能得到的最小代价。我们就有: +```cpp +dfs(i) = min{cost of target[i:j] + dfs(j+1)}; for (int j=i; j Date: Sun, 14 Jul 2024 22:19:56 -0700 Subject: [PATCH 2601/2729] Create 3219.Minimum-Cost-for-Cutting-Cake-II.cpp --- .../3219.Minimum-Cost-for-Cutting-Cake-II.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/3219.Minimum-Cost-for-Cutting-Cake-II.cpp diff --git a/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/3219.Minimum-Cost-for-Cutting-Cake-II.cpp b/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/3219.Minimum-Cost-for-Cutting-Cake-II.cpp new file mode 100644 index 000000000..98acd52a6 --- /dev/null +++ b/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/3219.Minimum-Cost-for-Cutting-Cake-II.cpp @@ -0,0 +1,37 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(int m, int n, vector& h, vector& v) + { + sort(h.rbegin(), h.rend()); + sort(v.rbegin(), v.rend()); + + LL i=0, j=0; + LL ret = 0; + while (iv[j]) + { + ret += h[i]*(j+1); + i++; + } + else + { + ret += v[j]*(i+1); + j++; + } + } + while (i Date: Sun, 14 Jul 2024 23:34:40 -0700 Subject: [PATCH 2602/2729] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/Readme.md diff --git a/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/Readme.md b/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/Readme.md new file mode 100644 index 000000000..b2ac8cb16 --- /dev/null +++ b/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/Readme.md @@ -0,0 +1,19 @@ +### 3219.Minimum-Cost-for-Cutting-Cake-II + +我们首先考虑,在所有的横切位置里面,我们会如何排序。显然,我们会优先切cost大的横切位置。因为越靠后进行的横切位置,由于中间可能隔着若干竖切,导致在该位置可能需要更多次的横切操作。所以将单次横切cost最大的放在前面,是最合算的。 + +同理,在所有的竖切位置里面,我们会优先选择单次操作cost大的。 + +接下来考虑,一个横切与一个纵切位置里相比,我们优先选择哪个。假设此时,横向已经分为了i块,纵向已经分为了j块,每个方向上都是相对于原始大小“一切到底”。我们很容易分析得到,如果方案1是先横切再竖切,引入的代价是`costH*j + costV*(i+1)`. 反之方案2先竖切再横切的话,引入的代价是`costV*i + costH*(j+1)`. 比较一下,当且仅当`costH > costV`的时候,方案1更优。 + +综上,我们可以得到一个推测的结论:我们只需要将所有横切与纵切的位置按照cost从大到小排序、依次切割并且“一切到底”,这样得到的总代价最小。 + +上述结论有一个重要的前提,就是每刀都是一切到底。那么是否存在不“一切到底”反而更优的情况呢?考虑下面 +``` + _________C____ +A |_____|B | + | | | + |_____|______| + D +``` +假设按照排序后的cost,第一刀是竖切,第二刀是横切AB。那么是否该将右半边也横切掉呢?我们的顾虑是,如果在右半边存在一个竖切的位置CD,那么AB一切到底会引入两倍的竖切CD。而如果先切CD,再切AB的延长线,那么我们引入的代价是CD+AB*2. 事实上,从之前的排序过程中我们已经知道AB的代价大于CD,所以后者的方案是不如前者的。因此,我们在按照cost顺次执行切割的时候都会“一切到底”。 From 9b46c0c50fd4e840be6e0cd908641a71002c72a8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jul 2024 23:35:21 -0700 Subject: [PATCH 2603/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 461d1b8f9..889c4efd2 100644 --- a/Readme.md +++ b/Readme.md @@ -1363,7 +1363,8 @@ [2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) [2868.The-Wording-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2868.The-Wording-Game) (M) [2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) -[3022.Minimize-OR-of-Remaining-Elements-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations) (H) +[3022.Minimize-OR-of-Remaining-Elements-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations) (H) +[3219.Minimum-Cost-for-Cutting-Cake-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II) (H) * ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) From 863626f86b3a536f2dd1c20e60dd65607f31f6c6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 30 Jul 2024 23:50:04 -0700 Subject: [PATCH 2604/2729] Create 3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp --- ...umber-of-Substrings-With-Dominant-Ones.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp diff --git a/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp new file mode 100644 index 000000000..12b6b2305 --- /dev/null +++ b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int numberOfSubstrings(string s) + { + int n = s.size(); + + vectorright = computeRightArray(s); + int ret = 0; + for (int len = 1; len <= 200; len++) + { + int j = 0, count = 0; + for (int i=0; i= count*count) + { + int extra = right[j-1] - max(0, count*count-have); + ret += max(extra+1, 0); + } + + count -= (s[i]=='0'); + } + } + + for (int i=0; i computeRightArray(const std::string& s) + { + int n = s.length(); + std::vector right(n, 0); + + for (int i = n-2; i >=0; i--) { + if (s[i + 1] == '1') { + right[i] = right[i + 1] + 1; + } + } + + return right; + } +}; From 17561f6e0a12ba10ad384b4be110123c8fc6cf47 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 30 Jul 2024 23:50:31 -0700 Subject: [PATCH 2605/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 889c4efd2..2f50026bd 100644 --- a/Readme.md +++ b/Readme.md @@ -56,6 +56,7 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) +[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From f56f385b1b5bd7550c9301babdbb0d3e9b671d26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 Jul 2024 00:11:20 -0700 Subject: [PATCH 2606/2729] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/Readme.md diff --git a/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/Readme.md b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/Readme.md new file mode 100644 index 000000000..d8f3da598 --- /dev/null +++ b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/Readme.md @@ -0,0 +1,13 @@ +### 3234.Count-the-Number-of-Substrings-With-Dominant-Ones + +对于substring,我们第一个想法是考虑前缀之差。假设以i为结尾的前缀里有x个1和y个0,那么我们希望找一个已有的前缀位置j(其包含p个1和q个0),需要满足`(x-p)>=(y-q)^2`. 由于这其中包含了平方关系,很难构造hash找出符合条件的j。 + +这是我们再审查这个平方关系。一般情况下,这意味着substring里的1要比0多很多。比如说有10个一,那么就需要有100个零。考虑到s的总长度也不过是4e4,这就意味着其实我们寻找的字符串里最多也就200个零,再配上40000个一就到达极限了。 + +所以此时我们的方案几乎就呼之欲出了,那就是穷举包含零的个数为1到200的substring。我们遍历长度m=1,...,200,对于每个固定的m,通过一遍单调的双指针移动就可以把所有包含零的个数是m的滑窗都找出来。时间复杂度是o(200n),符合题意。 + +假设找到一段滑窗,里面包含了m个零,那么该如何计数以它为基础的符合条件的substring呢?一种想法是,假设确定了最外边的两个0的位置i和j,那么我们可以自由调配i左边的1的个数、以及j右边的1的个数,但要使得区间内的0(个数已经固定)与1的个数符合条件。这样的方法比较复杂。 + +其实有一种更简单的做法,那么穷举substring的左边界i(不管是0还是1),通过上述的滑窗准则,找到对应右边界的j使得[i:j]恰好有m个0,另外有t个1. 那么我们可以知道,至少还需要`m*m-t`个1,这就需要从s[j]右边的若干个连续的1里面取。假设s[j]右边有连续k个1,那么超过`m*m-t`的部分我们可以自由选择,故有`k-(m*m-t)+1`种合法的substring右边界。 + +另外,对于m=0的特殊情况我们要单独处理。即substring里只含有1不含有0. 那么任意以1为左边界的substring,它的右边界可以包含任意数目的连续的1. From fe1367b01daba9d0ded5346039422d21bd236a6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 Jul 2024 00:13:39 -0700 Subject: [PATCH 2607/2729] Update 3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp --- ....Count-the-Number-of-Substrings-With-Dominant-Ones.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp index 12b6b2305..1366613b4 100644 --- a/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp +++ b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp @@ -6,17 +6,17 @@ class Solution { vectorright = computeRightArray(s); int ret = 0; - for (int len = 1; len <= 200; len++) + for (int m = 1; m <= 200; m++) { int j = 0, count = 0; for (int i=0; i= count*count) { @@ -39,7 +39,7 @@ class Solution { std::vector computeRightArray(const std::string& s) { - int n = s.length(); + int n = s.mgth(); std::vector right(n, 0); for (int i = n-2; i >=0; i--) { From 96cc4e33a4f0919f031d8b654113fe6d114c608e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Aug 2024 00:04:28 -0700 Subject: [PATCH 2608/2729] move 1526 --- ...r-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp | 0 ...Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp | 0 .../Readme.md | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Others}/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp (100%) rename {Greedy => Others}/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp (100%) rename {Greedy => Others}/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md (100%) diff --git a/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp b/Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp similarity index 100% rename from Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp rename to Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp diff --git a/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp b/Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp similarity index 100% rename from Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp rename to Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp diff --git a/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md b/Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md similarity index 100% rename from Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md rename to Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md From 2c42791cbd4b9c6af79121cc6586fddb775d7720 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Aug 2024 00:05:46 -0700 Subject: [PATCH 2609/2729] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 2f50026bd..808181805 100644 --- a/Readme.md +++ b/Readme.md @@ -1319,7 +1319,6 @@ [1354.Construct-Target-Array-With-Multiple-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1354.Construct-Target-Array-With-Multiple-Sums) (H-) [1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K) (M+) [1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits) (H) -[1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1535.Find-the-Winner-of-an-Array-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1535.Find-the-Winner-of-an-Array-Game) (M+) [1536.Minimum-Swaps-to-Arrange-a-Binary-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1536.Minimum-Swaps-to-Arrange-a-Binary-Grid) (H-) [1540.Can-Convert-String-in-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1540.Can-Convert-String-in-K-Moves) (M+) @@ -1576,7 +1575,8 @@ [798.Smallest-Rotation-with-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/798.Smallest-Rotation-with-Highest-Score) (H) [995.Minimum-Number-of-K-Consecutive-Bit-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Others/995.Minimum-Number-of-K-Consecutive-Bit-Flips) (H-) [1094.Car-Pooling](https://github.com/wisdompeak/LeetCode/tree/master/Others/1094.Car-Pooling) (E) -[1109.Corporate-Flight-Bookings](https://github.com/wisdompeak/LeetCode/tree/master/Others/1109.Corporate-Flight-Bookings) (M) +[1109.Corporate-Flight-Bookings](https://github.com/wisdompeak/LeetCode/tree/master/Others/1109.Corporate-Flight-Bookings) (M) +[1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1589.Maximum-Sum-Obtained-of-Any-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Others/1589.Maximum-Sum-Obtained-of-Any-Permutation) (M) [1674.Minimum-Moves-to-Make-Array-Complementary](https://github.com/wisdompeak/LeetCode/tree/master/Others/1674.Minimum-Moves-to-Make-Array-Complementary) (H) [1871.Jump-Game-VII](https://github.com/wisdompeak/LeetCode/tree/master/Others/1871.Jump-Game-VII) (M+) From a6f5fb2b6c9c645954e8d9e16562a4be08f214df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Aug 2024 00:27:19 -0700 Subject: [PATCH 2610/2729] Update 213.House-Robber-II_v2.cpp --- .../213.House-Robber-II/213.House-Robber-II_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/213.House-Robber-II/213.House-Robber-II_v2.cpp b/Dynamic_Programming/213.House-Robber-II/213.House-Robber-II_v2.cpp index aab193f61..cc8e31550 100644 --- a/Dynamic_Programming/213.House-Robber-II/213.House-Robber-II_v2.cpp +++ b/Dynamic_Programming/213.House-Robber-II/213.House-Robber-II_v2.cpp @@ -17,6 +17,6 @@ class Solution { dp[i][j] = max(nums[i]+ ((i+2>j)?0:dp[i+2][j]), dp[i+1][j]); } - return max(nums[0]+((2>n-2)?0:dp[2][n-2]), dp[1][n-1]); + return std::max(dp[0][n-2], dp[1][n-1]); } }; From 811f5df556b8d2ccf6ff09be2c52653517a8a971 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Aug 2024 00:31:44 -0700 Subject: [PATCH 2611/2729] Update 1191.K-Concatenation-Maximum-Sum.cpp --- .../1191.K-Concatenation-Maximum-Sum.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Greedy/1191.K-Concatenation-Maximum-Sum/1191.K-Concatenation-Maximum-Sum.cpp b/Greedy/1191.K-Concatenation-Maximum-Sum/1191.K-Concatenation-Maximum-Sum.cpp index 56df9e995..bc76f703f 100644 --- a/Greedy/1191.K-Concatenation-Maximum-Sum/1191.K-Concatenation-Maximum-Sum.cpp +++ b/Greedy/1191.K-Concatenation-Maximum-Sum/1191.K-Concatenation-Maximum-Sum.cpp @@ -20,7 +20,7 @@ class Solution { if (arrSum < 0) return maxSubArrSum(arr)%M; else - return (maxSubArrSum(arr) + ((long)k - 2) * arrSum % M)%M; + return (maxSubArrSum(arr) + ((long)k - 2) * arrSum)%M; } long maxSubArrSum(vectorarr) @@ -31,7 +31,6 @@ class Solution { for (int i = 0; i < arr.size(); i++) { max_ending_here = max_ending_here + arr[i]; - max_ending_here %= M; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) From db621e2ffd42be3647bef40d91764bd5dc87cd31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 08:37:27 -0700 Subject: [PATCH 2612/2729] Create 3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp --- ...ubstrings-That-Satisfy K-Constraint-II.cpp | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp b/Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp new file mode 100644 index 000000000..d16ea93a4 --- /dev/null +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp @@ -0,0 +1,156 @@ +using LL = long long; +LL M = 1e9+7; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + LL delta; + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info += delta * (left->end - left->start + 1); + left->delta += delta; + right->info += delta * (right->end - right->start + 1); + right->delta += delta; + left->tag = 1; + right->tag = 1; + tag = 0; + delta = 0; + } + } + + void updateRangeBy(int a, int b, int val) // increase range [a,b] by val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info += val * (end-start+1); + delta += val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRangeBy(a, b, val+delta); + right->updateRangeBy(a, b, val+delta); + delta = 0; + tag = 0; + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + + +class Solution { +public: + vector countKConstraintSubstrings(string s, int k, vector>& queries) + { + int n = s.size(); + vectorlen(n); + int j = 0; + int count0=0, count1=0; + for (int i=0; irets(queries.size()); + SegTreeNode* root = new SegTreeNode(0, n-1, 0); + + int i = n-1; + for (auto q: queries) + { + int a = q[0], b = q[1], idx=q[2]; + while (i>=a) + { + root->updateRangeBy(i, len[i], 1); + i--; + } + rets[idx] = root->queryRange(a,b); + } + + return rets; + } +}; From dd6bc033d48d857bca703d403c291c87a01bbe05 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 08:38:35 -0700 Subject: [PATCH 2613/2729] Rename 3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp to 3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp --- .../3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/{3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp => 3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp} (100%) diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp similarity index 100% rename from Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp rename to Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp From 5094287c37c442f23fbfbb5cdddf36e553c36fa4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 08:39:21 -0700 Subject: [PATCH 2614/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 808181805..cf50c2fd9 100644 --- a/Readme.md +++ b/Readme.md @@ -360,6 +360,7 @@ [3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) [3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) [3187.Peaks-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3187.Peaks-in-Array) (M+) +[3261.Count-Substrings-That-Satisfy-20K-Constraint-II](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II) (H-) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From f8ed840c054d255565dfaabb3ffaa14a83e4d03a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 18:27:38 -0700 Subject: [PATCH 2615/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md new file mode 100644 index 000000000..0a1f79945 --- /dev/null +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md @@ -0,0 +1,7 @@ +### 3261.Count-Substrings-That-Satisfy-K-Constraint-II + +假设以i作为左边界,那么我们容易得到最远的右边界j,使得[i:j]是最长的valid substring;并且以其中的任何一点作为右边界,都是valid substring. 然后发现,如果将左边界i往右移动一位,那么最远的右边界位置j不然是单调向右移动的。所以我们可以用双指针的方法,求得所有的len[i],表示以i作为左边界,那么我们得到最远的valid substring的右边界。 + +那么对于一个query而言,如何求[l,r]内所有的valid substring呢?考虑到Q的数量很大,我们很容易想到线段树,希望能用log的时间来解决一个query(计算一个区间内的substring之和)。但是一个valid sbustring是需要用两个端点来表示的,这似乎和线段树的应用有些不同。于是我们想到,能否在线段树里用一个点来表示一个substring?于是我们可以尝试将所有的valid substring只用其左端点来表示。那么线段树就可以很方便地求出所有左端点落入[l,r]内valid substring的个数。 + +但是这里就有个问题,[l,r]内所有的valid substring,并不等同于左端点落入[l,r]内valid substring。 From 2681038135e407adb36560458643168c49e7ff3e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 22:38:25 -0700 Subject: [PATCH 2616/2729] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md index 0a1f79945..814c5378a 100644 --- a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md @@ -2,6 +2,6 @@ 假设以i作为左边界,那么我们容易得到最远的右边界j,使得[i:j]是最长的valid substring;并且以其中的任何一点作为右边界,都是valid substring. 然后发现,如果将左边界i往右移动一位,那么最远的右边界位置j不然是单调向右移动的。所以我们可以用双指针的方法,求得所有的len[i],表示以i作为左边界,那么我们得到最远的valid substring的右边界。 -那么对于一个query而言,如何求[l,r]内所有的valid substring呢?考虑到Q的数量很大,我们很容易想到线段树,希望能用log的时间来解决一个query(计算一个区间内的substring之和)。但是一个valid sbustring是需要用两个端点来表示的,这似乎和线段树的应用有些不同。于是我们想到,能否在线段树里用一个点来表示一个substring?于是我们可以尝试将所有的valid substring只用其左端点来表示。那么线段树就可以很方便地求出所有左端点落入[l,r]内valid substring的个数。 +那么对于一个query而言,如何求[l,r]内所有的valid substring呢?考虑到Q的数量很大,我们很容易想到线段树,希望能用log的时间来解决一个query(计算一个区间内的substring之和)。但是一个valid sbustring是需要用两个端点来表示的,这似乎和线段树的应用有些不同。于是我们想到,能否在线段树里用一个点来表示一个substring?于是我们可以尝试将所有的valid substring只用其右端点来表示。举个例子,对于以i为左端点的valid subtring,根据其右端点的位置,我们在i,i+1,i+2,...,len[i]都可以记录+1;也就是说,在线段树上我们可以对[i,len[i]]这段区间整体都加1. 此外,线段树就可以很方便地query所有右端点落入[l,r]内valid substring的个数。 -但是这里就有个问题,[l,r]内所有的valid substring,并不等同于左端点落入[l,r]内valid substring。 +但是这里就有个问题,[l,r]内的valid substring,并不等同于右端点落入[l,r]内valid substring。对于后者而言,有些substring的左端点在l的左边,这是需要排除掉的。我们该如何去掉那些左端点在l左边的那些substring呢?在线段树的操作里,似乎并没有什么好办法,但是有一个巧妙的策略:那就是不把“那些左端点位于l左边的那些substring”收录进线段树。这就提示我们可以将queries按照左端点倒序排列依次处理。对于[l,r]这个query而言,我们(只)收录进所有左端点大于等于l的那些substring。此时在线段树内查询[l,r]的区间和,就代表了所有右端点在[l,r]范围内的valid substring,同时这些string的左端点都不会小于l。 From 7de25289506aa7fb46b594bab7baec5ea58d3873 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Aug 2024 01:09:39 -0700 Subject: [PATCH 2617/2729] Update 3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp --- .../3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp index d16ea93a4..6a6521eeb 100644 --- a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp @@ -115,7 +115,7 @@ class Solution { vector countKConstraintSubstrings(string s, int k, vector>& queries) { int n = s.size(); - vectorlen(n); + vectorend(n); int j = 0; int count0=0, count1=0; for (int i=0; i=a) { - root->updateRangeBy(i, len[i], 1); + root->updateRangeBy(i, end[i], 1); i--; } rets[idx] = root->queryRange(a,b); From 9070c047bf7d6e5a3b03d6c4d2e2d2fea3c6f7a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Sep 2024 21:54:28 -0700 Subject: [PATCH 2618/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md index 814c5378a..fa95f795d 100644 --- a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md @@ -1,6 +1,6 @@ ### 3261.Count-Substrings-That-Satisfy-K-Constraint-II -假设以i作为左边界,那么我们容易得到最远的右边界j,使得[i:j]是最长的valid substring;并且以其中的任何一点作为右边界,都是valid substring. 然后发现,如果将左边界i往右移动一位,那么最远的右边界位置j不然是单调向右移动的。所以我们可以用双指针的方法,求得所有的len[i],表示以i作为左边界,那么我们得到最远的valid substring的右边界。 +假设以i作为左边界,那么我们容易得到最远的右边界j,使得[i:j]是最长的valid substring;并且以其中的任何一点作为右边界,都是valid substring. 然后发现,如果将左边界i往右移动一位,那么最远的右边界位置j必然是单调向右移动的。所以我们可以用双指针的方法,求得所有的len[i],表示以i作为左边界,那么我们得到最远的valid substring的右边界。 那么对于一个query而言,如何求[l,r]内所有的valid substring呢?考虑到Q的数量很大,我们很容易想到线段树,希望能用log的时间来解决一个query(计算一个区间内的substring之和)。但是一个valid sbustring是需要用两个端点来表示的,这似乎和线段树的应用有些不同。于是我们想到,能否在线段树里用一个点来表示一个substring?于是我们可以尝试将所有的valid substring只用其右端点来表示。举个例子,对于以i为左端点的valid subtring,根据其右端点的位置,我们在i,i+1,i+2,...,len[i]都可以记录+1;也就是说,在线段树上我们可以对[i,len[i]]这段区间整体都加1. 此外,线段树就可以很方便地query所有右端点落入[l,r]内valid substring的个数。 From ab27ef51c5bb9a15e8d3eb516e4046ba471b51a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Sep 2024 23:56:38 -0700 Subject: [PATCH 2619/2729] Create 3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp --- ...e-Rearranged-to-Contain-a-String-II_v1.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp diff --git a/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp new file mode 100644 index 000000000..7113126aa --- /dev/null +++ b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long validSubstringCount(string word1, string word2) + { + vectortarget(26); + for (auto ch: word2) + target[ch-'a']++; + + vectorcount(26); + int j = 0; + LL ret = 0; + + int n = word1.size(); + for (int i=0; i&count, vector&target) + { + for (int i=0; i<26; i++) + if (count[i] Date: Tue, 24 Sep 2024 00:00:11 -0700 Subject: [PATCH 2620/2729] Create 3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp --- ...e-Rearranged-to-Contain-a-String-II_v2.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp diff --git a/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp new file mode 100644 index 000000000..ff30cde23 --- /dev/null +++ b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long validSubstringCount(string word1, string word2) + { + vectortarget(26); + for (auto ch: word2) + target[ch-'a']++; + int T = 0; + for (int i=0; i<26; i++) + if (target[i]!=0) T++; + + vectorcount(26); + int j = 0; + LL ret = 0; + + int t = 0; + int n = word1.size(); + for (int i=0; i Date: Tue, 24 Sep 2024 00:00:50 -0700 Subject: [PATCH 2621/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cf50c2fd9..53c320cfa 100644 --- a/Readme.md +++ b/Readme.md @@ -56,7 +56,8 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) -[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) +[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) +[3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 1cba110044d232bf91d739abf11c6c6dad044317 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Sep 2024 00:01:09 -0700 Subject: [PATCH 2622/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 53c320cfa..8dfbe3a42 100644 --- a/Readme.md +++ b/Readme.md @@ -56,7 +56,7 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) -[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) +[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) [3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) From 9221d343e3bf7e8555bcb4ed0235b6e214961b3b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Sep 2024 00:12:55 -0700 Subject: [PATCH 2623/2729] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/Readme.md diff --git a/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/Readme.md b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/Readme.md new file mode 100644 index 000000000..154b49c61 --- /dev/null +++ b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/Readme.md @@ -0,0 +1,19 @@ +### 3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II + +#### 解法1 +本题就是问有多少个子区间,里面包含了word2的所有字符。 + +假设固定了一个滑窗的左端点i,我们试图寻找符合条件的右端点j。不难发现,只需要单调增加j就可以找到一个最短的区间,之后右端点从j到n-1变化都是可以的,故总计数增加`n-j`. 然后我们思考当左端点变成i+1时,我们相比之前减少了一个字符,那么右端点j的位置如何变化?显然j必然是右移才行。由此发现,i和j都只需要单调右移,就可以找遍所有符合条件的子区间。故快慢指针即可解此题。 + +我们需要一个辅助函数,判断一个区间内的字符是否符合条件。因为本题只有小写因为字母,所以只需要开一个长度为26的计数器,存储滑窗里各个字符的频次,与word2的频次逐一比对即可。 + +这样的做法时间复杂度是o(26n). + +#### 解法2 +辅助函数可以进一步优化。事实上,我们不需要将26个字符的频次逐一比对。我们只需要再加一个计数器t,持续更新迄今为止有多少字符的频次已经满足要求。更新的规则是: +1. 当word[j]加入区间时,如果`count[word[j]]==target[word[j]]`,那么t可以增一。 +2. 当word[i]移出区间时,如果`count[word[i]]==target[word[i]]-1`,那么t可以增一。 +其他情况下t都不需要变化。当任何时候,如果t等于word2的字符种类数T时,就一定意味着区间内的所有字符频次都符合要求。 + +这样的做法时间复杂度是o(n). + From 799f902b20e04d2b45210bcbc579bc682a6c34c8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 26 Sep 2024 23:29:36 -0700 Subject: [PATCH 2624/2729] Update Readme.md --- Stack/032.Longest-Valid-Parentheses/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/032.Longest-Valid-Parentheses/Readme.md b/Stack/032.Longest-Valid-Parentheses/Readme.md index b7595b214..8946d5401 100644 --- a/Stack/032.Longest-Valid-Parentheses/Readme.md +++ b/Stack/032.Longest-Valid-Parentheses/Readme.md @@ -8,6 +8,6 @@ 由此,if possible,我们可以为每一个右括号i,寻找与之匹配的左括号j的位置(即离它左边最近的、可以匹配的左括号)。并且我们可以确定,[j:i]这对括号内的字符肯定也是已经正确匹配了的。 -但是[j:i]就一定是以j结尾的最长的合法字串了吗?不一定。此时观察,将栈顶元素j退栈“对消”之后,此时新的栈顶元素对应的位置并不一定是与j相邻的。中间这段“空隙”意味着什么呢?对,这段“空隙”是之前已经退栈了的其他合法字符串。所以我们可以在区间[j:i]的左边再加上这段长度。因此,真正的“以j结尾的最长的合法字串”的长度是```i - Stack.top()```。注意stack存放的是所有字符的index。 +但是[j:i]就一定是以i结尾的最长的合法字串了吗?不一定。此时观察,将栈顶元素j退栈“对消”之后,此时新的栈顶元素对应的位置并不一定是与j相邻的。中间这段“空隙”意味着什么呢?对,这段“空隙”是之前已经退栈了的其他合法字符串。所以我们可以在区间[j:i]的左边再加上这段长度。因此,真正的“以j结尾的最长的合法字串”的长度是```i - Stack.top()```。注意stack存放的是所有字符的index。 [Leetcode Link](https://leetcode.com/problems/longest-valid-parentheses) From a197f04db7872e922a4b9426ca551bb2521a9278 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:30:25 -0700 Subject: [PATCH 2625/2729] Create 1545.Find-Kth-Bit-in-Nth-Binary-String.cpp --- ...1545.Find-Kth-Bit-in-Nth-Binary-String.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String/1545.Find-Kth-Bit-in-Nth-Binary-String.cpp diff --git a/Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String/1545.Find-Kth-Bit-in-Nth-Binary-String.cpp b/Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String/1545.Find-Kth-Bit-in-Nth-Binary-String.cpp new file mode 100644 index 000000000..7cf549c8a --- /dev/null +++ b/Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String/1545.Find-Kth-Bit-in-Nth-Binary-String.cpp @@ -0,0 +1,28 @@ +class Solution { + vectorlen; +public: + char findKthBit(int n, int k) + { + len.resize(n+1); + len[1] = 1; + for (int i=2; i<=n; i++) + len[i] = len[i-1]*2+1; + + return dfs(n, k); + } + + char dfs(int n, int k) + { + if (n==1) return '0'; + if (k==len[n]/2+1) return '1'; + if (k Date: Sun, 29 Sep 2024 09:32:28 -0700 Subject: [PATCH 2626/2729] Create 3307.Find-the K-th-Character-in-String-Game-II.cpp --- ...d-the K-th-Character-in-String-Game-II.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp new file mode 100644 index 000000000..5bce51cfe --- /dev/null +++ b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp @@ -0,0 +1,31 @@ +using LL = long long; +class Solution { +public: + char kthCharacter(long long k, vector& operations) + { + LL n = 1; + int t = 0; + while (n=0; i--) + { + if (k>n/2) + { + if (operations[i]==0) + k = k-n/2; + else + { + k = k-n/2; + count++; + } + } + n/=2; + } + return 'a' + (count) % 26; + } +}; From fd96366ae328ca43a5f9649657764be6ce347b96 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:33:20 -0700 Subject: [PATCH 2627/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8dfbe3a42..7a954b505 100644 --- a/Readme.md +++ b/Readme.md @@ -1151,12 +1151,13 @@ [440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) -1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) +[1545.Find-Kth-Bit-in-Nth-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String) (M+) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) [2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) [2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) +[3307.Find-the%20K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the%20K-th-Character-in-String-Game-II) (M) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 9bc412bab76511ff17cba47c5bdd961638d10fc9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:38:09 -0700 Subject: [PATCH 2628/2729] Create Readme.md --- .../3307.Find-the K-th-Character-in-String-Game-II/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md new file mode 100644 index 000000000..685efefdb --- /dev/null +++ b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md @@ -0,0 +1,3 @@ +### 3307.Find-the K-th-Character-in-String-Game-II + +假设当前总共有n个字符,求其中的第k个。显然,如果k是在前n/2里,那么等效于求`dfs(n/2,k)`。如果是在后半部分,那么它其实是前半部分里第`k-n/2`个字符shift一位之后的结果,故等效于`dfs(n/2,k-n/2)+1`. 以此递归处理即可。时间就是logN. From 19bee901e120f3c18e1b4f7c4cbb372e71084633 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:40:32 -0700 Subject: [PATCH 2629/2729] Update Readme.md --- .../3307.Find-the K-th-Character-in-String-Game-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md index 685efefdb..ab90953fb 100644 --- a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md +++ b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md @@ -1,3 +1,3 @@ ### 3307.Find-the K-th-Character-in-String-Game-II -假设当前总共有n个字符,求其中的第k个。显然,如果k是在前n/2里,那么等效于求`dfs(n/2,k)`。如果是在后半部分,那么它其实是前半部分里第`k-n/2`个字符shift一位之后的结果,故等效于`dfs(n/2,k-n/2)+1`. 以此递归处理即可。时间就是logN. +假设当前总共有n个字符,求其中的第k个。显然,如果k是在前n/2里,那么等效于求`dfs(n/2,k)`。如果是在后半部分,那么它其实是前半部分里第`k-n/2`个字符shift零次或一次(取决于operation类型)之后的结果,即等效于`dfs(n/2,k-n/2)+1`. 以此递归处理即可。时间就是logN. From 0c51648986eff4f1cc57d42672801e712aae7b00 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:41:10 -0700 Subject: [PATCH 2630/2729] Update Readme.md --- .../3307.Find-the K-th-Character-in-String-Game-II/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md index ab90953fb..03d131228 100644 --- a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md +++ b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md @@ -1,3 +1,5 @@ ### 3307.Find-the K-th-Character-in-String-Game-II 假设当前总共有n个字符,求其中的第k个。显然,如果k是在前n/2里,那么等效于求`dfs(n/2,k)`。如果是在后半部分,那么它其实是前半部分里第`k-n/2`个字符shift零次或一次(取决于operation类型)之后的结果,即等效于`dfs(n/2,k-n/2)+1`. 以此递归处理即可。时间就是logN. + +此题类似 1545.Find-Kth-Bit-in-Nth-Binary-String From 4f2e603e032eb526c2fad3d8ceedd70ffae79f7e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:41:49 -0700 Subject: [PATCH 2631/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7a954b505..d06f5aba6 100644 --- a/Readme.md +++ b/Readme.md @@ -1157,7 +1157,7 @@ [2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) [2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) -[3307.Find-the%20K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the%20K-th-Character-in-String-Game-II) (M) +[3307.Find-the-K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the-K-th-Character-in-String-Game-II) (M) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From d0149bb452598fd12fc68269c967d948cdad0200 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:42:19 -0700 Subject: [PATCH 2632/2729] Rename Readme.md to Readme.md --- .../Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Recursion/{3307.Find-the K-th-Character-in-String-Game-II => 3307.Find-the-K-th-Character-in-String-Game-II}/Readme.md (100%) diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md b/Recursion/3307.Find-the-K-th-Character-in-String-Game-II/Readme.md similarity index 100% rename from Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md rename to Recursion/3307.Find-the-K-th-Character-in-String-Game-II/Readme.md From f21829d359b04f88ebc5a5bc98d5b78ddf1ebd71 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:43:10 -0700 Subject: [PATCH 2633/2729] Rename 3307.Find-the K-th-Character-in-String-Game-II.cpp to 3307.Find-the-K-th-Character-in-String-Game-II.cpp --- .../3307.Find-the-K-th-Character-in-String-Game-II.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Recursion/{3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp => 3307.Find-the-K-th-Character-in-String-Game-II/3307.Find-the-K-th-Character-in-String-Game-II.cpp} (100%) diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp b/Recursion/3307.Find-the-K-th-Character-in-String-Game-II/3307.Find-the-K-th-Character-in-String-Game-II.cpp similarity index 100% rename from Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp rename to Recursion/3307.Find-the-K-th-Character-in-String-Game-II/3307.Find-the-K-th-Character-in-String-Game-II.cpp From e221b7e4a98d502f19fe0667d039cf2115f3668f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 10:46:47 -0700 Subject: [PATCH 2634/2729] Create 3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp --- ...aining-Every-Vowel-and-K-Consonants-II.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp diff --git a/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp b/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp new file mode 100644 index 000000000..49b86eb96 --- /dev/null +++ b/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + long long countOfSubstrings(string word, int k) + { + int count0 = 0; + int count1 = 0; + int n = word.size(); + + unordered_setSet({'a','e','i','o','u'}); + unordered_mapMap; + + vectorconsecutive(n); + int c = 0; + for (int i=n-1; i>=0; i--) + { + if (Set.find(word[i])==Set.end()) + c = 0; + else + c++; + consecutive[i] = c; + } + + long long ret = 0; + int j = 0; + for (int i=0; i Date: Sun, 29 Sep 2024 10:47:47 -0700 Subject: [PATCH 2635/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d06f5aba6..62fc99052 100644 --- a/Readme.md +++ b/Readme.md @@ -57,7 +57,6 @@ [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) [3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) -[3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) @@ -67,6 +66,8 @@ [3134.Find-the-Median-of-the-Uniqueness-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array) (H-) [2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K) (M) [2537.Count-the-Number-of-Good-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays) (M+) +[3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) +[3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II) (H-) * ``Two pointers for two sequences`` [986.Interval-List-Intersections](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/986.Interval-List-Intersections) (M) [1229.Meeting-Scheduler](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1229.Meeting-Scheduler) (M+) From c18b3f0e36f7289ca4a4bb4b7ddff359627a32eb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 22:24:21 -0700 Subject: [PATCH 2636/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/Readme.md diff --git a/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/Readme.md b/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/Readme.md new file mode 100644 index 000000000..c639465ab --- /dev/null +++ b/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/Readme.md @@ -0,0 +1,9 @@ +### 3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II + +此题和`3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II`非常相似。 + +我们令count0统计元音的种类个数,count1统计辅音的字符个数。对于固定左端点i的区间而言,如果发现`count0<5 || count1=k`. 此时两种情况: +1. 如果count1>k,那么我们必然会尝试右移左端点i,因为再右移右端点j的话必然不会满足count1. +2. 如果count1==k,那么我们就找到了一组合法区间[i:j]。那么我们是否还有其他以i为左端点的合法区间呢?事实上,如果j右边有连续的元音出现的话,这些都是可以纳入合法区间的。所以我们可以提前计算一个数组A[k],记录k及k右边连续有多少个元音。这样答案就增加了`1+A[j+1]`个。 + +以上就考虑完了所有以i为左端点的情况。下一步就是将i右移一步,更新count0和count1,然后继续探索右端点即可。 From 67e24383ea7cfa517bcbdaea58017a495c8bc704 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 Dec 2024 22:44:15 -0800 Subject: [PATCH 2637/2729] Create 3388.Count-Beautiful-Splits-in-an-Array.cpp --- ...388.Count-Beautiful-Splits-in-an-Array.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 String/3388.Count-Beautiful-Splits-in-an-Array/3388.Count-Beautiful-Splits-in-an-Array.cpp diff --git a/String/3388.Count-Beautiful-Splits-in-an-Array/3388.Count-Beautiful-Splits-in-an-Array.cpp b/String/3388.Count-Beautiful-Splits-in-an-Array/3388.Count-Beautiful-Splits-in-an-Array.cpp new file mode 100644 index 000000000..87348ffea --- /dev/null +++ b/String/3388.Count-Beautiful-Splits-in-an-Array/3388.Count-Beautiful-Splits-in-an-Array.cpp @@ -0,0 +1,48 @@ +using LL = long long; + +class Solution { + const LL P = 53; + const LL M = 1e9 + 7; + + LL get_hash(const vector& prefix_hash, const vector& p_powers, int i, int j) + { + return (prefix_hash[j] - (prefix_hash[i-1] * p_powers[j-i+1]) % M + M) % M; + } + +public: + int beautifulSplits(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + int count = 0; + + vector prefix_hash(n+1, 0); + vector p_powers(n+1, 1); + + for (int i = 1; i <= n; i++) + { + prefix_hash[i] = (prefix_hash[i - 1] * P + nums[i]) % M; + p_powers[i] = (p_powers[i - 1] * P) % M; + } + + for (int i = 2; i < n; i++) + for (int j = i + 1; j <= n; j++) + { + LL nums1_hash = get_hash(prefix_hash, p_powers, 1, i-1); + LL nums2_hash = get_hash(prefix_hash, p_powers, i, j-1); + int len1 = i-1; + int len2 = j-i; + int len3 = n-j+1; + + int flag =0; + if ((len2>=len1) && nums1_hash == get_hash(prefix_hash, p_powers, i, i+len1-1)) + flag = 1; + + if (len3>=len2 && nums2_hash == get_hash(prefix_hash, p_powers, j, j+len2-1)) + flag = 1; + count += flag; + } + + return count; + } +}; From be2b53e8923a8d8f3b49e35c7717a7efa8e8adfd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 Dec 2024 22:45:06 -0800 Subject: [PATCH 2638/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 62fc99052..79882f603 100644 --- a/Readme.md +++ b/Readme.md @@ -1048,6 +1048,7 @@ [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) [2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) +[3388.Count-Beautiful-Splits-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/3388.Count-Beautiful-Splits-in-an-Array) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) From 3660f9028aebe1e25df38aedbbc524abdf24a64f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Dec 2024 00:22:21 -0800 Subject: [PATCH 2639/2729] Create Readme.md --- String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md diff --git a/String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md b/String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md new file mode 100644 index 000000000..5fe95028c --- /dev/null +++ b/String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md @@ -0,0 +1,8 @@ +### 3388.Count-Beautiful-Splits-in-an-Array + +根据n的数量级,考虑如果暴力枚举两处分界点的话,那么需要能以o(1)的时间判定一段subarray是否是另一段subarray的前缀。此时常见的方法只有rolling hash。事实上,每个nums[i]的数值有上限50,故可以类比于字符串的rolling hash,方法应该是可行的。 + +需要注意的几个细节: +1. 每个nums[i]的数值上限是50,故可以选取质数53作为进制。 +2. 一段区间的`hash[i:j] = prefix_hash[j] - prefix_hash[i-1] * power[j-i+1]`,同时取余的过程要始终保证是正数。 +3. 判定subarray1是否subarray2的前缀时,要保证subarray2的长度不能小于subarray1. 同理判定subarray2是否subarray3的前缀,也需要考虑这个约束。 From b289047c0da86704d05073b98404c4f23bd5d3f1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Dec 2024 00:27:06 -0800 Subject: [PATCH 2640/2729] Create 3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp --- ...e-Amount-After-Two-Days-of-Conversions.cpp | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp diff --git a/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp b/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp new file mode 100644 index 000000000..6e0bfde8c --- /dev/null +++ b/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp @@ -0,0 +1,59 @@ +class Solution { + unordered_mapname2idx; +public: + double maxAmount(string initialCurrency, vector>& pairs1, vector& rates1, vector>& pairs2, vector& rates2) + { + unordered_setSet; + for (auto pair: pairs1) + { + Set.insert(pair[0]); + Set.insert(pair[1]); + } + for (auto pair: pairs2) + { + Set.insert(pair[0]); + Set.insert(pair[1]); + } + int idx = 0; + for (string s: Set) + name2idx[s] = idx++; + + + int n = name2idx.size(); + vector> dist1 = floyd(pairs1, rates1); + vector> dist2 = floyd(pairs2, rates2); + + int s = name2idx[initialCurrency]; + double ret = 1.0; + for (int i=0; i> floyd(vector>& pairs, vector& rates) + { + int n = name2idx.size(); + vector>dist(n, vector(n,0)); + for (int i=0; i Date: Sun, 15 Dec 2024 00:43:56 -0800 Subject: [PATCH 2641/2729] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/Readme.md diff --git a/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/Readme.md b/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/Readme.md new file mode 100644 index 000000000..9304b3c44 --- /dev/null +++ b/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/Readme.md @@ -0,0 +1,17 @@ +### 3387.Maximize-Amount-After-Two-Days-of-Conversions + +考虑到货币的种类只有20种,我们似乎可以用暴力的方法求出每天任意两种货币之间的最大汇率。于是我们可以想到使用o(n^3)的Floyd算法,看做是求图中任意两点之间的最大距离。 + +Floyd的具体做法是,每次引入一条边,然后将全局网络做一遍松弛: +``` +for ([a,b]: edges) + for (int i=0; ib的路径长度(汇率)是t的话,必然有b->a的路径长度是1/t,别忘了将其也加入图优化的松弛过程。 From 3ed821c8a2db792d2e77b65c01fa02dd00c41696 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Dec 2024 00:44:34 -0800 Subject: [PATCH 2642/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 79882f603..6c9b50aa1 100644 --- a/Readme.md +++ b/Readme.md @@ -1191,6 +1191,7 @@ [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) [2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) [2976.Minimum-Cost-to-Convert-String-I](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2976.Minimum-Cost-to-Convert-String-I) (M+) +[3387.Maximize-Amount-After-Two-Days-of-Conversions](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions) (H-) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From ad51a828733ffb78fd96dac7d2183fc4f730b7d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Dec 2024 00:18:30 -0800 Subject: [PATCH 2643/2729] Create 3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp --- ...ns-to-Make-Character-Frequencies-Equal.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp diff --git a/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp b/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp new file mode 100644 index 000000000..3d319cc0f --- /dev/null +++ b/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + int makeStringGood(string s) + { + vectorfreq(26); + for (char c : s) { + freq[c-'a']++; + } + int max_freq = *max_element(freq.begin(), freq.end()); + + int ret = INT_MAX/2; + vectordiff(26); + + for (int target = 1; target <= max_freq; target++) + { + for (int i=0; i<26; i++) + diff[i] = freq[i] - target; + vector>dp(26, vector(2, INT_MAX/2)); + + int carry; + dp[0][0] = freq[0]; + dp[0][1] = abs(diff[0]); + + for (int i=1; i<26; i++) + { + dp[i][0] = min(dp[i-1][0], dp[i-1][1]) + freq[i]; + + dp[i][1] = min(dp[i-1][0], dp[i-1][1]) + abs(diff[i]); + + if (i>=1 && diff[i-1]>0 && diff[i]<0) + { + int common = min(abs(diff[i-1]), abs(diff[i])); + dp[i][1] = min(dp[i][1], dp[i-1][1] + abs(diff[i])-common); + } + + if (i>=1 && freq[i-1]>0 && diff[i]<0) + { + int common = min(abs(freq[i-1]), abs(diff[i])); + dp[i][1] = min(dp[i][1], dp[i-1][0] + abs(diff[i])-common); + } + } + + ret = min(ret, min(dp[25][0], dp[25][1])); + } + + return ret; + } +}; From 060b463d9cd19fe828fff723bd29e1d5eefe6c87 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Dec 2024 00:19:04 -0800 Subject: [PATCH 2644/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6c9b50aa1..51776579d 100644 --- a/Readme.md +++ b/Readme.md @@ -764,6 +764,7 @@ [3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification) (H-) [3082.Find-the-Sum-of-the-Power-of-All-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences) (H-) [3098.Find-the-Sum-of-Subsequence-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers) (H) +[3389.Minimum-Operations-to-Make-Character-Frequencies-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 8b35ff7af805ea26bcee99005f46704292f38fce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Dec 2024 00:39:23 -0800 Subject: [PATCH 2645/2729] Create Readme.md --- .../Readme.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/Readme.md diff --git a/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/Readme.md b/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/Readme.md new file mode 100644 index 000000000..c645d91c0 --- /dev/null +++ b/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/Readme.md @@ -0,0 +1,20 @@ +### 3389.Minimum-Operations-to-Make-Character-Frequencies-Equal + +此题的突破口是对所有可能的频率进行尝试,暴力地从1枚举到max_freq(对应出现频次最多的字母),然后考察是否有一种方法能够将所有字符的频次都变换成target。 + +对于题目中的规则,我们最需要深刻体会的就是第三条。事实上,我们不会将某个字符连续变换两次。比如说,a->b->c,那这两次变换,还不如直接删除a,添加c来得直观。所以唯一使用规则三的情景就是:对于字母表相邻的两种字符x和y,如果x需要删除一些,y需要增加一些,那么我们不妨将部分的x转化为y,以节省操作。更具体的,如果x需要删除a个,y需要增加b个,普通的“删除+增加”的操作需要a+b次,但是如果将c=min(a,b)个x转化为y次,我们就额外节省了c次操作。 + +此题的复杂之处在于,即使我们确定了某个目标频次target,但规则同时也允许部分字符的频次变成零。对于这两个不同的“做法”,需要考虑的策略其实也是不同的。因此我们对于a->z的的每个字符,都要考虑到它的两种“做法”。 + +假设我们考虑相邻的两个字符i-1和字符i。令`diff[i]=freq[i]-target`,正则表示相比于target多了,负表示相比于target还亏欠。定义dp[i][0]表示对字符i采取清零操作的总最小代价;dp[i][1]表示对字符i变换成target频次的总最小代价。 + +1. 如果对字符i采取清零,即dp[i][0],那么所需要的操作数必然是freq[i],与之前的状态无关。故`dp[i][0] = min(dp[i-1][0], dp[i-1][1]) + freq[i]`; + +2. 如果对字符i变换成目标targt,那么我们分两种情况: + * 不采用规则3,只靠增删,那么同理有`dp[i][1] = min(dp[i-1][0], dp[i-1][1]) + abs(diff[i])` + * 采用规则3,同时前一个字符的操作是通过删减达到清零,这就意味着a=freq[i-1],b=abs(diff[i]),故c=min(a,b),且有`dp[i][1] = dp[i-1][0]+abs(diff[i])-c` + * 采用规则3,同时前一个字符的操作是通过删减达到target,这就意味着a=diff[i-1],b=abs(diff[i]),故c=min(a,b),且有`dp[i][1] = dp[i-1][0]+abs(diff[i])-c` + +最终对于target而言,最优解就是遍历完26个字母后的`min(dp[25][0],dp[25][1])` + +全局最取遍历所有target之后的最优解。 From 139d2de864c8ac5ecfcd7b3bab31370c649251f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Dec 2024 23:32:30 -0800 Subject: [PATCH 2646/2729] Create 3399.Smallest-Substring-With-Identical-Characters-II.cpp --- ...Substring-With-Identical-Characters-II.cpp | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/3399.Smallest-Substring-With-Identical-Characters-II.cpp diff --git a/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/3399.Smallest-Substring-With-Identical-Characters-II.cpp b/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/3399.Smallest-Substring-With-Identical-Characters-II.cpp new file mode 100644 index 000000000..5a0c7928d --- /dev/null +++ b/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/3399.Smallest-Substring-With-Identical-Characters-II.cpp @@ -0,0 +1,61 @@ +class Solution { +public: + int minLength(string s, int numOps) + { + vectorarr; + vectornums; + for (auto ch: s) nums.push_back(ch-'0'); + + int n = s.size(); + for (int i=0; iarr, vector&nums, int len, int numOps) + { + if (len==1) + { + int count = 0; + for (int i=0; inumOps) + return false; + } + return true; + } +}; From ad72334cac1d96afe2773743c7bfed1675dd7859 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Dec 2024 23:33:11 -0800 Subject: [PATCH 2647/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 51776579d..45ed17189 100644 --- a/Readme.md +++ b/Readme.md @@ -147,6 +147,7 @@ [3048.Earliest-Second-to-Mark-Indices-I](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I) (M+) [3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) [3097.Shortest-Subarray-With-OR-at-Least-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II) (M) +[3399.Smallest-Substring-With-Identical-Characters-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 3fa59ff9d38110038aff04dfd7ba1a3f73c30c49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Dec 2024 23:54:37 -0800 Subject: [PATCH 2648/2729] Create Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/Readme.md diff --git a/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/Readme.md b/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/Readme.md new file mode 100644 index 000000000..b32e12466 --- /dev/null +++ b/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/Readme.md @@ -0,0 +1,18 @@ +### 3399.Smallest-Substring-With-Identical-Characters-II + +容易发现,只要操作次数越多,就越容易将最长的identical-chracter sbustring长度降下来,所以很明显适合二分搜值的框架。 + +于是问题转变成给定一个len,问是否能在numOps次flip操作内,使得s里不存在超过长度len的identical substring。 + +我们将原字符串里进行预处理,分割为一系列由相同字符组成的子串。对于任意一段长度为x的子串,我们至少需要做多少次flip呢?很明显,贪心思想就可以得到最优解,即每隔len个字符,我们就做一次flip。假设最少做t次flip,我们需要满足 +``` +x <= (len+1) * t + len +``` +才能保证x里面不会有超过长度为len的identical substring。于是求得`t>=(x-k)/(k+1)`。不等式右边是小数时,取上界整数。 + +但是此题有一个坑。如果len是1的话,那么当x是偶数时,会给下一段x带来困扰。比如说s=00001111,我们在处理第一段0000时,会得到贪心的做法做两次flip使得其变成0101。我们发现这样的话下一段的1111其实需要处理的长度是5,给算法带来了极大的不便。比较简单的处理方法就是对len=1的情况特别处理,跳出之前的思维模式,只要考虑将s强制转换为01相间的字符串,计算需要做的flip即可。 + +那为什么len是2的时候我们就不用担心呢?距离s=000111,如果按照贪心的做法,对于第一段000我们需要做一次flip使得其变成001,似乎依然会影响到下一段的111. 但事实上,对于一段我们不需要变换成001,可以将最右端的1随意往左调动一下,变换成010。结果就是flip的次数不变的前提下,依然可以保证不会出现长度超过2的identical substring。注意,回顾一下二分搜值的框架,我们不要求一定要构造出长度为2的identical substring。 + +同理当len=3时,也不会出现类似影响下一段的困扰。之前的计算t的表达式依然可以适用。 + From 303d221d66d6bc7a35c72a87ded5d3a4eee7e202 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Dec 2024 00:01:23 -0800 Subject: [PATCH 2649/2729] Create 3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp --- ...bsequences-with-a-Unique-Middle-Mode-I.cpp | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp diff --git a/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp b/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp new file mode 100644 index 000000000..782dafd92 --- /dev/null +++ b/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp @@ -0,0 +1,69 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + long long comb[1005][6]; +public: + LL getComb(int m, int n) + { + if (m& nums) + { + int n = nums.size(); + for (int i = 0; i <= n; ++i) + { + comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j <= 5; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + comb[i][j] %= M; + } + } + unordered_setSet(nums.begin(), nums.end()); + + LL ret = 0; + + unordered_mapleft; + unordered_mapright; + for (int x: nums) right[x]++; + + for (int i=0; i=1) left[nums[i-1]]++; + + ret += getComb(i - left[a], 2) * getComb(n-i-1-right[a], 2) %M; + ret %= M; + + for (int b: Set) + { + if (a==b) continue; + ret += getComb(left[b],2) * getComb(right[a], 1) * getComb(n-i-1-right[a]-right[b], 1) %M; + ret += getComb(right[b],2) * getComb(left[a], 1) * getComb(i-left[a]-left[b], 1) %M; + ret %= M; + } + + for (int b: Set) + { + if (a==b) continue; + ret += getComb(left[b],1) * getComb(i-left[b]-left[a], 1) * getComb(right[a], 1) * getComb(right[b], 1) %M; + ret += getComb(right[b],1) * getComb(n-i-1-right[b]-right[a], 1) * getComb(left[a], 1) * getComb(left[b], 1) %M; + ret %= M; + } + + for (int b: Set) + { + if (a==b) continue; + ret += getComb(left[b],2) * getComb(right[a], 1) * getComb(right[b], 1) %M; + ret += getComb(right[b],2) * getComb(left[a], 1) * getComb(left[b], 1) %M; + ret %= M; + } + } + + return (getComb(n, 5) - ret + M) % M; + } +}; From f861689b75f073557fedf3abdbe75796fa33ca8a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Dec 2024 00:01:55 -0800 Subject: [PATCH 2650/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 45ed17189..92adfc80f 100644 --- a/Readme.md +++ b/Readme.md @@ -1287,6 +1287,7 @@ [2539.Count-the-Number-of-Good-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2539.Count-the-Number-of-Good-Subsequences) (H-) [2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) [2954.Count-the-Number-of-Infection-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2954.Count-the-Number-of-Infection-Sequences) (H) +[3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From f38207e8c09b34697738542ce1c3effe4df275c1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Dec 2024 00:24:17 -0800 Subject: [PATCH 2651/2729] Create Readme.md --- .../Readme.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/Readme.md diff --git a/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/Readme.md b/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/Readme.md new file mode 100644 index 000000000..62ea183c9 --- /dev/null +++ b/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/Readme.md @@ -0,0 +1,37 @@ +### 3395.Subsequences-with-a-Unique-Middle-Mode-I + +所有任取5个元素的子序列有comb(n,5)个。我们枚举nums[i]=a为中间元素,考虑计算不符合条件的子序列的个数。 + +如果a出现了3次或以上,那么该序列必然是符合条件的,不用考虑。 + +如果a只出现了1次,那么该序列必然不符合条件。这样的子序列有多少个呢?只需要在左区间里任选两个非a的元素,在右区间里任选两个非a的元素。故可构造这样的子序列的个数是`comb(i-left[a],2) * comb(n-i-1-right[a], 2)`。其中left表示统计i左边的元素的频次hash,right表示统计i右边的元素的频次hash。 + +如果a出现了2次,那么必然有一种元素b出现了两次或三次,才能是不符合条件的子序列。我们可以枚举b,并分为三种情况: +1. b出现了两次,且两次都出现在同一侧(假设是左边),那么右边必须要出现另一个a,以及一个非a也非b的元素(假设是c)。故写为`b b a a c`的类型。这样的概率是 +``` +comb(left[a],2) * (right[a],1) * (n-i-1-right[a]-right[b], 1) +``` +类似的,如果两个b都在另一侧,只需将上面的left和right相反即可。 +``` +comb(right[a],2) * (left[a],1) * (i-left[a]-left[b], 1) +``` + +2. b出现了两次,且出现在两侧,那么nums[i]的左右两边分别需要再出现另一个a,以及一个非a也非b的元素(假设是c)。故写为`b a a b c`的类型。这样的概率是 +``` +comb(left[a],1) * (left[b],1) * right([b],1) * (n-i-1-right[a]-right[b], 1) +``` +或者反过来 +``` +comb(right[a],1) * (right[b],1) * left([b],1) * (i-left[a]-left[b], 1) +``` + +3. b出现了三次,占据了除两个a之外的全部位置。故写为`b b a a b`的类型。这样的概率是 +``` +comb(left[b],2) * (right[b],1) * right([a],1) +``` +或者反过来 +``` +comb(right[b],2) * (left[b],1) * left([a],1) +``` + +上述算法用了两重循环枚举a和b。另外,因为n只有1000,我们可以用n^2时间(或者只需要n*5)提前计算好所有1000以内的组合数。所以总的时间复杂度是n^2. From 24826e3954d3eec1229e8edcd9276544fe369aad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 28 Dec 2024 20:03:03 -0800 Subject: [PATCH 2652/2729] Update QuickPow.cpp --- Template/Math/QuickPow.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Template/Math/QuickPow.cpp b/Template/Math/QuickPow.cpp index c95068c43..481124e39 100644 --- a/Template/Math/QuickPow.cpp +++ b/Template/Math/QuickPow.cpp @@ -1,12 +1,12 @@ class Solution { -long long M = 1e9+7; +long long MOD = 1e9+7; public: long long quickMul(long long x, long long N) { if (N == 0) { return 1; } - LL y = quickMul(x, N / 2) % M; - return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); + LL y = quickMul(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); } double quickMul(double x, long long N) { @@ -17,8 +17,8 @@ long long M = 1e9+7; return N % 2 == 0 ? y * y : y * y * x; } - double myPow(double x, int n) { - long long N = n; - return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N); + // n can be negative. + double myPow(double x, int n) { + return n >= 0 ? quickMul(x, n) : 1.0 / quickMul(x, -n); } }; From 002b8b9794f29366bf677185057c5ce1bb6faba1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Dec 2024 16:51:58 -0800 Subject: [PATCH 2653/2729] Update Inverse_Element.cpp --- Template/Inverse_Element/Inverse_Element.cpp | 39 ++++++++------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/Template/Inverse_Element/Inverse_Element.cpp b/Template/Inverse_Element/Inverse_Element.cpp index 7b30a1420..0e79078e7 100644 --- a/Template/Inverse_Element/Inverse_Element.cpp +++ b/Template/Inverse_Element/Inverse_Element.cpp @@ -1,50 +1,41 @@ #include #define LL long long using namespace std; -const LL N = 1e6+7, mod = 998244353; +const LL N = 1e6+7, MOD = 998244353; /*********************************/ // Linear method to compute inv[i] -void main() +vectorcompute_inv(int n) { - LL inv[N]; + vectorinv(n+1); inv[1] = 1; - for(int i=2; i>= 1; + if (N <= 0) { + return 1; } - return ret; + LL y = quickPow(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); } -LL inv(LL x) +long long inv(LL x) { - return quickPow(x, mod - 2); + return quickPow(x, MOD - 2); } /*****************************/ -LL inv(int x) +long long compute_inv(int x) { LL s = 1; - for (; x > 1; x = mod%x) - s = s*(mod-mod/x)%mod; + for (; x > 1; x = MOD%x) + s = s*(MOD-MOD/x)%MOD; return s; } From cd9df767b6bae6fe13c4bd3732bcbfeb49d7aec2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Dec 2024 16:55:04 -0800 Subject: [PATCH 2654/2729] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 58 +++++++++++++++++++++------- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index f0f0bf418..f10efda58 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -1,19 +1,19 @@ using LL = long long; -main() + +/*********************************/ +// Version 1: compute all C(n,m) saved in comb +long long comb[1000][1000]; +for (int i = 0; i <= n; ++i) { - // Version 1: compute all C(n,m) saved in comb - long long comb[1000][1000]; - for (int i = 0; i <= n; ++i) - { - comb[i][i] = comb[i][0] = 1; - if (i==0) continue; - for (int j = 1; j < i; ++j) - { - comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; - } - } -} + comb[i][i] = comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j < i; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + } +} +/*********************************/ // Version 2: Compute C(n,m) on demand based on definition long long help(int n, int m) { @@ -26,6 +26,7 @@ long long help(int n, int m) return cnt; } +/*********************************/ // Version 3: Compute C(m,n) on demand with module M using LL = long long; LL M = 1e9+7; @@ -57,3 +58,34 @@ LL comb(LL m, LL n) return a * inv_b % M; } + +/*********************************/ +// Version 4: Compute C(m,n) on demand with module M +long long quickMul(long long x, long long N) +{ + if (N <= 0) { + return 1; + } + LL y = quickMul(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); +} + +void precompute(int n, vector& fact, vector& inv_fact) +{ + fact[0] = inv_fact[0] = 1; + for (int i = 1; i <= n; ++i) + { + fact[i] = fact[i - 1] * i % MOD; + } + inv_fact[n] = quickMul(fact[n], MOD - 2); + for (int i = n - 1; i >= 1; --i) + { + inv_fact[i] = inv_fact[i + 1] * (i + 1) % MOD; + } +} + +long long comb(int n, int k, const vector& fact, const vector& inv_fact) +{ + if (k > n || k < 0) return 0; + return fact[n] * inv_fact[k] % MOD * inv_fact[n - k] % MOD; +} From 01571c48701267f13700a58caca9306aa1e6761d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Dec 2024 16:59:02 -0800 Subject: [PATCH 2655/2729] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 40 ++++++++++++++-------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index f10efda58..73ce5ea38 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -61,31 +61,31 @@ LL comb(LL m, LL n) /*********************************/ // Version 4: Compute C(m,n) on demand with module M -long long quickMul(long long x, long long N) +const LL MOD = 1e9 + 7; +vector factorial; +vector GetFactorial(LL N) { - if (N <= 0) { + vectorrets(N+1); + rets[0] = 1; + for (int i=1; i<=N; i++) + rets[i] = rets[i-1] * i % MOD; + return rets; +} + +long long quickPow(long long x, long long N) { + if (N == 0) { return 1; } - LL y = quickMul(x, N / 2) % MOD; + LL y = quickPow(x, N / 2) % MOD; return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); } - -void precompute(int n, vector& fact, vector& inv_fact) -{ - fact[0] = inv_fact[0] = 1; - for (int i = 1; i <= n; ++i) - { - fact[i] = fact[i - 1] * i % MOD; - } - inv_fact[n] = quickMul(fact[n], MOD - 2); - for (int i = n - 1; i >= 1; --i) - { - inv_fact[i] = inv_fact[i + 1] * (i + 1) % MOD; - } -} -long long comb(int n, int k, const vector& fact, const vector& inv_fact) +LL comb(LL m, LL n) { - if (k > n || k < 0) return 0; - return fact[n] * inv_fact[k] % MOD * inv_fact[n - k] % MOD; + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % MOD; + LL inv_b = quickPow(b, (MOD-2)); + + return a * inv_b % MOD; } From 52caf01ed255f14cbb91aa855a58e7e8d401d01b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:13:35 -0800 Subject: [PATCH 2656/2729] Create 3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp --- ...rays-with-K-Matching-Adjacent-Elements.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp diff --git a/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp new file mode 100644 index 000000000..3cf1a6303 --- /dev/null +++ b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { +public: + const LL MOD = 1e9 + 7; + vector factorial; + vector GetFactorial(LL N) + { + vectorrets(N+1); + rets[0] = 1; + for (int i=1; i<=N; i++) + rets[i] = rets[i-1] * i % MOD; + return rets; + } + + long long quickPow(long long x, long long N) { + if (N == 0) { + return 1; + } + LL y = quickPow(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); + } + + LL comb(LL m, LL n) + { + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % MOD; + LL inv_b = quickPow(b, (MOD-2)); + + return a * inv_b % MOD; + } + + int countGoodArrays(int n, int m, int k) + { + factorial = GetFactorial(n); + return comb(n-1,k) * m % MOD * quickPow(m-1, n-k-1) % MOD; + } +}; From 4c99c92ef297223e0565020af006a18fae692345 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:14:22 -0800 Subject: [PATCH 2657/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 92adfc80f..c4258a543 100644 --- a/Readme.md +++ b/Readme.md @@ -1288,6 +1288,7 @@ [2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) [2954.Count-the-Number-of-Infection-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2954.Count-the-Number-of-Infection-Sequences) (H) [3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) +[3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From eb0122c1a1ca8139fa03b9ce0e893770e189ca59 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:28:31 -0800 Subject: [PATCH 2658/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md diff --git a/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md new file mode 100644 index 000000000..2437cc360 --- /dev/null +++ b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md @@ -0,0 +1,11 @@ +### 3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements + +考虑到恰有k个位置的元素与其左边元素相同,那么将其与其左边元素“合并”后,数组里可看做只有n-k个元素,并且这些元素在相邻的位置上不重复。证明很显然,如果“合并”后依然存在相邻的相同元素,那么原数组里必然不止k处相邻的相同元素。 + +从原数组里挑出k个位置,有comb(n,k)种方案。 + +任何一种上述的方案,对于“合并”后的数组的n-k个元素,要求相邻之间不重复,有多少种方案?第一个位置有m种选择,之后每一个位置都只有m-1种选择。故总共有`m*m^(n-k-1)`种方案。 + +所以最终答案就是简单的数学接 `comb(n,k)*m*m^(n-k-1)`. + +因为n和k是1e5,所以不能用o(n*k)的复杂度计算组合数任何n以内的组合数。我们可以直接硬算`comb(n,k) = n!/k!/(n-k)!`. 其中阶乘的复杂度就是o(n),但是涉及到了除法,故需要介入逆元。逆元的计算公式是`inv_x = quickPow(x, (MOD-2))`. From e2c08fc762bd6f192cb0524acaa4dd6aa77c552b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:29:19 -0800 Subject: [PATCH 2659/2729] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md index 2437cc360..037aa8903 100644 --- a/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md +++ b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md @@ -6,6 +6,6 @@ 任何一种上述的方案,对于“合并”后的数组的n-k个元素,要求相邻之间不重复,有多少种方案?第一个位置有m种选择,之后每一个位置都只有m-1种选择。故总共有`m*m^(n-k-1)`种方案。 -所以最终答案就是简单的数学接 `comb(n,k)*m*m^(n-k-1)`. +所以最终答案就是简单的数学表达式 `comb(n,k)*m*m^(n-k-1)`. 因为n和k是1e5,所以不能用o(n*k)的复杂度计算组合数任何n以内的组合数。我们可以直接硬算`comb(n,k) = n!/k!/(n-k)!`. 其中阶乘的复杂度就是o(n),但是涉及到了除法,故需要介入逆元。逆元的计算公式是`inv_x = quickPow(x, (MOD-2))`. From 7349706e75cff6e55fcb67573f9e0fb553eacc33 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:57:30 -0800 Subject: [PATCH 2660/2729] Create 3404.Count-Special-Subsequences.cpp --- .../3404.Count-Special-Subsequences.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp diff --git a/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp b/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp new file mode 100644 index 000000000..7b7089e75 --- /dev/null +++ b/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp @@ -0,0 +1,32 @@ +using LL = long long; +class Solution { +public: + LL getKey(int x, int y) + { + int g = gcd(x,y); + x = x/g; + y = y/g; + return (LL)x*1000+y; + } + long long numberOfSubsequences(vector& nums) + { + unordered_map>Map; + int n = nums.size(); + for (int i=0; i Date: Mon, 30 Dec 2024 00:58:45 -0800 Subject: [PATCH 2661/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c4258a543..b2829fbe4 100644 --- a/Readme.md +++ b/Readme.md @@ -1622,6 +1622,7 @@ [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) +[3404.Count-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Others/3404.Count-Special-Subsequences) (H) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 10846f4987fb95bb9c6496a062a26f500f7e9375 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 01:34:41 -0800 Subject: [PATCH 2662/2729] Create Readme.md --- Others/3404.Count-Special-Subsequences/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/3404.Count-Special-Subsequences/Readme.md diff --git a/Others/3404.Count-Special-Subsequences/Readme.md b/Others/3404.Count-Special-Subsequences/Readme.md new file mode 100644 index 000000000..d9bc06b56 --- /dev/null +++ b/Others/3404.Count-Special-Subsequences/Readme.md @@ -0,0 +1,13 @@ +### 3404.Count-Special-Subsequences + +考虑n的数量级,我们只能支持两重循环。 + +如果我们遍历p和r,那么如何能只用o(1)计算在(p,r)和(r,n)里相等乘积的pairs呢?这两段区间都是动态的,没法预处理,这个思路很难进行下去。 + +如果我们遍历p和q,那么我们需要用o(1)计算在(q,n)里找到两处r和s,使得nums[s]/nums[r]等于给定的ratio(即nums[p]/nums[q])。此时发现我们需要寻找的pairs集中在数组的右半边,这就提示我们可以将数组左边和右边分别进行预处理,可以用两次o(n^2)的时间求出所有的pairs的ratio,再按照ratio的数值作为hash key进行统计。 + +那么如何进行统计呢?我们顺着这个思路继续想下去。为了方便,假设我们用两重循环枚举r和s。随着r的移动,我们对于p/q的考察范围会相应地扩大,即[0,r-2]。我们想知道,在这个区间里有多少pairs的ratio等于nums[s]/nums[r]?注意到我们的考察区间有个上限,这说明了我们在预处理所有pairs的时候,除了按照ratio的值进行hash存放,还需要记录位置。记录什么位置呢?按q的位置进行记录就行了,因为p肯定小于q,故只要记录一个q,那么说明必然有一个相应合法的p存在。 + +更具体的,假设我们有很多对ratio相同的pairs,例如(1,3),(2,5),(2,8),(3,8),(4,8),(5,9),(6,9),我们只需要存下`Map[ratio]={3,5,8,8,8,9,9}`. 当r=10时,我们知道q的上界就是8,故只需要在这个数组里寻找小于等于8的个数,这里有5个,就说明有5个pairs可以作为(p,q),与当前枚举的(r,s)进行配对。 + +由此我们可以用两重循环枚举r与s,配合这种巧妙的hash记录,用`n^2*log(n)`的时间求解。 From 57522d8a5c2f307ee5976ac42526bc74dffe526c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 22:15:07 -0800 Subject: [PATCH 2663/2729] Update 3404.Count-Special-Subsequences.cpp --- .../3404.Count-Special-Subsequences.cpp | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp b/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp index 7b7089e75..8cd370995 100644 --- a/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp +++ b/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp @@ -1,31 +1,32 @@ -using LL = long long; class Solution { public: - LL getKey(int x, int y) + int getKey(int x, int y) { int g = gcd(x,y); x = x/g; y = y/g; - return (LL)x*1000+y; + return x*1000+y; } + long long numberOfSubsequences(vector& nums) { - unordered_map>Map; + unordered_map>Map; int n = nums.size(); - for (int i=0; i Date: Wed, 1 Jan 2025 22:57:23 -0800 Subject: [PATCH 2664/2729] Create 3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp --- ...of-Matching-Indices-After-Right-Shifts.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp diff --git a/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp b/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp new file mode 100644 index 000000000..2fc898808 --- /dev/null +++ b/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maximumMatchingIndices(vector& nums1, vector& nums2) + { + int ret = 0; + int n = nums1.size(); + unordered_map>Map; + for (int i=0; iscores(n); + for (int i=0; i Date: Wed, 1 Jan 2025 23:02:14 -0800 Subject: [PATCH 2665/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/Readme.md diff --git a/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/Readme.md b/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/Readme.md new file mode 100644 index 000000000..1a2511d6a --- /dev/null +++ b/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/Readme.md @@ -0,0 +1,9 @@ +### 3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts + +此题除了常规的n^2暴力枚举之外,还有一种更为巧妙的算法。我们定义长度为n的数组scores,其中scores[i]表示移动i次可以match到多少字符。 + +我们将nums2的所有元素存入一个hash表,key是元素大小,value是该元素出现的位置。然后遍历每个nums1[i],我们通过hash表查看nums1[i]在nums2里出现的所有位置(比如说idx),那么我们就知道进行`(idx-i+n)%n`次shift的话,我们可以得到一个match,即给对应的score加上1分。 + +最终返回scores数字里的最大值。 + +这种算法的第二层循环不固定是n,因此效率会更高一些。 From 34439a3ef8b548c228642680bee93a60e7ee825f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:02:56 -0800 Subject: [PATCH 2666/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b2829fbe4..36767bca3 100644 --- a/Readme.md +++ b/Readme.md @@ -1549,6 +1549,7 @@ [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) [3068.Find-the-Maximum-Sum-of-Node-Values](https://github.com/wisdompeak/LeetCode/tree/master/Others/3068.Find-the-Maximum-Sum-of-Node-Values) (M+) +[3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts](https://github.com/wisdompeak/LeetCode/tree/master/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts) (M+) * ``公式变形`` [2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` From c92bee4ea66cf350cb12f240e3b006694ea18800 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:10:28 -0800 Subject: [PATCH 2667/2729] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 36767bca3..20a750ad0 100644 --- a/Readme.md +++ b/Readme.md @@ -1495,7 +1495,9 @@ [2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) [2753.Count-Houses-in-a-Circular-Street-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2753.Count-Houses-in-a-Circular-Street-II) (H-) -[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) +[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) +3301.Maximize-the-Total-Height-of-Unique-Towers (M) +3397.Maximum Number-of-Distinct-Elements-After-Operations (M) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 8d18ab9403e034ccfdb0231b7b8b300f639bca33 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:10:44 -0800 Subject: [PATCH 2668/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 20a750ad0..93c5bc521 100644 --- a/Readme.md +++ b/Readme.md @@ -1495,7 +1495,7 @@ [2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) [2753.Count-Houses-in-a-Circular-Street-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2753.Count-Houses-in-a-Circular-Street-II) (H-) -[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) +[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) 3301.Maximize-the-Total-Height-of-Unique-Towers (M) 3397.Maximum Number-of-Distinct-Elements-After-Operations (M) From 82dcf3fe1f95434b70c1f69a822839318019b35d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:13:57 -0800 Subject: [PATCH 2669/2729] Create 3394.Check-if-Grid-can-be-Cut-into-Sections.cpp --- ...Check-if-Grid-can-be-Cut-into-Sections.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/3394.Check-if-Grid-can-be-Cut-into-Sections.cpp diff --git a/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/3394.Check-if-Grid-can-be-Cut-into-Sections.cpp b/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/3394.Check-if-Grid-can-be-Cut-into-Sections.cpp new file mode 100644 index 000000000..87f6a0874 --- /dev/null +++ b/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/3394.Check-if-Grid-can-be-Cut-into-Sections.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + bool checkValidCuts(int n, vector>& arr) + { + vector>widths; + vector>heights; + for (int i=0; i>&arr) + { + sort(arr.begin(),arr.end()); + + int j=0; + int count = 0; + for (int i=0; i=3) return true; + } + return false; + } +}; From 34175229f0a30a4aef6a3b5e579fee15347581ab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:14:44 -0800 Subject: [PATCH 2670/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 93c5bc521..81d7612a8 100644 --- a/Readme.md +++ b/Readme.md @@ -1050,7 +1050,7 @@ [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) [2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) -[3388.Count-Beautiful-Splits-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/3388.Count-Beautiful-Splits-in-an-Array) (H-) +[3388.Count-Beautiful-Splits-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/3388.Count-Beautiful-Splits-in-an-Array) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) @@ -1474,6 +1474,7 @@ [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) +[3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 533f61c6660be4126b518d7fc452e5d42093ba87 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:25:45 -0800 Subject: [PATCH 2671/2729] Create Readme.md --- .../3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md diff --git a/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md b/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md new file mode 100644 index 000000000..85ca694d5 --- /dev/null +++ b/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md @@ -0,0 +1,7 @@ +### 3394.Check-if-Grid-can-be-Cut-into-Sections + +本题的本质就是在横纵方向上,分别查验是否存在至少三个non-overlapping intervals. + +数non-overlapping intervals的经典算法就是将所有区间按照首端点排序。将第一个区间的未端点记作far,然后依次查看后续区间的首端点是否小于等于far,是的话就说明必然存在overlap。同时,每查看一个后续区间,我们都用该区间的尾端点区更新far值(取max)。直至下一个区间的首端点在far之后停止。此时我们之前考察的所有区间,必然都是存在partial overlap的,但是他们merge后的整体不会与其他区间再有重合。 + +之后我们再从下一个区间开始,重复上面的操作,找到另一个存在overlap的区间群。依次类推。 From c18e90a5e2416db1d4f0170162197eb82f0d1315 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Jan 2025 00:06:16 -0800 Subject: [PATCH 2672/2729] Create 3413.Maximum-Coins-From-K-Consecutive-Bags.cpp --- ....Maximum-Coins-From-K-Consecutive-Bags.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/3413.Maximum-Coins-From-K-Consecutive-Bags.cpp diff --git a/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/3413.Maximum-Coins-From-K-Consecutive-Bags.cpp b/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/3413.Maximum-Coins-From-K-Consecutive-Bags.cpp new file mode 100644 index 000000000..c94294323 --- /dev/null +++ b/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/3413.Maximum-Coins-From-K-Consecutive-Bags.cpp @@ -0,0 +1,46 @@ +using LL = long long; +class Solution { +public: + long long maximumCoins(vector>& coins, int k) + { + LL ret = 0; + sort(coins.begin(), coins.end()); + ret = max(ret, helper(coins, k)); + + for (auto& coin: coins) + { + int a = coin[0], b = coin[1]; + coin[0] = -b; + coin[1] = -a; + } + sort(coins.begin(), coins.end()); + ret = max(ret, helper(coins, k)); + + return ret; + } + + LL helper(vector>& coins, int k) + { + int n = coins.size(); + int j = 0; + LL sum = 0; + LL ret = 0; + for (int i=0; i= coins[j][1]) + { + sum += (LL)(coins[j][1]-coins[j][0]+1)*coins[j][2]; + j++; + } + LL extra = 0; + if (j= coins[j][0]) + { + extra += (LL)(end - coins[j][0] + 1) * coins[j][2]; + } + ret = max(ret, sum + extra); + sum -= (LL)(coins[i][1]-coins[i][0]+1)*coins[i][2]; + } + return ret; + } +}; From a5640e87a79213f72b9c0780411610cfd66c502f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Jan 2025 00:07:05 -0800 Subject: [PATCH 2673/2729] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 81d7612a8..d9f5e7111 100644 --- a/Readme.md +++ b/Readme.md @@ -1353,7 +1353,6 @@ [2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) [2242.Maximum-Score-of-a-Node-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2242.Maximum-Score-of-a-Node-Sequence) (M+) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) -[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) [2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) [2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K) (H-) @@ -1474,7 +1473,9 @@ [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) -[3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) +[3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) +[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) +[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 75207ee8d6ef7475878f63fd139141fa710ac4dd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Jan 2025 00:22:34 -0800 Subject: [PATCH 2674/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/Readme.md diff --git a/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/Readme.md b/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/Readme.md new file mode 100644 index 000000000..7c5469a3d --- /dev/null +++ b/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/Readme.md @@ -0,0 +1,11 @@ +### 3413.Maximum-Coins-From-K-Consecutive-Bags + +此题和2271.Maximum-White-Tiles-Covered-by-a-Carpet的思路类似。 + +对于长度为k的跨度,如果其一个端点没有落在任何区间,那么显然是不划算的。我们必然有更优的策略:平移这段跨度直至一端接触到某个区间的边缘,这样可以在另一端覆盖到更多的有效区域得到更大的价值。注意“某个区间的端点”可以是左端点,也可以是右端点。 + +再考虑,对于长度为k的跨度,如果其两个端点分别都落在了区间A和区间B内,那么同样也是不划算的。只要区间A和B的价值密度不一样,那么我们必然能找到更优的解,即朝价值密度更高的那个方向平移即可。平移的最终结果是:完全离开价值密度低的区间(如果另一端依然在价值密度高的区间的话),或者触碰到价值密度高的区间的边缘。 + +所以上述的结论就是,最优解的情况,必然发生在所选跨度恰好触碰在某个区间边缘的时候。所以我们分两种情况。首先,从左往右遍历每个区间的左边缘,当做是所选跨度k的左边界,然后可以确定右边界的位置,这样就计算总价值;随着对左边界的挨个尝试,右边界也是单调移动的。所以这是一个典型的双指针。然后,反过来,从右往左遍历每个区间的右边缘,当做是所选跨度的右边界,然后可以确定左边界的位置,这样就计算总价值;随着对右边界的挨个尝试,左边界也是单调移动的。 + +对于第二次遍历,我们可以重复利用第一次遍历的函数。只要将每个区间的左右端点完全颠倒即可。即原区间范围是[a,b],那么我们构造一个新的区间范围[-b,-a]。这样我们依然可以重复利用从左往右遍历的代码,本质上实现了从右往左的遍历。 From 3e4eda797d90b894ca22a818b4c8570ebe34f3d6 Mon Sep 17 00:00:00 2001 From: Eric Chou <87915276+EricccTaiwan@users.noreply.github.com> Date: Tue, 4 Feb 2025 12:27:46 +0800 Subject: [PATCH 2675/2729] Add the corresponding link to LeetCode 131 --- Dynamic_Programming/131.Palindrome-Partitioning/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dynamic_Programming/131.Palindrome-Partitioning/Readme.md b/Dynamic_Programming/131.Palindrome-Partitioning/Readme.md index 7aa706c3f..886e4524c 100644 --- a/Dynamic_Programming/131.Palindrome-Partitioning/Readme.md +++ b/Dynamic_Programming/131.Palindrome-Partitioning/Readme.md @@ -5,3 +5,5 @@ 然后从第一个字符开始进行深度优先搜索。设计dfs(i,temp),表示考虑以当前的位置i为substring的开头,遍历有哪些位置j满足[i:j]的字符串满足回文(即dp[i][j]=1),就将该字符串收录进temp,然后递归搜索第j+1个位置。如果dfs的参数i走到了n,说明恰好将整个s分割成了若干段回文串,就将这组分割的子串temp加入最终答案。 特别注意,这个dfs在回溯的时候需要将temp末尾加入的子串弹出。 + +[Leetcode Link](https://leetcode.com/problems/palindrome-partitioning/) From eb61567c73a42f8bc7bc31b0687af3cfa4e7f59a Mon Sep 17 00:00:00 2001 From: Eric Chou <87915276+EricccTaiwan@users.noreply.github.com> Date: Tue, 4 Feb 2025 15:57:18 +0800 Subject: [PATCH 2676/2729] Refactor: Change loop variable type from int to char for clarity Updated the loop variable in the DFS function from `int k` to `char k` to improve clarity and maintain consistency with the Sudoku board's data type. This change avoids implicit type conversions and ensures that the code directly represents the intended operations on character data ('1' to '9'). --- DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp b/DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp index 2c831d805..24c97459d 100644 --- a/DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp +++ b/DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp @@ -11,7 +11,7 @@ class Solution { if (j==9) return DFS(board, i+1, 0); if (board[i][j]!='.') return DFS(board, i, j+1); - for (int k='1'; k<='9'; k++) + for (char k='1'; k<='9'; k++) { if (!isValid(board, i, j, k)) continue; board[i][j]=k; From abd6ee0896e7127e83da1a0c2a82e059e2d94e25 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Feb 2025 00:37:31 -0800 Subject: [PATCH 2677/2729] Create 3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp --- ...rays with K Matching-Adjacent-Elements.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp diff --git a/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp b/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp new file mode 100644 index 000000000..992e3202f --- /dev/null +++ b/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { + LL MOD = 1e9 + 7; + LL comb[100005][75]; +public: + int minMaxSums(vector& nums, int k) + { + int n = nums.size(); + for (int i = 0; i <= n; ++i) + { + comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j <= k; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + comb[i][j] %= MOD; + } + } + + sort(nums.begin(), nums.end()); + + LL ret = 0; + for (int i=0; i Date: Fri, 7 Feb 2025 00:40:30 -0800 Subject: [PATCH 2678/2729] Delete Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp --- ...rays with K Matching-Adjacent-Elements.cpp | 38 ------------------- 1 file changed, 38 deletions(-) delete mode 100644 Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp diff --git a/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp b/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp deleted file mode 100644 index 992e3202f..000000000 --- a/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp +++ /dev/null @@ -1,38 +0,0 @@ -using LL = long long; -class Solution { - LL MOD = 1e9 + 7; - LL comb[100005][75]; -public: - int minMaxSums(vector& nums, int k) - { - int n = nums.size(); - for (int i = 0; i <= n; ++i) - { - comb[i][0] = 1; - if (i==0) continue; - for (int j = 1; j <= k; ++j) - { - comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; - comb[i][j] %= MOD; - } - } - - sort(nums.begin(), nums.end()); - - LL ret = 0; - for (int i=0; i Date: Fri, 7 Feb 2025 00:42:45 -0800 Subject: [PATCH 2679/2729] Create 3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp --- ...um-Sums-of-at-Most-Size-K-Subsequences.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp diff --git a/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp new file mode 100644 index 000000000..992e3202f --- /dev/null +++ b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { + LL MOD = 1e9 + 7; + LL comb[100005][75]; +public: + int minMaxSums(vector& nums, int k) + { + int n = nums.size(); + for (int i = 0; i <= n; ++i) + { + comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j <= k; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + comb[i][j] %= MOD; + } + } + + sort(nums.begin(), nums.end()); + + LL ret = 0; + for (int i=0; i Date: Fri, 7 Feb 2025 00:43:18 -0800 Subject: [PATCH 2680/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d9f5e7111..7c9ad7c66 100644 --- a/Readme.md +++ b/Readme.md @@ -1288,7 +1288,8 @@ [2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) [2954.Count-the-Number-of-Infection-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2954.Count-the-Number-of-Infection-Sequences) (H) [3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) -[3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) +[3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) +[3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences) (M+) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From f1dcc4c51e8f979ff0b2d44019b4de91c31f89b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Feb 2025 10:42:50 -0800 Subject: [PATCH 2681/2729] Create Readme.md --- .../Readme.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md diff --git a/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md new file mode 100644 index 000000000..2843d7f96 --- /dev/null +++ b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md @@ -0,0 +1,2 @@ +### 3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences + From 2f9b651fcfc956c125f2761c0938c27c10ab6bd0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Feb 2025 11:01:09 -0800 Subject: [PATCH 2682/2729] Update Readme.md --- .../Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md index 2843d7f96..977c48798 100644 --- a/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md +++ b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md @@ -1,2 +1,10 @@ ### 3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences +入手的思路很常规。我们不会枚举所有的subsequence然后查找它的最大值(或最小值)。反过来,我们会对每个元素考察,如果它是一个subsequence里的最大值(或最小值),那么这个subsequenec有多少个? + +显然,对于任意的nums[i],我们只需要在其他比它小的元素里找kk个即可(其中kk<=k-1)。如果有m个比它小的元素,那么以nums[i]为最大值的subsequence就有comb(m,kk)个。考虑到m不超过1e5,kk不超过70,我们可以提前将所有的comb(m,kk)都计算好。 + +此题需要注意的是,数值相同的nums可能有多个。也就是说,如果一个subsequence里同时有nums[i]和nums[j]都是最大值,那么我们不能将这个subsequence重复分给这两个数,只能挑一个来计算最大值。因此我们可以约定,比如说,只有最后一个出现的最大元素才是最大值。 + +更方便的做法是,因为本题的subsequence只看最大值,并不在意元素之间相对的顺序。所以我们可以直接将nums排序。因为排序前的任何一个subsequence,必然一一对应排序后的某个subsequence。对于排序后的nums,当我们认定nums[i]是最大值时,符合条件的subsequence的其他元素就必然在nums[:i-1]里任选即可。这样的组合就有`sum{comb(i, kk)}, where kk=0,1,..,k-1`. + From e9bff682e3111b7f1c736e7f43bcb6709d2dcf72 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Feb 2025 23:39:23 -0800 Subject: [PATCH 2683/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7c9ad7c66..5e9f37f40 100644 --- a/Readme.md +++ b/Readme.md @@ -1580,6 +1580,7 @@ [2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) [2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) [2818.Apply-Operations-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2818.Apply-Operations-to-Maximize-Score) (H-) +[3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences) (M+) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 5e3a4c143ebd0ed79ebd95f4d2fb3d2c123f02ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Feb 2025 00:30:14 -0800 Subject: [PATCH 2684/2729] Create 3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp --- ...ments-for-Target-Multiples-in-an-Array.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp diff --git a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp new file mode 100644 index 000000000..f29402b4a --- /dev/null +++ b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp @@ -0,0 +1,37 @@ +class Solution { + int dp[50005][1<<4]; + +public: + int minimumIncrements(vector& nums, vector& target) + { + int m = target.size(); + int n = nums.size(); + nums.insert(nums.begin(), 0); + int ret = INT_MAX/2; + + for (int state = 0; state < (1<0; subset=(subset-1)&state) + { + long long L = 1; + for (int j=0; j>j)&1) + L = lcm(L, target[j]); + if (L>INT_MAX/2) break; + } + if (L>INT_MAX/2) continue; + int cost = (nums[i]%L==0)?0:(L-nums[i]%L); + dp[i][state] = min(dp[i][state], dp[i-1][state-subset] + cost); + } + } + + return dp[n][(1< Date: Sat, 8 Feb 2025 00:31:03 -0800 Subject: [PATCH 2685/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5e9f37f40..4fe2356b1 100644 --- a/Readme.md +++ b/Readme.md @@ -935,7 +935,8 @@ [1494.Parallel-Courses-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1494.Parallel-Courses-II) (H) [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) [1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks) (M+) - [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) + [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) + [3444.Minimum-Increments-for-Target-Multiples-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array) (H=) * ``带权二分图`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1595.Minimum-Cost-to-Connect-Two-Groups-of-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points) (H) From 171203adc8fb29042be1c5724641796d14f23980 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Feb 2025 00:31:27 -0800 Subject: [PATCH 2686/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 4fe2356b1..08acb0ac8 100644 --- a/Readme.md +++ b/Readme.md @@ -936,7 +936,7 @@ [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) [1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks) (M+) [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) - [3444.Minimum-Increments-for-Target-Multiples-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array) (H=) + [3444.Minimum-Increments-for-Target-Multiples-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array) (H-) * ``带权二分图`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1595.Minimum-Cost-to-Connect-Two-Groups-of-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points) (H) From 722e7890ba98a200d5648bcb128847353bfa2b79 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 00:46:07 -0800 Subject: [PATCH 2687/2729] Create 3447.Assign-Elements-to-Groups-with-Constraints.cpp --- ...gn-Elements-to-Groups-with-Constraints.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Others/3447.Assign-Elements-to-Groups-with-Constraints/3447.Assign-Elements-to-Groups-with-Constraints.cpp diff --git a/Others/3447.Assign-Elements-to-Groups-with-Constraints/3447.Assign-Elements-to-Groups-with-Constraints.cpp b/Others/3447.Assign-Elements-to-Groups-with-Constraints/3447.Assign-Elements-to-Groups-with-Constraints.cpp new file mode 100644 index 000000000..fb78c0a9f --- /dev/null +++ b/Others/3447.Assign-Elements-to-Groups-with-Constraints/3447.Assign-Elements-to-Groups-with-Constraints.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector assignElements(vector& groups, vector& elements) + { + int n = *max_element(groups.begin(), groups.end()); + vectorarr(n+1, -1); + + for (int j=0; jn) continue; + + if (arr[x0]!=-1) continue; + + int x = x0; + while (x<=n) + { + if (arr[x]==-1) + arr[x] = j; + x+=x0; + } + } + + vectorrets; + for (int g: groups) + rets.push_back(arr[g]); + return rets; + } +}; From dd363d63208b3343123d7df64933b685e365ca8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 00:46:37 -0800 Subject: [PATCH 2688/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 08acb0ac8..8dd8692b3 100644 --- a/Readme.md +++ b/Readme.md @@ -1631,6 +1631,7 @@ [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) [3404.Count-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Others/3404.Count-Special-Subsequences) (H) +[3447.Assign-Elements-to-Groups-with-Constraints](https://github.com/wisdompeak/LeetCode/tree/master/Others/3447.Assign-Elements-to-Groups-with-Constraints) (M+) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From c71d7fc8cf4202f3ddb0cce45531758cf6b63191 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 00:57:30 -0800 Subject: [PATCH 2689/2729] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/3447.Assign-Elements-to-Groups-with-Constraints/Readme.md diff --git a/Others/3447.Assign-Elements-to-Groups-with-Constraints/Readme.md b/Others/3447.Assign-Elements-to-Groups-with-Constraints/Readme.md new file mode 100644 index 000000000..3e6d9e611 --- /dev/null +++ b/Others/3447.Assign-Elements-to-Groups-with-Constraints/Readme.md @@ -0,0 +1,7 @@ +### 3447.Assign-Elements-to-Groups-with-Constraints + +突破点在于groups里的元素的数值不超过1e5.在这个范围是,如果枚举所有1的倍数,然后枚举所有2的倍数,然后枚举所有3的倍数,直至枚举n的倍数,那么总共的时间复杂度是`n+n/2+n/3+...n/n = n*(1+1/2+1/3+...1/n)`.这个级数虽然不收敛,但是它是趋近于nlog(n)的。所以本题可以用暴力枚举。 + +所以本题的算法很简单。我们开一个长度为1e5的数组assign,来记录每个自然数最早能被哪个element所assign。我们依次考察element里的每个元素,比如说elements[j]=x,然后枚举x的所有倍数(直至1e5),比如说kx,那样就有`assign[kx] = j`,当然根据题意,我们对于每个assign我们只更新一次。 + +最后根据groups的数值,从assgin里把答案拷贝过去即可。 From 2318d0efb53c835e91d145d8d66a0d673312570e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 01:13:50 -0800 Subject: [PATCH 2690/2729] Create 3448.Count-Substrings-Divisible-By-Last-Digit.cpp --- ...unt-Substrings-Divisible-By-Last-Digit.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Hash/3448.Count-Substrings-Divisible-By-Last-Digit/3448.Count-Substrings-Divisible-By-Last-Digit.cpp diff --git a/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/3448.Count-Substrings-Divisible-By-Last-Digit.cpp b/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/3448.Count-Substrings-Divisible-By-Last-Digit.cpp new file mode 100644 index 000000000..fd25aa2ae --- /dev/null +++ b/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/3448.Count-Substrings-Divisible-By-Last-Digit.cpp @@ -0,0 +1,43 @@ +using LL = long long; +class Solution { + int n; +public: + long long countSubstrings(string s) + { + n = s.size(); + vectornums; + for (auto ch: s) + nums.push_back(ch-'0'); + nums.insert(nums.begin(), 0); + + LL ret = 0; + for (int k=1; k<=9; k++) + ret += helper(nums, k); + return ret; + } + + LL helper(vector&nums, int k) + { + vectorcount(k, 0); + vectorcount2(k,0); + LL ret = 0; + + int r = 0; + count[0] = 1; + for (int i=1; i<=n; i++) + { + for (int d=0; d Date: Sun, 9 Feb 2025 01:14:17 -0800 Subject: [PATCH 2691/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8dd8692b3..d99cd8366 100644 --- a/Readme.md +++ b/Readme.md @@ -211,6 +211,7 @@ [2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) [2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) [2950.Number-of-Divisible-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2950.Number-of-Divisible-Substrings) (H-) +[3448.Count-Substrings-Divisible-By-Last-Digit](https://github.com/wisdompeak/LeetCode/tree/master/Hash/3448.Count-Substrings-Divisible-By-Last-Digit) (H-) #### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/220.Contains-Duplicate-III) (M) From f71fb97fb40925f4fcbb8315dbe8130cea521934 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 02:11:37 -0800 Subject: [PATCH 2692/2729] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Hash/3448.Count-Substrings-Divisible-By-Last-Digit/Readme.md diff --git a/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/Readme.md b/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/Readme.md new file mode 100644 index 000000000..11cb9d3af --- /dev/null +++ b/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/Readme.md @@ -0,0 +1,21 @@ +### 3448.Count-Substrings-Divisible-By-Last-Digit + +这题很容易想到能否用“前缀+Hash”的套路来做。 + +假设`yyyxxxi`被d除的余数是r,那么我们能否找出某一段后缀是能被d整除的呢?我们不禁会想,如果前缀`yyy`被d除的余数恰好也是r,那么是否意味着`xxxi`就是能被d整除的呢?其实并不是。`xxxi`能被d整除的充要条件其实是`yyy0000`和`yyyxxxi`对于d同余,而不是`yyy`和`yyyxxxi`对于d同余。 + +于是我们发现,要判定以i为结尾的substring是否能被d整除,我们在Hash里就不能查找有多少“原始的前缀”的余数,而是应该查找有多少“升级后的前缀”的余数。比如说,当我们考察`abcdi`时,我们在Hash里记录的其实应该是`a0000`,`ab000`,`abc00`,`abcd0`对于d余数。这样方便我们和`abcdi`对于d的余数进行对照。如果有同余的,则说明当前有对应一段后缀能被d整除。 + +`abcd0`对于d余数从哪里来,其实就是`abcd`对于d余数r,再做变化r*10%r. + +`abc00`对于d余数从哪里来,其实就是`abc0`对于d余数r,再做变化得到`r*10%r`. 那么`abc0`对于d余数又从哪里来,其实就是`abc`对于d余数r,再做变化r*10%r. + +由此类推,我们只需要在每一轮,将Hash里存放的余数频次进行变化即可。比如说当前count里存放的是`a000`,`ab00`,`abc0`,`abcd`的余数频次,那么 +```cpp +for (int r=0; r Date: Sun, 9 Feb 2025 17:41:22 -0800 Subject: [PATCH 2693/2729] Create 3449.Maximize-the-Minimum-Game-Score.cpp --- .../3449.Maximize-the-Minimum-Game-Score.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Binary_Search/3449.Maximize-the-Minimum-Game-Score/3449.Maximize-the-Minimum-Game-Score.cpp diff --git a/Binary_Search/3449.Maximize-the-Minimum-Game-Score/3449.Maximize-the-Minimum-Game-Score.cpp b/Binary_Search/3449.Maximize-the-Minimum-Game-Score/3449.Maximize-the-Minimum-Game-Score.cpp new file mode 100644 index 000000000..eeea34179 --- /dev/null +++ b/Binary_Search/3449.Maximize-the-Minimum-Game-Score/3449.Maximize-the-Minimum-Game-Score.cpp @@ -0,0 +1,54 @@ +using LL = long long; +class Solution { + int n; +public: + long long maxScore(vector& points, int m) + { + n = points.size(); + LL left = 0, right = 1e15; + while (left < right) + { + LL mid = right - (right-left)/2; + if (checkOK(points, m, mid)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool checkOK(vector& points, LL M, LL P) + { + LL count = 1; + LL cur = points[0]; + + for (int i=0; i=P) return true; + LL d = (P-cur-1) / points[i] + 1; + return count+d*2 <= M; + } + + if (cur>=P) + { + count++; + if (count > M) return false; + cur = points[i+1]; + } + else + { + LL d = (P-cur-1) / points[i] + 1; + if (i==n-2 && count+d*2<=M && points[i+1]*d>=P) + return true; + + count += 2*d+1; + if (count > M) return false; + cur = points[i+1] * (d+1); + } + } + + return true; + } +}; From 1c5d6676341e7002f27eae47e4609ab57043fd5f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 17:42:22 -0800 Subject: [PATCH 2694/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d99cd8366..cf594d125 100644 --- a/Readme.md +++ b/Readme.md @@ -148,6 +148,7 @@ [3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) [3097.Shortest-Subarray-With-OR-at-Least-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II) (M) [3399.Smallest-Substring-With-Identical-Characters-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II) (H-) +[3449.Maximize-the-Minimum-Game-Score](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3449.Maximize-the-Minimum-Game-Score) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From a0ae3a88dd100f94c273705dafdd8577ae9866fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 22:14:19 -0800 Subject: [PATCH 2695/2729] Create Readme.md --- .../3449.Maximize-the-Minimum-Game-Score/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Binary_Search/3449.Maximize-the-Minimum-Game-Score/Readme.md diff --git a/Binary_Search/3449.Maximize-the-Minimum-Game-Score/Readme.md b/Binary_Search/3449.Maximize-the-Minimum-Game-Score/Readme.md new file mode 100644 index 000000000..53d35b1f8 --- /dev/null +++ b/Binary_Search/3449.Maximize-the-Minimum-Game-Score/Readme.md @@ -0,0 +1,11 @@ +### 3449.Maximize-the-Minimum-Game-Score + +考虑到m的范围异常的大,本题极有可能是二分搜值。我们猜测一个值X,然后检验是否能在m次移动后,使得所有的元素都大于等于X。 + +移动的策略似乎很明显可以贪心。当我在0号位置的时候,如果还没有实现得分大于X,必然会通过先朝右再朝左的反复横跳d次,直至满足0号位置大于等于X。为什么只选择在0号和1号位置的反复横跳而不是更大的幅度?感觉没有必要。如果更大幅度的反复横跳,不仅在0号位置和1号位置上各自增加d次赋分,而且会在2号及之后的位置上也增加d次赋分,但这些赋分是否值得呢?不见得。因此,我们只需要老老实实每次做幅度为1的来回横跳即可。 + +综上,我们的算法是:当我们来到i时,查看在该位置是否已经超过了预期得分。如果没有,那就计算还需要几次赋分(假设记作d次)。然后就再做`=>(i+1)=>i`的d次反复移动。在i位置上满足之后,再移动依次到i+1的位置上,此时注意我们已经在i+1的位置上得到了`points[i+1]*(d+1)`的分数。然后重复上述的过程。 + +需要特别注意的边界逻辑有两个地方: +1. 如果走到了最后一个位置,仍没有超过预期得分,那么只能进行“往左再往右”的反复横跳。 +2. 如果走到了倒数第二个位置,经过几次横跳之后,发现在此位置和下一个位置都已经满足了得分预期,那么最后一步可以不用再走了。 From 373e16835e19471644224fc0c036193e359da3b5 Mon Sep 17 00:00:00 2001 From: Eric Chou Date: Mon, 10 Feb 2025 21:12:50 +0800 Subject: [PATCH 2696/2729] Update LeetCode 208 link --- Trie/208.Implement-Trie--Prefix-Tree/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trie/208.Implement-Trie--Prefix-Tree/Readme.md b/Trie/208.Implement-Trie--Prefix-Tree/Readme.md index b00c62ee4..d7aed2b8b 100644 --- a/Trie/208.Implement-Trie--Prefix-Tree/Readme.md +++ b/Trie/208.Implement-Trie--Prefix-Tree/Readme.md @@ -7,4 +7,4 @@ 4. 在Trie树中找指定的前缀(不需要找到叶子节点) -[Leetcode Link](https://leetcode.com/problems/implement-trie--prefix-tree) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/implement-trie-prefix-tree) \ No newline at end of file From fe756936fe41d89fc5da8632780f24804b5ff7a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Feb 2025 00:41:33 -0800 Subject: [PATCH 2697/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md diff --git a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md new file mode 100644 index 000000000..181ee3917 --- /dev/null +++ b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md @@ -0,0 +1,11 @@ +### 3444.Minimum-Increments-for-Target-Multiples-in-an-Array + +本题的一个难点就是nums里的某个元素在变换后可以是targets里一个元素的倍数,也可以是多个元素的公倍数。此时如果注意到targets里的元素个数不超过4,应该可以想到枚举其所有的子集,来与nums里的某个数对应。因此这是一个基于bit mask的DP问题。 + +我们令dp[i][state]表示在nums的前i个元素里,已经满足了是targets里state代表的那些元素的倍数,需要的最少操作代价。此时针对nums[i]的决策无非两种情况。 +1. nums[i]并没有成为state里的任何元素的倍数,那么`dp[i][state]=dp[i-1][state]`. +2. nums[i]是state里某些元素的(公)倍数。于是我们需要枚举state里的子集subset,就有`dp[i][state]=dp[i-1][state-subset]+cost(nums[i], targets[subset]`。这里的cost,显然就是将nums[i]增加至targets[subset]所对应的最小公倍数即可。 + +最终答案就是dp[n][(1< Date: Fri, 14 Feb 2025 00:15:19 +0800 Subject: [PATCH 2698/2729] Fix integer overflow by using uint64_t for dp array --- Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp | 2 +- Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v2.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp b/Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp index 3f3465781..043f12224 100644 --- a/Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp +++ b/Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp @@ -2,7 +2,7 @@ class Solution { public: int change(int amount, vector& coins) { - vectordp(amount+1,0); + vectordp(amount+1,0); dp[0] = 1; for (int i=0; i& coins) { - vectordp(amount+1,0); + vectordp(amount+1,0); dp[0] = 1; for (int i=0; i Date: Fri, 14 Feb 2025 22:21:57 -0800 Subject: [PATCH 2699/2729] Update 3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp --- ...ments-for-Target-Multiples-in-an-Array.cpp | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp index f29402b4a..86b5d5a9f 100644 --- a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp +++ b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp @@ -1,20 +1,18 @@ class Solution { int dp[50005][1<<4]; - public: int minimumIncrements(vector& nums, vector& target) { - int m = target.size(); int n = nums.size(); + int m = target.size(); nums.insert(nums.begin(), 0); - int ret = INT_MAX/2; - - for (int state = 0; state < (1<0; subset=(subset-1)&state) @@ -23,15 +21,13 @@ class Solution { for (int j=0; j>j)&1) - L = lcm(L, target[j]); - if (L>INT_MAX/2) break; - } - if (L>INT_MAX/2) continue; - int cost = (nums[i]%L==0)?0:(L-nums[i]%L); - dp[i][state] = min(dp[i][state], dp[i-1][state-subset] + cost); + L = lcm(L, target[j]); + } + long long cost = (nums[i] % L == 0) ? 0 : (L - nums[i]%L); + dp[i][state] = min((long long)dp[i][state], (long long)dp[i-1][state-subset] + cost); } } - + return dp[n][(1< Date: Sun, 16 Feb 2025 22:53:54 -0800 Subject: [PATCH 2700/2729] Update Readme.md --- .../Readme.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md index 181ee3917..c71750ff3 100644 --- a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md +++ b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md @@ -7,5 +7,3 @@ 2. nums[i]是state里某些元素的(公)倍数。于是我们需要枚举state里的子集subset,就有`dp[i][state]=dp[i-1][state-subset]+cost(nums[i], targets[subset]`。这里的cost,显然就是将nums[i]增加至targets[subset]所对应的最小公倍数即可。 最终答案就是dp[n][(1< Date: Sun, 16 Feb 2025 23:08:23 -0800 Subject: [PATCH 2701/2729] Create 3458.Select-K-Disjoint-Special-Substrings.cpp --- ...8.Select-K-Disjoint-Special-Substrings.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings.cpp diff --git a/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings.cpp b/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings.cpp new file mode 100644 index 000000000..e452ea401 --- /dev/null +++ b/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + bool maxSubstringLength(string s, int k) + { + int n = s.size(); + vector>pos(26); + for (int i=0; i>intervals; + for (int letter=0; letter<26; letter++) + { + if (pos[letter].empty()) continue; + int start = pos[letter][0]; + int i = start; + int far = pos[letter].back(); + + bool flag = true; + while (i<=far) + { + far = max(far, pos[s[i]-'a'].back()); + if (pos[s[i]-'a'][0]=k; + } + + + int helper(vector> &intervals) { + sort(intervals.begin(), intervals.end(), [](pair a, pair b) { + return a.second < b.second; + }); + + int count = 0; + int far = INT_MIN; + + for (auto &interval : intervals) + { + if (interval.first > far) { + count++; + far = interval.second; + } + } + return count; + } +}; From 3c52d1e2ad193fe4216b3a1495e2581312e58298 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Feb 2025 23:09:06 -0800 Subject: [PATCH 2702/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index cf594d125..ba7baba3a 100644 --- a/Readme.md +++ b/Readme.md @@ -1480,6 +1480,7 @@ [3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) +[3458.Select-K-Disjoint-Special-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3458.Select-K-Disjoint-Special-Substrings) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 403a93e2690b81ee4e275e1851933aaff3e467f6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Feb 2025 23:23:21 -0800 Subject: [PATCH 2703/2729] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md diff --git a/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md b/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md new file mode 100644 index 000000000..a599d5957 --- /dev/null +++ b/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md @@ -0,0 +1,11 @@ +### 3458.Select-K-Disjoint-Special-Substrings + +此题是若干个套路题的缝合。 + +首先我们要找出所有self-contained的substring,这等同于`3104. Find Longest Self-Contained Substring`. 例如,我们寻找以字母'a'开头的self-contained的substring,必然会找原字符串中'a'第一次出现的位置start。然后从那个位置往后推进,至少要推进到原字符串中'a'最后一次出现的位置end。在推进的过程中,如果遇到任何新的字符比如说'b',那么做两件事: +1. 检查'b'第一次出现的位置是否在start之前,如果是的话,那么立即停止并退出。因为包含'a'的自包含的substring无法满足'b'的自包含。 +2. 如果通过了第一条,那么我们查看'b'最后一次出现的位置,需要将end更新至更远,以保证'a''b'都是自包含的。 + +如果推进的过程持续至指针追上了end,那么意味着[start,end]区间内的所有字母都是自包含的。 + +我们由此可以得到最多26段自包含的区间。我们需要判断是否至少有k个区间是彼此不相交的。这就等同于`435.Non-overlapping-Intervals`. 一个常见的贪心的做法,就是将所有区间按照尾端点排序。贪心的原则就是:如果有若干个彼此相交的区间,根据规则我们最多只能取一个,那必然只会选择尾端点更靠前的,这样会留给后续更多的空间能选择不相交的区间。所以我们必然选择排序后的第一个区间,然后顺序检查后续的区间,如果与其相交的区间都舍弃;此时下一个区间就是选择的第二个区间:因为它与首区间不相交,且尾端点是剩下所有里面最靠前的。以此类推。 From 37c8c8258303304a95f1907ac86fa30997b685b7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Feb 2025 16:48:34 -0800 Subject: [PATCH 2704/2729] Update Readme.md --- Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md b/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md index a599d5957..b489c0f20 100644 --- a/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md +++ b/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md @@ -8,4 +8,7 @@ 如果推进的过程持续至指针追上了end,那么意味着[start,end]区间内的所有字母都是自包含的。 -我们由此可以得到最多26段自包含的区间。我们需要判断是否至少有k个区间是彼此不相交的。这就等同于`435.Non-overlapping-Intervals`. 一个常见的贪心的做法,就是将所有区间按照尾端点排序。贪心的原则就是:如果有若干个彼此相交的区间,根据规则我们最多只能取一个,那必然只会选择尾端点更靠前的,这样会留给后续更多的空间能选择不相交的区间。所以我们必然选择排序后的第一个区间,然后顺序检查后续的区间,如果与其相交的区间都舍弃;此时下一个区间就是选择的第二个区间:因为它与首区间不相交,且尾端点是剩下所有里面最靠前的。以此类推。 +我们需要判断是否至少有k个区间是彼此不相交的。这就等同于`435.Non-overlapping-Intervals`. 一个常见的贪心的做法,就是将所有区间按照尾端点排序。贪心的原则就是:如果有若干个彼此相交的区间,根据规则我们最多只能取一个,那必然只会选择尾端点更靠前的,这样会留给后续更多的空间能选择不相交的区间。所以我们必然选择排序后的第一个区间,然后顺序检查后续的区间,如果与其相交的区间都舍弃;此时下一个区间就是选择的第二个区间:因为它与首区间不相交,且尾端点是剩下所有里面最靠前的。以此类推。 + +事实上,还有更简单的计算逻辑。我们得到的最多26段自包含的区间,要么互斥,要么互相嵌套,不可能出现部分相交的情况。分析见`1520. Maximum Number of Non-Overlapping Substrings`. 所以我们只需要两两比较,如果大的包含小的,去掉大的即可。 + From 3b899e7be1ac8ac8c7c6cad4638bdf6cb9583d2a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Feb 2025 16:51:40 -0800 Subject: [PATCH 2705/2729] Create 3458.Select-K-Disjoint-Special-Substrings_v2.cpp --- ...elect-K-Disjoint-Special-Substrings_v2.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings_v2.cpp diff --git a/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings_v2.cpp b/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings_v2.cpp new file mode 100644 index 000000000..1cecdda41 --- /dev/null +++ b/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings_v2.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + bool maxSubstringLength(string s, int k) + { + int n = s.size(); + vector>pos(26); + for (int i=0; i>intervals; + for (int letter=0; letter<26; letter++) + { + if (pos[letter].empty()) continue; + int start = pos[letter][0]; + int i = start; + int far = pos[letter].back(); + + bool flag = true; + while (i<=far) + { + far = max(far, pos[s[i]-'a'].back()); + if (pos[s[i]-'a'][0]=k; + } + + bool contains(paira, pairb) + { + return a.firstb.second; + } + + int helper(vector> &intervals) { + int n = intervals.size(); + vectorcheck(n, 1); + for (int i=0; i Date: Mon, 17 Feb 2025 16:53:11 -0800 Subject: [PATCH 2706/2729] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index ba7baba3a..7d6b6bfb4 100644 --- a/Readme.md +++ b/Readme.md @@ -1437,7 +1437,6 @@ 826.Most-Profit-Assigning-Work (M) [1268.Search-Suggestions-System](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1268.Search-Suggestions-System) (H-) [1402.Reducing-Dishes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1402.Reducing-Dishes) (M) -[1520.Maximum-Number-of-Non-Overlapping-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1520.Maximum-Number-of-Non-Overlapping-Substrings) (H-) [1564.Put-Boxes-Into-the-Warehouse-I](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1564.Put-Boxes-Into-the-Warehouse-I) (M+) [1665.Minimum-Initial-Energy-to-Finish-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1665.Minimum-Initial-Energy-to-Finish-Tasks) (H-) [1686.Stone-Game-VI](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1686.Stone-Game-VI) (H-) @@ -1478,8 +1477,10 @@ [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) [3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) -[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) -[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) +[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) +[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) +3104.Find Longest Self-Contained Substring (TBD) +[1520.Maximum-Number-of-Non-Overlapping-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1520.Maximum-Number-of-Non-Overlapping-Substrings) (H-) [3458.Select-K-Disjoint-Special-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3458.Select-K-Disjoint-Special-Substrings) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) From 1205ff0995690e5451b58ef7c9be70041cbbbb95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Feb 2025 00:02:42 -0800 Subject: [PATCH 2707/2729] Create 3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp --- ...h-of-Longest-V-Shaped-Diagonal-Segment.cpp | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp diff --git a/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp b/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp new file mode 100644 index 000000000..630d01175 --- /dev/null +++ b/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp @@ -0,0 +1,59 @@ +class Solution { + vector>dir; + int memo[501][501][4][2]; +public: + int lenOfVDiagonal(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + int ret = 0; + dir = {{-1,1},{1,1},{1,-1},{-1,-1}}; + + for (int i=0; i=0 && i=0 && j>& grid, int x, int y, int k, int t) + { + if (memo[x][y][k][t]!=0) return memo[x][y][k][t]; + + int m = grid.size(), n = grid[0].size(); + int ret = 1; + + int i = x+dir[k].first, j = y+dir[k].second; + + if (inbound(i,j,m,n) && canContinue(grid[x][y], grid[i][j])) + ret = max(ret, 1 + dfs(grid,i,j,k,t)); + + if (t==1) + { + int kk=(k+1)%4; + i = x+dir[k].first, j = y+dir[k].second; + if (inbound(i,j,m,n) && canContinue(grid[x][y], grid[i][j])) + ret = max(ret, 1 + dfs(grid,i,j,kk,0)); + } + memo[x][y][k][t] = ret; + return ret; + } +}; From 02094c93dba6f18388e71e4bcd85d2012664164c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Feb 2025 00:03:08 -0800 Subject: [PATCH 2708/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7d6b6bfb4..e2b33d869 100644 --- a/Readme.md +++ b/Readme.md @@ -552,6 +552,7 @@ [2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) [2065.Maximum-Path-Quality-of-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2065.Maximum-Path-Quality-of-a-Graph) (M) [2850.Minimum-Moves-to-Spread-Stones-Over-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid) (M) +[3459.Length-of-Longest-V-Shaped-Diagonal-Segment](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment) (M+) * ``search in an array`` [090.Subsets-II](https://github.com/wisdompeak/LeetCode/tree/master/DFS/090.Subsets-II) (M+) [301.Remove-Invalid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/DFS/301.Remove-Invalid-Parentheses) (H) From 0bba13046978502f24d5e026d695cb41eb6f86cf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Feb 2025 00:15:59 -0800 Subject: [PATCH 2709/2729] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/Readme.md diff --git a/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/Readme.md b/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/Readme.md new file mode 100644 index 000000000..4d9e572bd --- /dev/null +++ b/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/Readme.md @@ -0,0 +1,9 @@ +### 3459.Length-of-Longest-V-Shaped-Diagonal-Segment + +很常规的深度优先搜索。每个格子、每个方向只会进入一次。所以最多有`500*500*4=1e6`种状态。再加上有一次转弯的机会,所以2e6种状态是可以遍历和存储下来的。 + +定义dfs(x,y,k,t)表示以k的方向进入(x,y)的格子、且还有t次转弯机会时,还能走的最长路径。如果t==0,那么只能按照k的方向进入下一个(i1,j1);否则还可以考察按照k+1的方向进入下一个(i2,j2). + +注意进入的下一个各自(i,j)和(x,y)要满足数值上的约束,否则即可停止往下搜索。 + +此外,本题的记忆化根据四个参数进行记忆化也是必须的。 From b508b0d0ab68837013ca4c7bcdde71e634e5d2d2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Feb 2025 00:41:44 -0800 Subject: [PATCH 2710/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index e2b33d869..d5c8f42bd 100644 --- a/Readme.md +++ b/Readme.md @@ -1479,7 +1479,7 @@ [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) [3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) -[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) +[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) 3104.Find Longest Self-Contained Substring (TBD) [1520.Maximum-Number-of-Non-Overlapping-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1520.Maximum-Number-of-Non-Overlapping-Substrings) (H-) [3458.Select-K-Disjoint-Special-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3458.Select-K-Disjoint-Special-Substrings) (H-) From d83cea183bd4febf7e359d05f0a6da328b965601 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Feb 2025 23:59:46 -0800 Subject: [PATCH 2711/2729] Create Lucas.cpp --- Template/Math/Lucas.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Template/Math/Lucas.cpp diff --git a/Template/Math/Lucas.cpp b/Template/Math/Lucas.cpp new file mode 100644 index 000000000..27c293bd0 --- /dev/null +++ b/Template/Math/Lucas.cpp @@ -0,0 +1,20 @@ +/* + To compute C(n,m) % p, when p is a small prime (and we cannot use Fermat's Little Theorem) + https://oi-wiki.org/math/number-theory/lucas/ +*/ + +long long Lucas(long long n, long long m, long long p) { + if (m == 0) return 1; + return (C(n % p, m % p) * Lucas(n / p, m / p, p)) % p; +} + +long long C(int n, int m) +{ + long long cnt = 1; + for(int i = 0; i < m; i++) + { + cnt *= n - i; + cnt /= i + 1; + } + return cnt; +} From d921f7c66d65e5973e7fb1242c0fbd1c93a12e0a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Feb 2025 00:03:55 -0800 Subject: [PATCH 2712/2729] Create 3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp --- ...re-Equal-in-String-After-Operations-II.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp diff --git a/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp new file mode 100644 index 000000000..d4c69486e --- /dev/null +++ b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp @@ -0,0 +1,48 @@ +using LL = long long; + +class Solution { +public: + bool hasSameDigits(string s) + { + return check(s,5) && check(s,2); + } + + long long Lucas(long long n, long long m, long long p) { + if (m == 0) return 1; + return (C(n % p, m % p) * Lucas(n / p, m / p, p)) % p; + } + + long long C(int n, int m) + { + long long cnt = 1; + for(int i = 0; i < m; i++) + { + cnt *= n - i; + cnt /= i + 1; + } + return cnt; + } + + bool check(string s, int p) + { + int n = s.size(); + + int m = n-2; + int ret1 = 0; + for (int i=0; i Date: Mon, 24 Feb 2025 00:04:20 -0800 Subject: [PATCH 2713/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d5c8f42bd..0297e73aa 100644 --- a/Readme.md +++ b/Readme.md @@ -1294,6 +1294,7 @@ [3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) [3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) [3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences) (M+) +[3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II) (H+) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From 2e5ac27c370305913a09fdd1e918dbd42f533e6b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Feb 2025 00:35:03 -0800 Subject: [PATCH 2714/2729] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md diff --git a/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md new file mode 100644 index 000000000..beea6c1f3 --- /dev/null +++ b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md @@ -0,0 +1,22 @@ +### 3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II + +我们不难发现,如果将一个数组nums按照题目描述中的方法操作直至只剩一个元素,中间过程其实构造了一个杨辉倒三角形。每个元素对于最终结果的贡献次数,对应于二项式系数的分布(binomial coefficient)。假设nums长度是n+1,那么nums[i]在最终的结果中被累加了C(n,i)次。 + +根据题意,我们想求nums里前n-1个元素按照二项式系数权重累加后对于10的余数,是否等于nums里后n-1个元素按照二项式系数权重累加后对于10的余数。这其中就涉及到如何求任意的`C(m,k)%10`。C(m,k)里面有除法,对它的取模需要涉及除数的逆元。 + +首先,我们不能用费马小定理。因为这里的模数是10,并不是一个质数。此时可以想到分拆为2和5. 事实上,如果a与b关于2同余,并且关于5同余,那么一定关于10同余。所以我们对于本题,需要做两次分别关于2和5的同余的检查。 + +此时,我们能否用费马小定理求逆元呢?依然不能。费马小定理的使用有个条件,b不能被p整除。 +``` +a / b (mod p) = a * inv(b) (mod p) +where inv(b) = b^(p-2) and b cannot be divided by p. +``` +这里的p非常小,分别是2和5,很容易被组合数计算表达式的分母整除。 + +因此此题涉及到了一个非常专业的知识点,Lucas定理。见https://oi-wiki.org/math/number-theory/lucas/ +``` +long long Lucas(long long n, long long m, long long p) { + if (m == 0) return 1; + return (C(n % p, m % p, p) * Lucas(n / p, m / p, p)) % p; +} +``` From bf7d25a5d9133567cb29ff0e9672218ff20a09b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Feb 2025 00:36:06 -0800 Subject: [PATCH 2715/2729] Update Readme.md --- .../Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md index beea6c1f3..bacce3201 100644 --- a/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md +++ b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md @@ -13,10 +13,11 @@ where inv(b) = b^(p-2) and b cannot be divided by p. ``` 这里的p非常小,分别是2和5,很容易被组合数计算表达式的分母整除。 -因此此题涉及到了一个非常专业的知识点,Lucas定理。见https://oi-wiki.org/math/number-theory/lucas/ +因此此题涉及到了一个生僻的知识点,Lucas定理。见https://oi-wiki.org/math/number-theory/lucas/ ``` long long Lucas(long long n, long long m, long long p) { if (m == 0) return 1; return (C(n % p, m % p, p) * Lucas(n / p, m / p, p)) % p; } ``` +用这个函数,我们就直接求得了`C(n,i)%p`的值,再作为nums[i]的系数带入计算。 From 6eb1f47e40d50eba73ac822f0ff1364c57dbb66c Mon Sep 17 00:00:00 2001 From: Eric Chou Date: Wed, 12 Mar 2025 02:37:22 +0800 Subject: [PATCH 2716/2729] Fix integer overflow in LC260. Single Number III - Changed `int` to `long long` for variable `s` to prevent overflow when handling `INT_MIN` (`-2147483648`). - Updated `t` to use `long long` to ensure correctness in bit manipulation. - Fixes issue with new test case: `nums = [1,1,0,-2147483648]`, where `int` overflowed due to `s & (s-1)`. --- .../260.Single-Number-III/260.Single-Number-III.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Bit_Manipulation/260.Single-Number-III/260.Single-Number-III.cpp b/Bit_Manipulation/260.Single-Number-III/260.Single-Number-III.cpp index d5a308b60..bbfea14a2 100644 --- a/Bit_Manipulation/260.Single-Number-III/260.Single-Number-III.cpp +++ b/Bit_Manipulation/260.Single-Number-III/260.Single-Number-III.cpp @@ -2,9 +2,9 @@ class Solution { public: vector singleNumber(vector& nums) { - int s = 0; + long long s = 0; for (auto n:nums) s = s^n; // i.e. a^b - int t = s^(s&(s-1)); // only keep the rightmost set bit + long long t = s^(s&(s-1)); // only keep the rightmost set bit int a = 0, b = 0; for (auto n:nums) { From 2fe597c6ae7b42986fed91ca311f3c30010b85c6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 11:45:43 -0700 Subject: [PATCH 2717/2729] Create 3490.Count-Beautiful-Numbers.cpp --- .../3490.Count-Beautiful-Numbers.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Recursion/3490.Count-Beautiful-Numbers/3490.Count-Beautiful-Numbers.cpp diff --git a/Recursion/3490.Count-Beautiful-Numbers/3490.Count-Beautiful-Numbers.cpp b/Recursion/3490.Count-Beautiful-Numbers/3490.Count-Beautiful-Numbers.cpp new file mode 100644 index 000000000..0891090f8 --- /dev/null +++ b/Recursion/3490.Count-Beautiful-Numbers/3490.Count-Beautiful-Numbers.cpp @@ -0,0 +1,47 @@ +using State = tuple; + +class Solution { +public: + map memo; + vector digits; + + int dfs(int pos, int sum, int product, bool tight, bool leading_zero) + { + if (pos == digits.size()) { + return (sum > 0) && (product % sum == 0); + } + + State key = {pos, sum, product, tight, leading_zero}; + if (memo.find(key) != memo.end()) return memo[key]; + + int limit = (tight ? digits[pos] : 9); + int res = 0; + + for (int d = 0; d <= limit; d++) + { + res += dfs(pos + 1, sum + d, (leading_zero && d == 0) ? 1 : product * d, tight && (d == limit), leading_zero && (d == 0)); + } + + return memo[key] = res; + } + + int count(int T) + { + if (T <= 0) return 0; + digits.clear(); + memo.clear(); + + while (T > 0) + { + digits.push_back(T % 10); + T /= 10; + } + reverse(digits.begin(), digits.end()); + return dfs(0, 0, 1, true, true); + } + + int beautifulNumbers(int l, int r) + { + return count(r) - count(l-1); + } +}; From a254b3cc21a00928abbf944f2bdb74475a4f8dc0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 11:46:26 -0700 Subject: [PATCH 2718/2729] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0297e73aa..1cb5984d3 100644 --- a/Readme.md +++ b/Readme.md @@ -1165,7 +1165,8 @@ [2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) [2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) -[3307.Find-the-K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the-K-th-Character-in-String-Game-II) (M) +[3307.Find-the-K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the-K-th-Character-in-String-Game-II) (M) +[3490.Count-Beautiful-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3490.Count-Beautiful-Numbers) (M+) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From c3bb91f8f6a13f89f4fc4de330b53e3b559f67ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 11:59:07 -0700 Subject: [PATCH 2719/2729] Create Readme.md --- Recursion/3490.Count-Beautiful-Numbers/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Recursion/3490.Count-Beautiful-Numbers/Readme.md diff --git a/Recursion/3490.Count-Beautiful-Numbers/Readme.md b/Recursion/3490.Count-Beautiful-Numbers/Readme.md new file mode 100644 index 000000000..b11758572 --- /dev/null +++ b/Recursion/3490.Count-Beautiful-Numbers/Readme.md @@ -0,0 +1,11 @@ +### 3490.Count-Beautiful-Numbers + +常见的数位DP或者递归搜索。本质我们需要设计一个函数count(T)来记录0-T之间所有符合条件的数。 + +因为beautiful number最多只有10位,每个位置最多只有0-9共十种填法,我们可以逐位搜索。搜索过程中,第pos个位置上的可选决策受到两个先前状态的制约: +1. 该位置是否贴近上限T。如果pos之前的选择都是贴着上限T,那么在第pos位上,我们的选择上限也只能是T[pos],否则上限可以是9. +2. 该位置是否是先导零。如果pos之前的选择全部都是0,那么在pos位置之前记录的乘积应该强制认作是1。这么做是为了处理这样一种情况:pos之前都是0,并且pos位也想取零。如果没有这条规则,那么递归到后面的乘积就永远是零了。 + +由此,我们一旦做出了pos位置上的鞠策,在往后递归的时候,也需要相应更新isTight和isLeadingZero这两个状态。 + +递归需要记忆化的支持。本题记忆化的状态就是递归函数的参数:pos, sum, product, isTight, isLeadingZero。我们可以用tuple作为key,加上有序map来存储访问过的状态。 From 98d5feba56cf615688745d8a71512ba9229261d9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 12:04:09 -0700 Subject: [PATCH 2720/2729] Update Readme.md --- Recursion/3490.Count-Beautiful-Numbers/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Recursion/3490.Count-Beautiful-Numbers/Readme.md b/Recursion/3490.Count-Beautiful-Numbers/Readme.md index b11758572..923b9750c 100644 --- a/Recursion/3490.Count-Beautiful-Numbers/Readme.md +++ b/Recursion/3490.Count-Beautiful-Numbers/Readme.md @@ -9,3 +9,12 @@ 由此,我们一旦做出了pos位置上的鞠策,在往后递归的时候,也需要相应更新isTight和isLeadingZero这两个状态。 递归需要记忆化的支持。本题记忆化的状态就是递归函数的参数:pos, sum, product, isTight, isLeadingZero。我们可以用tuple作为key,加上有序map来存储访问过的状态。 + +有人会问product的个数会不会很大?事实上9个digit想乘,可以得到的不同的乘积并不大。 +``` +st = {1} # 空集的乘积(乘法单位元) +for _ in range(9): # 9 个数相乘 + st = set(x * d for x in st for d in range(10)) # 每个数从 0 到 9 +print(len(st)) # 3026 +``` +总的记忆化状态数目最多`9*81*3000*2*2=8748000`,恰好可以接受。 From 1c2b0ff7aeb37f693c22fe0850a3e60ff16e16a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 12:11:51 -0700 Subject: [PATCH 2721/2729] Create 3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp diff --git a/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp new file mode 100644 index 000000000..e52102668 --- /dev/null +++ b/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int minZeroArray(vector& nums, vector>& queries) + { + int n = nums.size(); + int left = 0, right = queries.size(); + while (left < right) + { + int mid = left+(right-left)/2; + if (isOK(nums, queries, mid)) + right = mid; + else + left = mid+1; + } + if (isOK(nums,queries, left)) return left; + else return -1; + } + + bool isOK(vector& nums, vector>& queries, int t) + { + int n = nums.size(); + vector>diff(n+1); + for (int i=0; iSet; + for (int i=0; i0) Set.insert(x); + else Set.erase(Set.lower_bound(-x)); + } + if (!subsetSum(Set, nums[i])) + return false; + } + return true; + } + + bool subsetSum(multiset& nums, int target) + { + vector dp(target + 1, false); + dp[0] = true; + for (int num : nums) + { + for (int j = target; j >= num; j--) { + if (dp[j - num]) + dp[j] = true; + } + } + return dp[target]; + } +}; From 976e0c8f9198b6f244af76359be2f796e88d6f2e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 12:12:17 -0700 Subject: [PATCH 2722/2729] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1cb5984d3..5e7b25640 100644 --- a/Readme.md +++ b/Readme.md @@ -1620,6 +1620,7 @@ [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) [3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) [3169.Count-Days-Without-Meetings](https://github.com/wisdompeak/LeetCode/tree/master/Others/3169.Count-Days-Without-Meetings) (M) +[3489.Zero-Array-Transformation-IV](https://github.com/wisdompeak/LeetCode/tree/master/Others/3489.Zero-Array-Transformation-IV) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 15cfdf2fb1e3d22e78565631faf3be774ca811ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:28:29 -0700 Subject: [PATCH 2723/2729] Create 3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp diff --git a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp new file mode 100644 index 000000000..e52102668 --- /dev/null +++ b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int minZeroArray(vector& nums, vector>& queries) + { + int n = nums.size(); + int left = 0, right = queries.size(); + while (left < right) + { + int mid = left+(right-left)/2; + if (isOK(nums, queries, mid)) + right = mid; + else + left = mid+1; + } + if (isOK(nums,queries, left)) return left; + else return -1; + } + + bool isOK(vector& nums, vector>& queries, int t) + { + int n = nums.size(); + vector>diff(n+1); + for (int i=0; iSet; + for (int i=0; i0) Set.insert(x); + else Set.erase(Set.lower_bound(-x)); + } + if (!subsetSum(Set, nums[i])) + return false; + } + return true; + } + + bool subsetSum(multiset& nums, int target) + { + vector dp(target + 1, false); + dp[0] = true; + for (int num : nums) + { + for (int j = target; j >= num; j--) { + if (dp[j - num]) + dp[j] = true; + } + } + return dp[target]; + } +}; From 962c080de1200ab83555770e7e542ec60b34d06c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:28:42 -0700 Subject: [PATCH 2724/2729] Create Readme.md --- .../3489.Zero-Array-Transformation-IV/Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Dynamic_Programming/3489.Zero-Array-Transformation-IV/Readme.md diff --git a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/Readme.md b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/Readme.md new file mode 100644 index 000000000..476ca9320 --- /dev/null +++ b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/Readme.md @@ -0,0 +1,17 @@ +### 3489.Zero-Array-Transformation-IV + +这本质是一个背包问题。每处理一个query,在对应区间内的nums[i]就多得了一次删减的操作。 + +我们需要查看这些nums[i]在获得这个额外的删减机会之后,是否能连同之前的删减操作,实现置零?很显然,如果该query能够让nums[i]再削减d,那么就取决于nums[i]之前能否削减至d。 + +我们令dp[i][v]表示如果nums[i]的数值是v,能否最终削减成为零。就有 +``` +for q: queries + a = q[0], b = q[1], d = q[2]; + for (i=a; i=b; i++) { + for (int v=0; v<=1000; v++) { + dp[i][v] = dp[i][v] || d[i][v-d]; + } + } +``` +最终查看所有的dp[i][nums[i]]是否为true。 From 56cb89e88c5ae0aa391fd81d405c65eb1143c713 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:30:07 -0700 Subject: [PATCH 2725/2729] Delete Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 56 ------------------- 1 file changed, 56 deletions(-) delete mode 100644 Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp diff --git a/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp deleted file mode 100644 index e52102668..000000000 --- a/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp +++ /dev/null @@ -1,56 +0,0 @@ -class Solution { -public: - int minZeroArray(vector& nums, vector>& queries) - { - int n = nums.size(); - int left = 0, right = queries.size(); - while (left < right) - { - int mid = left+(right-left)/2; - if (isOK(nums, queries, mid)) - right = mid; - else - left = mid+1; - } - if (isOK(nums,queries, left)) return left; - else return -1; - } - - bool isOK(vector& nums, vector>& queries, int t) - { - int n = nums.size(); - vector>diff(n+1); - for (int i=0; iSet; - for (int i=0; i0) Set.insert(x); - else Set.erase(Set.lower_bound(-x)); - } - if (!subsetSum(Set, nums[i])) - return false; - } - return true; - } - - bool subsetSum(multiset& nums, int target) - { - vector dp(target + 1, false); - dp[0] = true; - for (int num : nums) - { - for (int j = target; j >= num; j--) { - if (dp[j - num]) - dp[j] = true; - } - } - return dp[target]; - } -}; From cc9deb103f66c27f9b1fbc2ff81426f41204ffed Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:30:57 -0700 Subject: [PATCH 2726/2729] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5e7b25640..c89ddc8a7 100644 --- a/Readme.md +++ b/Readme.md @@ -857,6 +857,7 @@ [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) [2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) [2902.Count-of-Sub-Multisets-With-Bounded-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum) (H) +[3489.Zero-Array-Transformation-IV](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3489.Zero-Array-Transformation-IV) (H-) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) @@ -1620,7 +1621,6 @@ [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) [3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) [3169.Count-Days-Without-Meetings](https://github.com/wisdompeak/LeetCode/tree/master/Others/3169.Count-Days-Without-Meetings) (M) -[3489.Zero-Array-Transformation-IV](https://github.com/wisdompeak/LeetCode/tree/master/Others/3489.Zero-Array-Transformation-IV) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 6c2efd5e54917422011a5cd63df6cae66bc924f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:42:00 -0700 Subject: [PATCH 2727/2729] Update 3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 66 +++++++------------ 1 file changed, 24 insertions(+), 42 deletions(-) diff --git a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp index e52102668..5f8e44b98 100644 --- a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp +++ b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp @@ -1,56 +1,38 @@ class Solution { + int dp[10][1005]; public: - int minZeroArray(vector& nums, vector>& queries) - { - int n = nums.size(); - int left = 0, right = queries.size(); - while (left < right) - { - int mid = left+(right-left)/2; - if (isOK(nums, queries, mid)) - right = mid; - else - left = mid+1; - } - if (isOK(nums,queries, left)) return left; - else return -1; - } - - bool isOK(vector& nums, vector>& queries, int t) + bool isOK(vector& nums) { - int n = nums.size(); - vector>diff(n+1); - for (int i=0; iSet; - for (int i=0; i0) Set.insert(x); - else Set.erase(Set.lower_bound(-x)); + flag = 0; + break; } - if (!subsetSum(Set, nums[i])) - return false; } - return true; + return flag; } - bool subsetSum(multiset& nums, int target) + int minZeroArray(vector& nums, vector>& queries) { - vector dp(target + 1, false); - dp[0] = true; - for (int num : nums) + for (int i=0; i= num; j--) { - if (dp[j - num]) - dp[j] = true; - } + int a = queries[k][0], b = queries[k][1], d = queries[k][2]; + for (int i=a; i<=b; i++) + { + for (int v=1000; v>=0; v--) + if (v>=d) dp[i][v] = (dp[i][v] || dp[i][v-d]); + } + + if (isOK(nums)) return k+1; } - return dp[target]; + return -1; } }; From f938d2966291a612e078a28716c81102afc5d5b0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 01:28:19 -0700 Subject: [PATCH 2728/2729] Update 3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp index 5f8e44b98..5ffad9060 100644 --- a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp +++ b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp @@ -1,38 +1,34 @@ class Solution { - int dp[10][1005]; + int dp[10][1001]; public: bool isOK(vector& nums) { - int flag = 1; for (int i=0; i& nums, vector>& queries) { for (int i=0; i=0; v--) - if (v>=d) dp[i][v] = (dp[i][v] || dp[i][v-d]); - } - + if (v>=d && dp[i][v-d] == true) + dp[i][v] = true; + } if (isOK(nums)) return k+1; } - return -1; + return -1; } }; From 83a42a33dff1462d073505a91bb1988923b17cbe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 01:32:11 -0700 Subject: [PATCH 2729/2729] Update Readme.md --- Recursion/3490.Count-Beautiful-Numbers/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/3490.Count-Beautiful-Numbers/Readme.md b/Recursion/3490.Count-Beautiful-Numbers/Readme.md index 923b9750c..542d37d94 100644 --- a/Recursion/3490.Count-Beautiful-Numbers/Readme.md +++ b/Recursion/3490.Count-Beautiful-Numbers/Readme.md @@ -6,7 +6,7 @@ 1. 该位置是否贴近上限T。如果pos之前的选择都是贴着上限T,那么在第pos位上,我们的选择上限也只能是T[pos],否则上限可以是9. 2. 该位置是否是先导零。如果pos之前的选择全部都是0,那么在pos位置之前记录的乘积应该强制认作是1。这么做是为了处理这样一种情况:pos之前都是0,并且pos位也想取零。如果没有这条规则,那么递归到后面的乘积就永远是零了。 -由此,我们一旦做出了pos位置上的鞠策,在往后递归的时候,也需要相应更新isTight和isLeadingZero这两个状态。 +由此,我们一旦做出了pos位置上的决策,在往后递归的时候,也需要相应更新isTight和isLeadingZero这两个状态。 递归需要记忆化的支持。本题记忆化的状态就是递归函数的参数:pos, sum, product, isTight, isLeadingZero。我们可以用tuple作为key,加上有序map来存储访问过的状态。