From 397ed3c0b630fec3b3acf89d1fc72750e7d3e20b Mon Sep 17 00:00:00 2001 From: Razak Date: Thu, 26 Aug 2021 15:10:19 +0530 Subject: [PATCH 01/33] C++ IMPLEMENTATION OF 205 --- .../isomorphic_strings.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 0205_isomorphic_strings/isomorphic_strings.cpp diff --git a/0205_isomorphic_strings/isomorphic_strings.cpp b/0205_isomorphic_strings/isomorphic_strings.cpp new file mode 100644 index 0000000..5eb6551 --- /dev/null +++ b/0205_isomorphic_strings/isomorphic_strings.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +class Solution +{ +public: + string mp(string s) + { + map m; + string ans = ""; + for (auto c : s) + { + if (m.find(c) == m.end()) + { + m[c] = m.size(); + } + ans += m[c]; + } + return ans; + } + bool isIsomorphic(string s, string t) + { + if (mp(s) == mp(t)) + { + return true; + } + return false; + } +}; + +int main() +{ + string s, t; + cout << "Enter 2 Strings : "; + cin >> s >> t; + Solution sol; + if (sol.isIsomorphic(s, t)) + { + cout << "True"; + } + else + { + cout << "False"; + } +} \ No newline at end of file From e8d1f7c082ec0edd4dec63c433e6ef9a36aa8556 Mon Sep 17 00:00:00 2001 From: Pratik Goyal Date: Thu, 26 Aug 2021 19:22:50 +0530 Subject: [PATCH 02/33] Updated strstr.cc Implemented Rabin-Karp Algorithm for 0028_implement_strstr --- 0028_implement_strstr/strstr.cc | 40 ++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/0028_implement_strstr/strstr.cc b/0028_implement_strstr/strstr.cc index 08808ff..1262839 100644 --- a/0028_implement_strstr/strstr.cc +++ b/0028_implement_strstr/strstr.cc @@ -4,7 +4,41 @@ using namespace std; class Solution { public: - int strStr(string haystack, string needle) { - return haystack.find(needle); - } + + // Rabin-Karp Algorithm for string matching + int strStr(string haystack, string needle) { + long long mod = 1e9 + 7, p = 53; + int h = haystack.size(), n = needle.size(); + if (h < n) return -1; + if (n == 0) return 0; + + // precalculating powers of p + vector p_pow(max(h, n)); + p_pow[0] = 1; + for (int i = 1; i < p_pow.size(); i++) { + p_pow[i] = (p_pow[i - 1] * p) % mod; + } + // calculating haystack_hash + vector haystack_hash(haystack.size() + 1, 0); + for (int i = 0; i < h; i++) { + haystack_hash[i + 1] = (haystack_hash[i] + (haystack[i] - 'a' + 1) * p_pow[i]) % mod; + } + + // calculating needle_hash + long long needle_hash = 0; + for (int i = 0; i < n; i++) { + needle_hash = (needle_hash + (needle[i] - 'a' + 1) * p_pow[i]) % mod; + } + + // checking for matching hashes + for (int i = 0; i <= h - n; i++) { + long long curr_hash = (haystack_hash[i + n] + mod - haystack_hash[i]) % mod; + if (curr_hash == (needle_hash * p_pow[i]) % mod) { + return i; + } + } + + // if no hash is find + return -1; + } }; From 6d87a27915502d0f85fffadc2fa55f69440d31a9 Mon Sep 17 00:00:00 2001 From: Zuchen Liu Date: Wed, 1 Sep 2021 17:46:28 +0800 Subject: [PATCH 03/33] case 0012 bug fix --- 0012_roman_numeral/roman_numeral.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/0012_roman_numeral/roman_numeral.c b/0012_roman_numeral/roman_numeral.c index 4bdb8ec..b66c249 100644 --- a/0012_roman_numeral/roman_numeral.c +++ b/0012_roman_numeral/roman_numeral.c @@ -82,7 +82,8 @@ static char *intToRoman(int num) num2char(&p, hundred_bit, 2); num2char(&p, ten_bit, 1); num2char(&p, one_bit, 0); - + *p = '\0'; + return roman_numeral; } From 3926f977f86cdd8ab41f2686ca64c934923ae5b7 Mon Sep 17 00:00:00 2001 From: Pratik Goyal Date: Tue, 5 Oct 2021 21:31:13 +0530 Subject: [PATCH 04/33] Added C++ Implementation --- .../longest_palindromic_substring.cc | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 0005_longest_palindromic_substring/longest_palindromic_substring.cc diff --git a/0005_longest_palindromic_substring/longest_palindromic_substring.cc b/0005_longest_palindromic_substring/longest_palindromic_substring.cc new file mode 100644 index 0000000..3b95bb1 --- /dev/null +++ b/0005_longest_palindromic_substring/longest_palindromic_substring.cc @@ -0,0 +1,25 @@ +#include + +using namespace std; + +class Solution { +public: + string longestPalindrome(string s) { + bool dp[1005][1005]; + int n = s.size(); + int strlen = 0, start; + for(int i=n-1; i>=0; i--){ + for(int j=i; j Date: Mon, 9 Jan 2023 19:45:36 +0800 Subject: [PATCH 05/33] Add 0990 satisfiability of equality equations Signed-off-by: begeekmyfriend --- .../Makefile | 2 + .../equality_equations.c | 74 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 0990_satisfiability_of_equality_equations/Makefile create mode 100644 0990_satisfiability_of_equality_equations/equality_equations.c diff --git a/0990_satisfiability_of_equality_equations/Makefile b/0990_satisfiability_of_equality_equations/Makefile new file mode 100644 index 0000000..1e9c818 --- /dev/null +++ b/0990_satisfiability_of_equality_equations/Makefile @@ -0,0 +1,2 @@ +all: + gcc -o test equality_equations.c diff --git a/0990_satisfiability_of_equality_equations/equality_equations.c b/0990_satisfiability_of_equality_equations/equality_equations.c new file mode 100644 index 0000000..4d93265 --- /dev/null +++ b/0990_satisfiability_of_equality_equations/equality_equations.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include + + +struct ufs { + int parents[512]; +}; + +static inline void ufs_init(struct ufs *set) +{ + int i; + for (i = 0; i < sizeof(set->parents) / sizeof(int); i++) { + set->parents[i] = i; + } +} + +static inline int ufs_find(struct ufs *set, int node) +{ + assert(node >= 0 && node <= sizeof(set->parents) / sizeof(int)); + if (set->parents[node] != node) { + set->parents[node] = ufs_find(set, set->parents[node]); + } + return set->parents[node]; +} + +static inline void ufs_union(struct ufs *set, int p, int q) +{ + int root_p, root_q; + + root_p = ufs_find(set, p); + root_q = ufs_find(set, q); + /* Omit root_p == root_q if-condition */ + set->parents[root_p] = root_q; +} + +static inline bool ufs_connected(struct ufs *set, int p, int q) +{ + return ufs_find(set, p) == ufs_find(set, q); +} + +bool equationsPossible(char ** equations, int equationsSize) +{ + int i; + struct ufs *set; + + set = malloc(sizeof(*set)); + ufs_init(set); + + for (i = 0; i < equationsSize; i++) { + if (equations[i][1] == '=') { + ufs_union(set, equations[i][0], equations[i][3]); + } + } + + for (i = 0; i < equationsSize; i++) { + if (equations[i][1] == '!') { + if (ufs_connected(set, equations[i][0], equations[i][3])) { + return false; + } + } + } + + return true; +} + +int main(int argc, char **argv) +{ + //char *equations[] = {"a==b", "c==c", "x==y" }; + char *equations[] = {"a==b", "b!=c", "a==c" }; + printf("%s\n", equationsPossible(equations, sizeof(equations)/sizeof(char *)) ? "true" : "false"); + return 0; +} From 1c913a481c14c7db7048c0c1bbd3f4056a06ab21 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 8 Oct 2023 21:57:16 +0800 Subject: [PATCH 06/33] Update comment Signed-off-by: begeekmyfriend --- 0206_reverse_linked_list/reverse_list.c | 2 ++ 0206_reverse_linked_list/reverse_list.cc | 2 ++ 2 files changed, 4 insertions(+) diff --git a/0206_reverse_linked_list/reverse_list.c b/0206_reverse_linked_list/reverse_list.c index 9031752..22c65bd 100644 --- a/0206_reverse_linked_list/reverse_list.c +++ b/0206_reverse_linked_list/reverse_list.c @@ -31,8 +31,10 @@ struct ListNode *reverseList(struct ListNode *head) struct ListNode *prev = NULL; struct ListNode *p = head; while (p != NULL) { + /* prev <- p <- q */ struct ListNode *q = p->next; p->next = prev; + /* step */ prev = p; p = q; } diff --git a/0206_reverse_linked_list/reverse_list.cc b/0206_reverse_linked_list/reverse_list.cc index 212aee6..426a748 100644 --- a/0206_reverse_linked_list/reverse_list.cc +++ b/0206_reverse_linked_list/reverse_list.cc @@ -18,8 +18,10 @@ class Solution { ListNode *prev = nullptr; ListNode *p = head; while (p != nullptr) { + // prev <- p <- q ListNode *q = p->next; p->next = prev; + // step prev = p; p = q; } From db352a9121c44a4c307ecb3860878102b38afcd0 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 21 Oct 2023 18:58:50 +0800 Subject: [PATCH 07/33] Update comments Signed-off-by: begeekmyfriend --- 0046_permutations/permutations.c | 22 +++++++++++--------- 0046_permutations/permutations.cc | 24 +++++++++++---------- 0047_permutations_ii/permutations.c | 31 +++++++++++++++------------- 0047_permutations_ii/permutations.cc | 7 ++++--- 4 files changed, 46 insertions(+), 38 deletions(-) diff --git a/0046_permutations/permutations.c b/0046_permutations/permutations.c index e901c03..9f9ca36 100644 --- a/0046_permutations/permutations.c +++ b/0046_permutations/permutations.c @@ -41,16 +41,18 @@ static void dfs(int *nums, int size, bool *used, int *stack, memcpy(results[*count], stack, size * sizeof(int)); col_size[*count] = size; (*count)++; - } else { - /* Reverse order is allowed in different levels, always starts from [0] */ - for (i = 0; i < size; i++) { - if (!used[i]) { - /* Used marks only allows remaining elements in DFS levels */ - used[i] = true; - stack[len] = nums[i]; - dfs(nums, size, used, stack, len + 1, results, count, col_size); - used[i] = false; - } + return; + } + + /* Reverse order is allowed in different levels, always starts from [0] */ + for (i = 0; i < size; i++) { + if (!used[i]) { + /* Used marks all the allowable remaining elements in the next DFS + * levels */ + stack[len] = nums[i]; + used[i] = true; + dfs(nums, size, used, stack, len + 1, results, count, col_size); + used[i] = false; } } } diff --git a/0046_permutations/permutations.cc b/0046_permutations/permutations.cc index acef735..35b4efe 100644 --- a/0046_permutations/permutations.cc +++ b/0046_permutations/permutations.cc @@ -16,17 +16,19 @@ class Solution { void dfs(vector& nums, vector& used, vector>& res) { if (stack.size() == nums.size()) { res.push_back(stack); - } else { - // Reverse order is allowed in different levels, always starts from [0] - for (int i = 0; i < nums.size(); i++) { - if (!used[i]) { - // Used marks only allows remaining elements in DFS levels - used[i] = true; - stack.push_back(nums[i]); - dfs(nums, used, res); - stack.pop_back(); - used[i] = false; - } + return; + } + + // Reverse order is allowed in different levels, always starts from [0] + for (int i = 0; i < nums.size(); i++) { + if (!used[i]) { + // Used marks all the allowable remaining elements in the next + // DFS levels + used[i] = true; + stack.push_back(nums[i]); + dfs(nums, used, res); + stack.pop_back(); + used[i] = false; } } } diff --git a/0047_permutations_ii/permutations.c b/0047_permutations_ii/permutations.c index 13d2fe4..96688cb 100644 --- a/0047_permutations_ii/permutations.c +++ b/0047_permutations_ii/permutations.c @@ -12,26 +12,29 @@ static void dfs(int *nums, int size, bool *used, int *stack, int len, int **results, int *count, int *col_size) { int i; + if (len == size) { results[*count] = malloc(len * sizeof(int)); memcpy(results[*count], stack, len * sizeof(int)); col_size[*count] = size; (*count)++; - } else { - /* Reverse order is allowed in different levels, always starts from [0] */ - for (i = 0; i < size; i++) { - /* Used marks only allows remaining elements in DFS levels */ - if (!used[i]) { - if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { - /* In case duplicate permutation with same elemements in the same postion */ - /* used[i - 1] == true means different level position */ - continue; - } - used[i] = true; - stack[len] = nums[i]; - dfs(nums, size, used, stack, len + 1, results, count, col_size); - used[i] = false; + return; + } + + /* Reverse order is allowed in different levels, always starts from [0] */ + for (i = 0; i < size; i++) { + /* used marks remaining allowable elements in the next DFS level */ + if (!used[i]) { + if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { + /* !used[i - 1] means the upper DFS level does not contain + * nums[i - 1] such that we need to exclude the duplicate + * enumeration that has been recorded with used[i - 1]==true. */ + continue; } + stack[len] = nums[i]; + used[i] = true; + dfs(nums, size, used, stack, len + 1, results, count, col_size); + used[i] = false; } } } diff --git a/0047_permutations_ii/permutations.cc b/0047_permutations_ii/permutations.cc index 70c3e46..de8bdff 100644 --- a/0047_permutations_ii/permutations.cc +++ b/0047_permutations_ii/permutations.cc @@ -19,11 +19,12 @@ class Solution { res.push_back(stack); } else { for (int i = 0; i < nums.size(); i++) { - // Used marks only allows remaining elements in DFS levels + // used marks remaining allowable elements in the next DFS level if (!used[i]) { if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { - // In case duplicate permutation with same elemements in the same postion - // used[i - 1] == true means different level position + // !used[i - 1] means the upper DFS level does not contain + // nums[i - 1] such that we need to exclude the duplicate + // enumeration that has been recorded with used[i-1]==true. continue; } stack.push_back(nums[i]); From 198f46cfcc2096160f997a821f6c0c3df0065880 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 22 Oct 2023 18:17:15 +0800 Subject: [PATCH 08/33] Update comments Signed-off-by: begeekmyfriend --- 0015_three_sum/three_sum.c | 8 +++++++- 0018_four_sum/four_sum.c | 19 ++++++++++++------- 0031_next_permutation/next_permutation.cc | 8 ++------ 0167_two_sum_ii/two_sum.c | 8 ++++---- 0167_two_sum_ii/two_sum.cc | 6 +++--- 5 files changed, 28 insertions(+), 21 deletions(-) diff --git a/0015_three_sum/three_sum.c b/0015_three_sum/three_sum.c index 7ce5dbd..53cd947 100644 --- a/0015_three_sum/three_sum.c +++ b/0015_three_sum/three_sum.c @@ -31,7 +31,7 @@ static void two_sum(int *nums, int low, int high, int target, int **results, int ** Return an array of arrays of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ -int** threeSum(int* nums, int numsSize, int* returnSize) +int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { if (numsSize < 3) { return NULL; @@ -47,6 +47,12 @@ int** threeSum(int* nums, int numsSize, int* returnSize) two_sum(nums, i + 1, numsSize - 1, -nums[i], results, returnSize); } } + + *returnColumnSizes = malloc(*returnSize * sizeof(int *)); + for (i = 0; i < *returnSize; i++) { + (*returnColumnSizes)[i] = 3; + } + return results; } diff --git a/0018_four_sum/four_sum.c b/0018_four_sum/four_sum.c index ebeeabb..8b8a182 100644 --- a/0018_four_sum/four_sum.c +++ b/0018_four_sum/four_sum.c @@ -8,8 +8,8 @@ static int compare(const void *a, const void *b) return *(int *) a - *(int *) b; } -static void k_sum(int *nums, int low, int high, int target, int total, int k, - int *stack, int len, int **results, int *count, int *col_sizes) +static void k_sum(int *nums, int low, int high, long target, int total, int k, + int *stack, int len, int **results, int *count) { int i; if (k == 2) { @@ -24,7 +24,6 @@ static void k_sum(int *nums, int low, int high, int target, int total, int k, stack[len++] = nums[high]; results[*count] = malloc(total * sizeof(int)); memcpy(results[*count], stack, total * sizeof(int)); - col_sizes[*count] = total; (*count)++; len -= 2; while (++low < high && nums[low] == nums[low - 1]) {} @@ -36,7 +35,8 @@ static void k_sum(int *nums, int low, int high, int target, int total, int k, for (i = low; i <= high - k + 1; i++) { if (i > low && nums[i] == nums[i - 1]) continue; stack[len] = nums[i]; - k_sum(nums, i + 1, high, target - nums[i], 4, k - 1, stack, len + 1, results, count, col_sizes); + k_sum(nums, i + 1, high, target - nums[i], 4, k - 1, stack, + len + 1, results, count); } } } @@ -49,15 +49,20 @@ static void k_sum(int *nums, int low, int high, int target, int total, int k, int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes) { *returnSize = 0; - int i, j, capacity = 50000; + int i, capacity = 50000; int **results = malloc(capacity * sizeof(int *)); - *returnColumnSizes = malloc(capacity * sizeof(int)); if (numsSize >= 4) { qsort(nums, numsSize, sizeof(*nums), compare); int *stack = malloc(4 * sizeof(int)); - k_sum(nums, 0, numsSize - 1, target, 4, 4, stack, 0, results, returnSize, *returnColumnSizes); + k_sum(nums, 0, numsSize - 1, target, 4, 4, stack, 0, results, returnSize); } + + *returnColumnSizes = malloc(capacity * sizeof(int)); + for (i = 0; i < *returnSize; i++) { + (*returnColumnSizes)[i] = 4; + } + return results; } diff --git a/0031_next_permutation/next_permutation.cc b/0031_next_permutation/next_permutation.cc index d1c7f72..5b8256c 100644 --- a/0031_next_permutation/next_permutation.cc +++ b/0031_next_permutation/next_permutation.cc @@ -5,10 +5,6 @@ using namespace std; class Solution { public: void nextPermutation(vector& nums) { - if (nums.size() < 2) { - return; - } - int i = nums.size() - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { i--; @@ -16,10 +12,10 @@ class Solution { if (i >= 0) { int j = nums.size() - 1; - while (j >= 0 && nums[j] >= nums[i]) { + while (j >= 0 && nums[i] >= nums[j]) { j--; } - swap(nums.begin() + i, nums.begin() + j); + swap(nums[i], nums[j]); } reverse(nums.begin() + i + 1, nums.end()); diff --git a/0167_two_sum_ii/two_sum.c b/0167_two_sum_ii/two_sum.c index 86d4c4d..7478668 100644 --- a/0167_two_sum_ii/two_sum.c +++ b/0167_two_sum_ii/two_sum.c @@ -9,14 +9,14 @@ static int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) { int i = 0, j = numbersSize - 1; while (i < j) { - int diff = target - numbers[i] - numbers[j]; - if (diff > 0) { + int sum = numbers[i] + numbers[j]; + if (sum < target) { i++; - } else if (diff < 0) { + } else if (sum > target) { j--; } else { *returnSize = 2; - int *indexes = malloc(*returnSize * sizeof(int)); + int *indexes = malloc(2 * sizeof(int)); indexes[0] = i + 1; indexes[1] = j + 1; return indexes; diff --git a/0167_two_sum_ii/two_sum.cc b/0167_two_sum_ii/two_sum.cc index 4ba80b8..c8c1610 100644 --- a/0167_two_sum_ii/two_sum.cc +++ b/0167_two_sum_ii/two_sum.cc @@ -9,10 +9,10 @@ class Solution { int i = 0; int j = numbers.size() - 1; while (i < j) { - int diff = target - numbers[i] - numbers[j]; - if (diff > 0) { + int sum = numbers[i] + numbers[j]; + if (sum < target) { i++; - } else if (diff < 0) { + } else if (sum > target) { j--; } else { res.push_back(i + 1); From d547944da2776361c785dfe1578ca1eb7193eb9b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 23 Oct 2023 11:18:57 +0800 Subject: [PATCH 09/33] Update comments Signed-off-by: begeekmyfriend --- 0042_trapping_rain_water/trap_water.c | 27 +++++++++++++ 0042_trapping_rain_water/trap_water.cc | 2 + .../rect_in_histogram.c | 24 +++++------ 0085_maximal_rectangle/maximal_rectangle.c | 40 ++++++++++--------- 4 files changed, 62 insertions(+), 31 deletions(-) diff --git a/0042_trapping_rain_water/trap_water.c b/0042_trapping_rain_water/trap_water.c index 5f184e4..a304e24 100644 --- a/0042_trapping_rain_water/trap_water.c +++ b/0042_trapping_rain_water/trap_water.c @@ -1,6 +1,31 @@ #include #include +#if 0 +static int trap(int* height, int heightSize) +{ + int i, res = 0; + int *lmax = malloc(heightSize * sizeof(int)); + int *rmax = malloc(heightSize * sizeof(int)); + + lmax[0] = height[0]; + rmax[heightSize - 1] = height[heightSize - 1]; + + for (i = 1; i < heightSize; i++) { + lmax[i] = height[i] > lmax[i - 1] ? height[i] : lmax[i - 1] ; + } + + for (i = heightSize - 2; i >= 0; i--) { + rmax[i] = height[i] > rmax[i + 1] ? height[i] : rmax[i + 1] ; + } + + for (i = 1; i < heightSize - 1; i++) { + res += (lmax[i] < rmax[i] ? lmax[i] : rmax[i] ) - height[i]; + } + + return res; +} +#endif static int trap(int* height, int heightSize) { @@ -12,6 +37,7 @@ static int trap(int* height, int heightSize) int r = heightSize - 1, rmax = 0; while (l < r) { if (height[l] < height[r]) { + /* Only lmax is needed for lmax < rmax here */ if (height[l] > lmax) { lmax = height[l]; } else { @@ -19,6 +45,7 @@ static int trap(int* height, int heightSize) } l++; } else { + /* Only rmax is needed for rmax < lmax here */ if (height[r] > rmax) { rmax = height[r]; } else { diff --git a/0042_trapping_rain_water/trap_water.cc b/0042_trapping_rain_water/trap_water.cc index 42be139..dd91e7e 100644 --- a/0042_trapping_rain_water/trap_water.cc +++ b/0042_trapping_rain_water/trap_water.cc @@ -13,6 +13,7 @@ class Solution { int right = height.size() - 1, right_max = 0; while (left < right) { if (height[left] < height[right]) { + /* Only lmax is needed for lmax < rmax here */ if (height[left] > left_max) { left_max = height[left]; } else { @@ -20,6 +21,7 @@ class Solution { } left++; } else { + /* Only rmax is needed for rmax < lmax here */ if (height[right] > right_max) { right_max = height[right]; } else { diff --git a/0084_largest_rectangle_in_histogram/rect_in_histogram.c b/0084_largest_rectangle_in_histogram/rect_in_histogram.c index 49116ff..4e302ad 100644 --- a/0084_largest_rectangle_in_histogram/rect_in_histogram.c +++ b/0084_largest_rectangle_in_histogram/rect_in_histogram.c @@ -3,33 +3,33 @@ static int largestRectangleArea(int* heights, int heightsSize) { - int *indexes = malloc(heightsSize * sizeof(int)); - int *left = malloc(heightsSize * sizeof(int)); - int *right = malloc(heightsSize * sizeof(int)); + int *idx_stk = malloc(heightsSize * sizeof(int)); + int *lmax = malloc(heightsSize * sizeof(int)); + int *rmax = malloc(heightsSize * sizeof(int)); int i, pos = 0; for (i = 0; i < heightsSize; i++) { - /* monotonous increasing stack */ - while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { + /* keep monotonous increasing stack */ + while (pos > 0 && heights[i] < heights[idx_stk[pos - 1]]) { pos--; } - left[i] = pos == 0 ? -1 : indexes[pos - 1]; - indexes[pos++] = i; + lmax[i] = pos == 0 ? -1 : idx_stk[pos - 1]; + idx_stk[pos++] = i; } pos = 0; for (i = heightsSize - 1; i >= 0; i--) { - /* monotonous increasing stack */ - while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { + /* keep monotonous increasing stack */ + while (pos > 0 && heights[i] < heights[idx_stk[pos - 1]]) { pos--; } - right[i] = pos == 0 ? heightsSize : indexes[pos - 1]; - indexes[pos++] = i; + rmax[i] = pos == 0 ? heightsSize : idx_stk[pos - 1]; + idx_stk[pos++] = i; } int max_area = 0; for (i = 0; i < heightsSize; i++) { - int area = heights[i] * (right[i] - left[i] - 1); + int area = heights[i] * (rmax[i] - lmax[i] - 1); max_area = area > max_area ? area : max_area; } diff --git a/0085_maximal_rectangle/maximal_rectangle.c b/0085_maximal_rectangle/maximal_rectangle.c index c33ad1c..3f620c3 100644 --- a/0085_maximal_rectangle/maximal_rectangle.c +++ b/0085_maximal_rectangle/maximal_rectangle.c @@ -10,49 +10,49 @@ static inline int max(int a, int b) static int area_calc(int *heights, int size) { - int *indexes = malloc(size * sizeof(int)); - int *lhist = malloc(size * sizeof(int)); - int *rhist = malloc(size * sizeof(int)); + int *idx_stk = malloc(size * sizeof(int)); + int *lmax = malloc(size * sizeof(int)); + int *rmax = malloc(size * sizeof(int)); int i, pos = 0; for (i = 0; i < size; i++) { - /* squeeze to keep monotonous increasing histograms */ - while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { + /* keep monotonous increasing maxograms */ + while (pos > 0 && heights[i] < heights[idx_stk[pos - 1]]) { pos--; } - lhist[i] = pos == 0 ? -1 : indexes[pos - 1]; - indexes[pos++] = i; + lmax[i] = pos == 0 ? -1 : idx_stk[pos - 1]; + idx_stk[pos++] = i; } pos = 0; for (i = size - 1; i >= 0; i--) { - /* squeeze to keep monotonous increasing histograms */ - while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { + /* keep monotonous increasing maxograms */ + while (pos > 0 && heights[i] < heights[idx_stk[pos - 1]]) { pos--; } - rhist[i] = pos == 0 ? size : indexes[pos - 1]; - indexes[pos++] = i; + rmax[i] = pos == 0 ? size : idx_stk[pos - 1]; + idx_stk[pos++] = i; } int max_area = 0; for (i = 0; i < size; i++) { - int area = heights[i] * (rhist[i] - lhist[i] - 1); + int area = heights[i] * (rmax[i] - lmax[i] - 1); max_area = max(area, max_area); } return max_area; } -static int maximalRectangle(char** matrix, int matrixRowSize, int matrixColSize) +static int maximalRectangle(char** matrix, int matrixSize, int* matrixColSize) { int i, j, max_area = 0; - int *heights = malloc(matrixColSize * sizeof(int)); - memset(heights, 0, matrixColSize * sizeof(int)); - for (i = 0; i < matrixRowSize; i++) { - for (j = 0; j < matrixColSize; j++) { + int *heights = malloc(matrixColSize[0] * sizeof(int)); + memset(heights, 0, matrixColSize[0] * sizeof(int)); + for (i = 0; i < matrixSize; i++) { + for (j = 0; j < matrixColSize[i]; j++) { heights[j] = matrix[i][j] == '1' ? heights[j] + 1 : 0; } - max_area = max(max_area, area_calc(heights, matrixColSize)); + max_area = max(max_area, area_calc(heights, matrixColSize[i])); } return max_area; } @@ -68,9 +68,11 @@ int main(int argc, char **argv) int i, j; int row_size = argc - 1; int col_size = strlen(argv[1]); + int *cols = malloc(row_size * sizeof(int)); for (i = 0; i < row_size; i++) { + cols[i] = strlen(argv[1]); printf("%s\n", argv[i + 1]); } - printf("%d\n", maximalRectangle(argv + 1, argc - 1, strlen(argv[1]))); + printf("%d\n", maximalRectangle(argv + 1, argc - 1, cols)); return 0; } From c8116b509eed986d5e0bf9931ede0b27013bba29 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 26 Oct 2023 20:40:23 +0800 Subject: [PATCH 10/33] Use __typeof for compile compatibility Signed-off-by: begeekmyfriend --- .../concatenation.c | 4 ++-- .../binary_tree_build.c | 4 ++-- .../binary_tree_build.c | 4 ++-- 0123_best_time_to_buy_and_sell_stock_iii/stock.c | 2 +- 0126_word_ladder_ii/word_ladder.c | 4 ++-- 0127_word_ladder/word_ladder.c | 4 ++-- 0128_longest_consecutive_sequence/consec_seq.c | 4 ++-- 0133_clone_graph/clone_graph.c | 4 ++-- 0140_word_break_ii/word_break.c | 4 ++-- 0146_lru_cache/lru_cache.c | 10 +++++----- 0149_max_points_on_a_line/points_on_line.c | 4 ++-- 0166_fraction_to_recurring_decimal/fraction.c | 4 ++-- 0460_lfu_cache/lfu_cache.c | 10 +++++----- 13 files changed, 31 insertions(+), 31 deletions(-) diff --git a/0030_substring_with_concatenation_of_all_words/concatenation.c b/0030_substring_with_concatenation_of_all_words/concatenation.c index 4018389..475cc45 100644 --- a/0030_substring_with_concatenation_of_all_words/concatenation.c +++ b/0030_substring_with_concatenation_of_all_words/concatenation.c @@ -11,9 +11,9 @@ container_of(ptr, type, member) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c b/0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c index f0be239..53d4916 100644 --- a/0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c +++ b/0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c @@ -9,9 +9,9 @@ container_of(ptr, type, member) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c b/0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c index b37dd41..5adb6ab 100644 --- a/0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c +++ b/0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c @@ -9,9 +9,9 @@ container_of(ptr, type, member) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0123_best_time_to_buy_and_sell_stock_iii/stock.c b/0123_best_time_to_buy_and_sell_stock_iii/stock.c index c0e38ef..55172db 100644 --- a/0123_best_time_to_buy_and_sell_stock_iii/stock.c +++ b/0123_best_time_to_buy_and_sell_stock_iii/stock.c @@ -53,7 +53,7 @@ static int maxProfit(int* prices, int pricesSize) int total = left_profit[pricesSize - 1]; for (i = pricesSize - 2; i >= 0; i--) { if (prices[i] > max) { - max = prices[i]; + max = prices[i]; } else { tmp = max - prices[i]; right_profit = tmp > right_profit ? tmp : right_profit; diff --git a/0126_word_ladder_ii/word_ladder.c b/0126_word_ladder_ii/word_ladder.c index 963b6b4..9efc70f 100644 --- a/0126_word_ladder_ii/word_ladder.c +++ b/0126_word_ladder_ii/word_ladder.c @@ -13,9 +13,9 @@ #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0127_word_ladder/word_ladder.c b/0127_word_ladder/word_ladder.c index dc12247..f057487 100644 --- a/0127_word_ladder/word_ladder.c +++ b/0127_word_ladder/word_ladder.c @@ -12,9 +12,9 @@ #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0128_longest_consecutive_sequence/consec_seq.c b/0128_longest_consecutive_sequence/consec_seq.c index 3d52eda..f3e5d3f 100644 --- a/0128_longest_consecutive_sequence/consec_seq.c +++ b/0128_longest_consecutive_sequence/consec_seq.c @@ -9,9 +9,9 @@ container_of(ptr, type, member) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0133_clone_graph/clone_graph.c b/0133_clone_graph/clone_graph.c index 748c342..1c18389 100644 --- a/0133_clone_graph/clone_graph.c +++ b/0133_clone_graph/clone_graph.c @@ -9,9 +9,9 @@ container_of(ptr, type, member) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0140_word_break_ii/word_break.c b/0140_word_break_ii/word_break.c index e987eae..588bc1e 100644 --- a/0140_word_break_ii/word_break.c +++ b/0140_word_break_ii/word_break.c @@ -10,9 +10,9 @@ container_of(ptr, type, member) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0146_lru_cache/lru_cache.c b/0146_lru_cache/lru_cache.c index 79c8cf5..205896c 100644 --- a/0146_lru_cache/lru_cache.c +++ b/0146_lru_cache/lru_cache.c @@ -11,15 +11,15 @@ #define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) #define list_for_each_entry_safe(pos, n, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member), \ - n = list_entry(pos->member.next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member), \ + n = list_entry(pos->member.next, __typeof(*pos), member); \ &pos->member != (head); \ - pos = n, n = list_entry(n->member.next, typeof(*n), member)) + pos = n, n = list_entry(n->member.next, __typeof(*n), member)) struct list_head { struct list_head *next, *prev; diff --git a/0149_max_points_on_a_line/points_on_line.c b/0149_max_points_on_a_line/points_on_line.c index 3291c69..c0ad22f 100644 --- a/0149_max_points_on_a_line/points_on_line.c +++ b/0149_max_points_on_a_line/points_on_line.c @@ -11,9 +11,9 @@ container_of(ptr, type, member) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0166_fraction_to_recurring_decimal/fraction.c b/0166_fraction_to_recurring_decimal/fraction.c index b2c7a8b..f1c90ff 100644 --- a/0166_fraction_to_recurring_decimal/fraction.c +++ b/0166_fraction_to_recurring_decimal/fraction.c @@ -11,9 +11,9 @@ container_of(ptr, type, member) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) struct list_head { struct list_head *next, *prev; diff --git a/0460_lfu_cache/lfu_cache.c b/0460_lfu_cache/lfu_cache.c index a902948..fdcfb77 100644 --- a/0460_lfu_cache/lfu_cache.c +++ b/0460_lfu_cache/lfu_cache.c @@ -13,15 +13,15 @@ #define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) #define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member); \ &(pos)->member != (head); \ - pos = list_entry((pos)->member.next, typeof(*pos), member)) + pos = list_entry((pos)->member.next, __typeof(*pos), member)) #define list_for_each_entry_safe(pos, n, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member), \ - n = list_entry(pos->member.next, typeof(*pos), member); \ + for (pos = list_entry((head)->next, __typeof(*pos), member), \ + n = list_entry(pos->member.next, __typeof(*pos), member); \ &pos->member != (head); \ - pos = n, n = list_entry(n->member.next, typeof(*n), member)) + pos = n, n = list_entry(n->member.next, __typeof(*n), member)) struct list_head { struct list_head *next, *prev; From aca3d041d3571abcf02981c6874677f032db577e Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 27 Oct 2023 12:09:28 +0800 Subject: [PATCH 11/33] Improvement Signed-off-by: begeekmyfriend --- .../consec_seq.c | 23 +++------ .../consec_seq.cc | 27 ++++++++++ 0130_surrounded_regions/surrounded_regions.c | 49 ++++++++++--------- 3 files changed, 58 insertions(+), 41 deletions(-) create mode 100644 0128_longest_consecutive_sequence/consec_seq.cc diff --git a/0128_longest_consecutive_sequence/consec_seq.c b/0128_longest_consecutive_sequence/consec_seq.c index f3e5d3f..d42b664 100644 --- a/0128_longest_consecutive_sequence/consec_seq.c +++ b/0128_longest_consecutive_sequence/consec_seq.c @@ -94,26 +94,15 @@ int longestConsecutive(int* nums, int numsSize) } for (i = 0; i < numsSize; i++) { - int len = 0; - int num; - node = find(nums[i], numsSize, heads); - while (node != NULL) { - len++; - num = node->num; - list_del(&node->link); - - int left = num; - while ((node = find(--left, numsSize, heads)) != NULL) { + /* Find the first consecutive number */ + node = find(nums[i] - 1, numsSize, heads); + if (node == NULL) { + int len = 0; + int num = nums[i]; + while ((node = find(num++, numsSize, heads)) != NULL) { len++; list_del(&node->link); } - - int right = num; - while ((node = find(++right, numsSize, heads)) != NULL) { - len++; - list_del(&node->link); - } - length = len > length ? len : length; } } diff --git a/0128_longest_consecutive_sequence/consec_seq.cc b/0128_longest_consecutive_sequence/consec_seq.cc new file mode 100644 index 0000000..fa264fc --- /dev/null +++ b/0128_longest_consecutive_sequence/consec_seq.cc @@ -0,0 +1,27 @@ +#include + +using namespace std; + +class Solution { +public: + int longestConsecutive(vector& nums) { + int res = 0; + unordered_set s; + for (int i = 0; i < nums.size(); i++) { + s.insert(nums[i]); + } + for (int n : nums) { + if (!s.count(n - 1)) { + int len = 0; + int num = n; + while (s.count(num)) { + s.erase(num); + num++; + len++; + } + res = len > res ? len : res; + } + } + return res; + } +}; diff --git a/0130_surrounded_regions/surrounded_regions.c b/0130_surrounded_regions/surrounded_regions.c index ab2cf6d..701f5ed 100644 --- a/0130_surrounded_regions/surrounded_regions.c +++ b/0130_surrounded_regions/surrounded_regions.c @@ -117,7 +117,7 @@ static void bfs(char **board, int row_size, int col_size, } } -void solve(char** board, int boardRowSize, int boardColSize) +void solve(char** board, int boardSize, int *boardColSize) { int i, j; struct node *new; @@ -126,48 +126,48 @@ void solve(char** board, int boardRowSize, int boardColSize) INIT_LIST_HEAD(&queue); INIT_LIST_HEAD(&free_list); - for (i = 0; i < boardColSize; i++) { + for (i = 0; i < boardColSize[0]; i++) { if (board[0][i] == 'O') { new = node_new(&free_list); new->x = 0; new->y = i; list_add_tail(&new->link, &queue); - bfs(board, boardRowSize, boardColSize, &queue, &free_list); + bfs(board, boardSize, boardColSize[0], &queue, &free_list); } } - for (i = 0; i < boardColSize; i++) { - if (board[boardRowSize - 1][i] == 'O') { + for (i = 0; i < boardColSize[0]; i++) { + if (board[boardSize - 1][i] == 'O') { new = node_new(&free_list); - new->x = boardRowSize - 1; + new->x = boardSize - 1; new->y = i; list_add_tail(&new->link, &queue); - bfs(board, boardRowSize, boardColSize, &queue, &free_list); + bfs(board, boardSize, boardColSize[0], &queue, &free_list); } } - for (i = 0; i < boardRowSize; i++) { + for (i = 0; i < boardSize; i++) { if (board[i][0] == 'O') { new = node_new(&free_list); new->x = i; new->y = 0; list_add_tail(&new->link, &queue); - bfs(board, boardRowSize, boardColSize, &queue, &free_list); + bfs(board, boardSize, boardColSize[i], &queue, &free_list); } } - for (i = 0; i < boardRowSize; i++) { - if (board[i][boardColSize - 1] == 'O') { + for (i = 0; i < boardSize; i++) { + if (board[i][boardColSize[i] - 1] == 'O') { new = node_new(&free_list); new->x = i; - new->y = boardColSize - 1; + new->y = boardColSize[i] - 1; list_add_tail(&new->link, &queue); - bfs(board, boardRowSize, boardColSize, &queue, &free_list); + bfs(board, boardSize, boardColSize[i], &queue, &free_list); } } - for (i = 0; i < boardRowSize; i++) { - for (j = 0; j < boardColSize; j++) { + for (i = 0; i < boardSize; i++) { + for (j = 0; j < boardColSize[i]; j++) { board[i][j] = board[i][j] == 'P' ? 'O' : 'X'; } } @@ -177,33 +177,33 @@ int main(void) { int i, j; int row_size = 5; - int col_size = 5; + int *col_sizes = malloc(row_size * sizeof(int)); char **board = malloc(row_size * sizeof(char *)); - board[0] = malloc(col_size); + board[0] = malloc(row_size); board[0][0] = 'X'; board[0][1] = 'X'; board[0][2] = 'X'; board[0][3] = 'X'; board[0][4] = 'X'; - board[1] = malloc(col_size); + board[1] = malloc(row_size); board[1][0] = 'O'; board[1][1] = 'X'; board[1][2] = 'O'; board[1][3] = 'O'; board[1][4] = 'X'; - board[2] = malloc(col_size); + board[2] = malloc(row_size); board[2][0] = 'O'; board[2][1] = 'O'; board[2][2] = 'X'; board[2][3] = 'O'; board[2][4] = 'X'; - board[3] = malloc(col_size); + board[3] = malloc(row_size); board[3][0] = 'X'; board[3][1] = 'X'; board[3][2] = 'O'; board[3][3] = 'X'; board[3][4] = 'X'; - board[4] = malloc(col_size); + board[4] = malloc(row_size); board[4][0] = 'X'; board[4][1] = 'X'; board[4][2] = 'O'; @@ -211,16 +211,17 @@ int main(void) board[4][4] = 'X'; for (i = 0; i < row_size; i++) { - for (j = 0; j < col_size; j++) { + col_sizes[i] = row_size; + for (j = 0; j < col_sizes[i]; j++) { printf("%c ", board[i][j]); } printf("\n"); } printf("\n"); - solve(board, row_size, col_size); + solve(board, row_size, col_sizes); for (i = 0; i < row_size; i++) { - for (j = 0; j < col_size; j++) { + for (j = 0; j < col_sizes[i]; j++) { printf("%c ", board[i][j]); } printf("\n"); From d4f6d7e664649259b5db14772d9eaf3b9998403b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 28 Oct 2023 09:27:16 +0800 Subject: [PATCH 12/33] Improvement Signed-off-by: begeekmyfriend --- .../rotated_array.c | 2 + .../rotated_array.cc | 5 ++ .../kth_elem.c | 55 ++++++++++--------- 3 files changed, 36 insertions(+), 26 deletions(-) diff --git a/0033_search_in_rotated_sorted_array/rotated_array.c b/0033_search_in_rotated_sorted_array/rotated_array.c index 822c2ee..07d508c 100644 --- a/0033_search_in_rotated_sorted_array/rotated_array.c +++ b/0033_search_in_rotated_sorted_array/rotated_array.c @@ -12,6 +12,8 @@ static int search(int* nums, int numsSize, int target) return mid; } + /* lo might be mid */ + /* We only need to consider non-rotated sorted array search */ if (nums[lo] <= nums[mid]) { if (nums[lo] <= target && target < nums[mid]) { hi = mid - 1; diff --git a/0033_search_in_rotated_sorted_array/rotated_array.cc b/0033_search_in_rotated_sorted_array/rotated_array.cc index 6332d10..67d0ec8 100644 --- a/0033_search_in_rotated_sorted_array/rotated_array.cc +++ b/0033_search_in_rotated_sorted_array/rotated_array.cc @@ -7,11 +7,15 @@ class Solution { int search(vector& nums, int target) { int lo = 0; int hi = nums.size() - 1; + for (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) { return mid; } + + // lo might be mid + // We only need to consider non-rotated sorted array search if (nums[lo] <= nums[mid]) { if (nums[lo] <= target && target < nums[mid]) { hi = mid - 1; @@ -26,6 +30,7 @@ class Solution { } } } + return -1; } }; diff --git a/0215_kth_largest_element_in_an_array/kth_elem.c b/0215_kth_largest_element_in_an_array/kth_elem.c index c4f6294..4551749 100644 --- a/0215_kth_largest_element_in_an_array/kth_elem.c +++ b/0215_kth_largest_element_in_an_array/kth_elem.c @@ -1,44 +1,47 @@ #include #include +static inline void swap(int *a, int *b) +{ + int t = *a; + *a = *b; + *b = t; +} -static int partition(int *nums, int lo, int hi) +static int quick_select(int *nums, int lo, int hi, int k) { if (lo >= hi) { return hi; } - int i = lo; - int j = hi; - int pivot = nums[hi]; + int i = lo - 1; + int j = hi + 1; + int pivot = nums[lo]; while (i < j) { - while (i < j && nums[i] <= pivot) { i++; } - /* Loop invariant: nums[i] > pivot or i == j */ - nums[j] = nums[i]; - while (i < j && nums[j] >= pivot) { j--; } - /* Loop invariant: nums[j] > pivot or i == j */ - nums[i] = nums[j]; + /* For case of large amounts of consecutive duplicate elements, we + * shall make the partition in the middle of the array as far as + * possible. If the partition is located in the head or tail, the + * performance might well be very bad for it. + */ + while (nums[++i] > pivot) {} + while (nums[--j] < pivot) {} + if (i < j) { + swap(&nums[i], &nums[j]); + } + } + + /* invariant: i == j + 1 or i == j */ + if (j >= k - 1) { + return quick_select(nums, lo, j, k); + } else { + return quick_select(nums, j + 1, hi, k); } - /* Loop invariant: i == j */ - nums[i] = pivot; - return i; } int findKthLargest(int* nums, int numsSize, int k) { - int lo = 0, hi = numsSize - 1; - for (; ;) { - int p = partition(nums, lo, hi); - if (p < numsSize - k) { - lo = p + 1; - } else if (p > numsSize - k) { - hi = p - 1; - } else { - lo = p; - break; - } - } - return nums[lo]; + int i = quick_select(nums, 0, numsSize - 1, k); + return nums[i]; } From 502d663742f936fd17f05e0e96a5d4c60b6c0b9c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 29 Oct 2023 18:10:30 +0800 Subject: [PATCH 13/33] Add max heap approach for No.215 Signed-off-by: begeekmyfriend --- .../kth_elem.c | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/0215_kth_largest_element_in_an_array/kth_elem.c b/0215_kth_largest_element_in_an_array/kth_elem.c index 4551749..bf9ea50 100644 --- a/0215_kth_largest_element_in_an_array/kth_elem.c +++ b/0215_kth_largest_element_in_an_array/kth_elem.c @@ -1,6 +1,7 @@ #include #include + static inline void swap(int *a, int *b) { int t = *a; @@ -8,6 +9,35 @@ static inline void swap(int *a, int *b) *b = t; } +static void max_heapify(int *nums, int size, int parent) +{ + int i = parent; /* parent is the root */ + int l = parent * 2 + 1; + int r = parent * 2 + 2; + + if (l < size && nums[l] > nums[i]) { + i = l; + } + + if (r < size && nums[r] > nums[i]) { + i = r; + } + + /* percolate up */ + if (i != parent) { + swap(&nums[i], &nums[parent]); + max_heapify(nums, size, i); + } +} + +static void build_max_heap(int *nums, int size) +{ + int i; + for (i = size / 2; i >= 0; i--) { + max_heapify(nums, size, i); + } +} + static int quick_select(int *nums, int lo, int hi, int k) { if (lo >= hi) { @@ -40,8 +70,22 @@ static int quick_select(int *nums, int lo, int hi, int k) int findKthLargest(int* nums, int numsSize, int k) { +#if 0 int i = quick_select(nums, 0, numsSize - 1, k); return nums[i]; +#else + int i; + + build_max_heap(nums, numsSize); + + /* nums[0] is the largest element and the last is the least */ + for (i = numsSize - 1; i >= numsSize - k + 1; i--) { + swap(&nums[0], &nums[i]); + max_heapify(nums, numsSize, 0); + } + + return nums[0]; +#endif } From 4973627be987da929d9abcba24a374a9aa4a694c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 4 Nov 2023 22:16:10 +0800 Subject: [PATCH 14/33] Improvement Signed-off-by: begeekmyfriend --- 0023_merge_k_sorted_lists/merge_lists.c | 143 ++++++------------ 0152_maximum_product_subarray/subarray.c | 3 +- .../minimum.c | 12 +- .../minimum.c | 21 ++- 4 files changed, 67 insertions(+), 112 deletions(-) diff --git a/0023_merge_k_sorted_lists/merge_lists.c b/0023_merge_k_sorted_lists/merge_lists.c index 3b29dd6..b183e2e 100644 --- a/0023_merge_k_sorted_lists/merge_lists.c +++ b/0023_merge_k_sorted_lists/merge_lists.c @@ -2,141 +2,94 @@ #include #include +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ struct ListNode { int val; struct ListNode *next; }; -struct PriorityQueue { - struct ListNode **nodes; - int size; -}; - static inline void swap(struct ListNode **a, struct ListNode **b) { - struct ListNode *tmp = *a; + struct ListNode *t = *a; *a = *b; - *b = tmp; + *b = t; } -static inline int left(int i) { return i * 2 + 1; } -static inline int right(int i) { return left(i) + 1; } -static inline int parent(int i) { return (i - 1) / 2; } - -static void queue_dump(struct PriorityQueue *queue) +static void min_heapify(struct ListNode **nodes, int size, int parent) { - int i; - for (i = 0; i < queue->size; i++) { - printf("%d ", queue->nodes[i]->val); - } - printf("\n"); -} + int i = parent; /* parent is the root */ + int l = parent * 2 + 1; + int r = parent * 2 + 2; -static void percolate_up(struct ListNode **nodes, int i) -{ - while (i >= 0 && nodes[parent(i)]->val > nodes[i]->val) { - swap(nodes + parent(i), nodes + i); - i = parent(i); + if (l < size && nodes[l]->val < nodes[i]->val) { + i = l; } -} -static void percolate_down1(struct ListNode **nodes, int size, int child) -{ - int i, min; - for (i = child; i >= 0; i = parent(i)) { - if (right(i) < size) { - min = nodes[left(i)]->val < nodes[right(i)]->val ? left(i) : right(i); - } else { - min = left(i); - } - if (nodes[min]->val < nodes[i]->val) { - swap(nodes + min, nodes + i); - } else { - break; - } + if (r < size && nodes[r]->val < nodes[i]->val) { + i = r; } -} -static void percolate_down2(struct ListNode **nodes, int size) -{ - int i, min; - for (i = 0; left(i) < size; i = min) { - if (right(i) < size) { - min = nodes[left(i)]->val < nodes[right(i)]->val ? left(i) : right(i); - } else { - min = left(i); - } - if (nodes[min]->val < nodes[i]->val) { - swap(nodes + min, nodes + i); - } else { - break; - } + /* percolate up */ + if (i != parent) { + swap(&nodes[i], &nodes[parent]); + min_heapify(nodes, size, i); } } -static void heap_build(struct PriorityQueue *queue) +static void build_min_heap(struct ListNode **nodes, int size) { int i; - for (i = queue->size / 2 - 1; i > 0; i--) { - percolate_down1(queue->nodes, queue->size, i); - } -} -static void put(struct PriorityQueue *queue, struct ListNode *node) -{ - queue->nodes[queue->size++] = node; - percolate_up(queue->nodes, queue->size - 1); + if (size <= 0) return; + + for (i = size / 2; i >= 0; i--) { + min_heapify(nodes, size, i); + } } -static struct ListNode *get(struct PriorityQueue *queue) +static struct ListNode *get(struct ListNode **nodes, int size) { - int i; - struct ListNode *p = queue->nodes[0]; - swap(queue->nodes, queue->nodes + queue->size - 1); - queue->size--; - percolate_down2(queue->nodes, queue->size); + struct ListNode *p = nodes[0]; + nodes[0] = nodes[--size]; + min_heapify(nodes, size, 0); return p; } -static struct PriorityQueue *init(int size) +static void put(struct ListNode **nodes, int size, struct ListNode *n) { - struct PriorityQueue *queue = malloc(sizeof(*queue)); - queue->nodes = malloc(size * sizeof(*queue->nodes)); - queue->size = 0; - return queue; + nodes[size++] = n; + build_min_heap(nodes, size); } -static struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) +struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) { - if (listsSize == 0) { - return NULL; - } - - if (listsSize == 1) { - return lists[0]; - } - - int i; + int i, size = 0; struct ListNode dummy; - struct ListNode *prev; - struct PriorityQueue *queue = init(listsSize); - - dummy.next = NULL; - prev = &dummy; + struct ListNode *p = &dummy; + struct ListNode **nodes = malloc(listsSize * sizeof(struct ListNode)); for (i = 0; i < listsSize; i++) { if (lists[i] != NULL) { - put(queue, lists[i]); + nodes[size++] = lists[i]; } } - heap_build(queue); - while (queue->size > 0) { - struct ListNode *n = get(queue); - prev->next = n; - prev = n; + build_min_heap(nodes, size); + + while (size > 0) { + struct ListNode *n = get(nodes, size); + size--; + p->next = n; + p = p->next; if (n->next != NULL) { - put(queue, n->next); + put(nodes, size, n->next); + size++; } n->next = NULL; } diff --git a/0152_maximum_product_subarray/subarray.c b/0152_maximum_product_subarray/subarray.c index cabe83d..3af1389 100644 --- a/0152_maximum_product_subarray/subarray.c +++ b/0152_maximum_product_subarray/subarray.c @@ -2,6 +2,7 @@ #include #include + static inline int min(int a, int b) { return a < b ? a : b; @@ -31,8 +32,6 @@ static int maxProduct(int* nums, int numsSize) int main(int argc, char **argv) { - - int i, count = argc - 1; int *nums = malloc(count * sizeof(int)); for (i = 0; i < count; i++) { diff --git a/0153_find_minimum_in_rotated_sorted_array/minimum.c b/0153_find_minimum_in_rotated_sorted_array/minimum.c index 1073f1f..677d426 100644 --- a/0153_find_minimum_in_rotated_sorted_array/minimum.c +++ b/0153_find_minimum_in_rotated_sorted_array/minimum.c @@ -6,17 +6,15 @@ static int findMin(int* nums, int numsSize) { int lo = 0; int hi = numsSize - 1; - int min = INT_MAX; - while (lo <= hi) { + while (lo < hi) { int mid = lo + (hi - lo) / 2; - min = min < nums[mid] ? min : nums[mid]; - if (nums[mid] > nums[hi]) { - lo = mid + 1; + if (nums[mid] < nums[hi]) { + hi = mid; } else { - hi = mid - 1; + lo = mid + 1; } } - return min; + return nums[lo]; } int main(int argc, char **argv) diff --git a/0154_find_minimum_in_rotated_sorted_array_ii/minimum.c b/0154_find_minimum_in_rotated_sorted_array_ii/minimum.c index a1ec893..6e11f26 100644 --- a/0154_find_minimum_in_rotated_sorted_array_ii/minimum.c +++ b/0154_find_minimum_in_rotated_sorted_array_ii/minimum.c @@ -3,16 +3,21 @@ static int findMin(int* nums, int numsSize) { - if (numsSize == 1) { - return nums[0]; - } - int i, j; - for (i = 1; i < numsSize; i++) { - if (nums[i] < nums[i - 1]) { - return nums[i]; + int lo = 0; + int hi = numsSize - 1; + + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] < nums[hi]) { + hi = mid; + } else if (nums[mid] > nums[hi]) { + lo = mid + 1; + } else { + hi--; } } - return nums[0]; + + return nums[lo]; } int main(int argc, char **argv) From eef0996fdec7aad5c9ade4bf9dcb2ba5298bef37 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 4 Nov 2023 22:27:36 +0800 Subject: [PATCH 15/33] Improvement Signed-off-by: begeekmyfriend --- 0021_merge_two_sorted_lists/merge_lists.c | 16 ++++++---------- 0021_merge_two_sorted_lists/merge_lists.cc | 17 ++++++----------- 2 files changed, 12 insertions(+), 21 deletions(-) diff --git a/0021_merge_two_sorted_lists/merge_lists.c b/0021_merge_two_sorted_lists/merge_lists.c index 34ecdb0..6c89645 100644 --- a/0021_merge_two_sorted_lists/merge_lists.c +++ b/0021_merge_two_sorted_lists/merge_lists.c @@ -9,25 +9,21 @@ struct ListNode { static struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { struct ListNode dummy; - struct ListNode *prev = &dummy; + struct ListNode *tail = &dummy; dummy.next = l1; while (l1 != NULL && l2 != NULL) { if (l1->val <= l2->val) { - prev = l1; + tail->next = l1; l1 = l1->next; } else { - struct ListNode *tmp = l2->next; - l2->next = l1; - prev->next = l2; - prev = l2; - l2 = tmp; + tail->next = l2; + l2 = l2->next; } + tail = tail->next; } - if (l2 != NULL) { - prev->next = l2; - } + tail->next = l1 != NULL ? l1 : l2; return dummy.next; } diff --git a/0021_merge_two_sorted_lists/merge_lists.cc b/0021_merge_two_sorted_lists/merge_lists.cc index a5d7a63..58a47f7 100644 --- a/0021_merge_two_sorted_lists/merge_lists.cc +++ b/0021_merge_two_sorted_lists/merge_lists.cc @@ -15,26 +15,21 @@ using namespace std; class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { - struct ListNode *prev, dummy; - - prev = &dummy; + struct ListNode *tail, dummy; + tail = &dummy; dummy.next = l1; + while (l1 != nullptr && l2 != nullptr) { if (l1->val <= l2->val) { - prev = l1; + tail->next = l1; l1 = l1->next; } else { - struct ListNode *tmp = l2; + tail->next = l2; l2 = l2->next; - tmp->next = l1; - prev->next = tmp; - prev = tmp; } } - if (l2 != nullptr) { - prev->next = l2; - } + tail->next = l1 != nullptr ? l1 : l2; return dummy.next; } From 14678606b31629f5c2857e40006b720565dc77fc Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 5 Nov 2023 11:50:57 +0800 Subject: [PATCH 16/33] Improvement Signed-off-by: begeekmyfriend --- 0021_merge_two_sorted_lists/merge_lists.c | 1 - 0023_merge_k_sorted_lists/merge_lists.c | 38 +++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/0021_merge_two_sorted_lists/merge_lists.c b/0021_merge_two_sorted_lists/merge_lists.c index 6c89645..021a584 100644 --- a/0021_merge_two_sorted_lists/merge_lists.c +++ b/0021_merge_two_sorted_lists/merge_lists.c @@ -10,7 +10,6 @@ static struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { struct ListNode dummy; struct ListNode *tail = &dummy; - dummy.next = l1; while (l1 != NULL && l2 != NULL) { if (l1->val <= l2->val) { diff --git a/0023_merge_k_sorted_lists/merge_lists.c b/0023_merge_k_sorted_lists/merge_lists.c index b183e2e..5695b91 100644 --- a/0023_merge_k_sorted_lists/merge_lists.c +++ b/0023_merge_k_sorted_lists/merge_lists.c @@ -67,8 +67,45 @@ static void put(struct ListNode **nodes, int size, struct ListNode *n) build_min_heap(nodes, size); } +static struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) +{ + struct ListNode dummy; + struct ListNode *tail = &dummy; + + while (l1 != NULL && l2 != NULL) { + if (l1->val <= l2->val) { + tail->next = l1; + l1 = l1->next; + } else { + tail->next = l2; + l2 = l2->next; + } + tail = tail->next; + } + + tail->next = l1 != NULL ? l1 : l2; + + return dummy.next; +} + +static struct ListNode* dfs(struct ListNode** lists, int lo, int hi) +{ + if (lo > hi) // listsSize might be zero + return NULL; + + if (lo == hi) + return lists[lo]; + + int mid = lo + (hi - lo) / 2; + return mergeTwoLists(dfs(lists, lo, mid), dfs(lists, mid + 1, hi)); +} + + struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) { +#if 1 + return dfs(lists, 0, listsSize - 1); +#else int i, size = 0; struct ListNode dummy; struct ListNode *p = &dummy; @@ -95,6 +132,7 @@ struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) } return dummy.next; +#endif } int main(void) From 72226ca39e004e680c30a842a6defb527efc035b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 6 Nov 2023 16:18:23 +0800 Subject: [PATCH 17/33] Improvement Signed-off-by: begeekmyfriend --- .../longest_substring_without_repeat.c | 28 ++++++------------- .../longest_substring_without_repeat.cc | 24 ++++++---------- .../window_substring.c | 14 ++++++++-- 3 files changed, 28 insertions(+), 38 deletions(-) diff --git a/0003_longest_substring_without_repeat/longest_substring_without_repeat.c b/0003_longest_substring_without_repeat/longest_substring_without_repeat.c index 7af62c6..51c7c27 100644 --- a/0003_longest_substring_without_repeat/longest_substring_without_repeat.c +++ b/0003_longest_substring_without_repeat/longest_substring_without_repeat.c @@ -5,31 +5,19 @@ int lengthOfLongestSubstring(char *s) { - int offset[128]; - int max_len = 0; + int count[256] = {0}; int len = 0; - int index = 0; + int i, j; - memset(offset, 0xff, sizeof(offset)); - while (*s != '\0') { - if (offset[*s] == -1) { - len++; - } else { - if (index - offset[*s] > len) { - /* not included in sliding window, go on increasing */ - len++; - } else { - /* repetition in sliding window, count from scratch */ - len = index - offset[*s]; - } + for (i = 0, j = 0; s[i] != '\0'; i++) { + count[s[i]]++; + while (count[s[i]] > 1) { + len = i - j > len ? i - j : len; + count[s[j++]] -= 1; } - if (len > max_len) { - max_len = len; - } - offset[*s++] = index++; } - return max_len; + return i - j > len ? i - j : len; } int main(int argc, char **argv) diff --git a/0003_longest_substring_without_repeat/longest_substring_without_repeat.cc b/0003_longest_substring_without_repeat/longest_substring_without_repeat.cc index 08a12e2..af643ca 100644 --- a/0003_longest_substring_without_repeat/longest_substring_without_repeat.cc +++ b/0003_longest_substring_without_repeat/longest_substring_without_repeat.cc @@ -5,26 +5,18 @@ using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { - vector indexes(128, -1); - int max_len = 0; + vector count(256); int len = 0; + int i, j; - for (int i = 0; i < s.length(); i++) { - if (indexes[s[i]] == -1) { - len++; - } else { - if (i - indexes[s[i]] > len) { - /* not included in sliding window, go on increasing */ - len++; - } else { - /* repetition in sliding window, count from scratch */ - len = i - indexes[s[i]]; - } + for (i = 0, j = 0; i < s.length(); i++) { + count[s[i]]++; + while (count[s[i]] > 1) { + len = i - j > len ? i - j : len; + count[s[j++]] -= 1; } - max_len = max(max_len, len); - indexes[s[i]] = i; } - return max_len; + return i - j > len ? i - j : len; } }; diff --git a/0076_minimum_window_substring/window_substring.c b/0076_minimum_window_substring/window_substring.c index a9e87ab..41f5d0b 100644 --- a/0076_minimum_window_substring/window_substring.c +++ b/0076_minimum_window_substring/window_substring.c @@ -2,6 +2,17 @@ #include #include + +/* sliding window pattern + * while (r < size) { + * // check target condition + * while (target_condition) { + * // calculate minimum length + * // iterate left indicator + * } + * // iterate right indicator + * } + */ static char *minWindow(char *s, char *t) { int i, j, count[256] = { 0 }; @@ -42,8 +53,7 @@ static char *minWindow(char *s, char *t) memcpy(result, s + start, min_len); result[min_len] = '\0'; } else { - result = malloc(1); - result[0] = '\0'; + result = ""; } return result; From c40b4b8395181f9390ebd50dadc9fc9bc30f7b9c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 18 Nov 2023 11:51:05 +0800 Subject: [PATCH 18/33] Improvement Signed-off-by: begeekmyfriend --- 0058_length_of_last_word/word_length.c | 20 ++++++++++--------- 0070_climbing_stairs/climb_stairs.c | 19 ++++++++---------- .../rm_dup.c | 20 +++++++++++-------- 3 files changed, 31 insertions(+), 28 deletions(-) diff --git a/0058_length_of_last_word/word_length.c b/0058_length_of_last_word/word_length.c index b18cec9..bad2085 100644 --- a/0058_length_of_last_word/word_length.c +++ b/0058_length_of_last_word/word_length.c @@ -1,18 +1,20 @@ #include #include +#include int lengthOfLastWord(char *s) { - int len = 0; - while (*s != '\0') { - if (s[-1] == ' ' && s[0] != ' ') { - len = 1; - } else if (*s != ' ') { - len++; - } - s++; + int word_len = 0; + int len = strlen(s); + + while (len > 0 && s[--len] == ' ') {} + + while (len >= 0 && s[len] != ' ') { + word_len++; + len--; } - return len; + + return word_len; } int main(int argc, char **argv) diff --git a/0070_climbing_stairs/climb_stairs.c b/0070_climbing_stairs/climb_stairs.c index 3ecc50c..e1e05ea 100644 --- a/0070_climbing_stairs/climb_stairs.c +++ b/0070_climbing_stairs/climb_stairs.c @@ -4,28 +4,25 @@ static int dfs(int n, int *count) { - if (n == 0) { - return 0; + if (n == 1) { + return 1; + } else if (n == 2) { + return 2; } else if (count[n] > 0) { return count[n]; } else { - if (n >= 1) { - count[n] += dfs(n - 1, count); - } - if (n >= 2) { - count[n] += dfs(n - 2, count); - } + count[n] += dfs(n - 1, count); + count[n] += dfs(n - 2, count); return count[n]; } } static int climbStairs(int n) { -#if 0 +#if 1 + if (n < 1) return 0; int *count = malloc((n + 1) * sizeof(int)); memset(count, 0, (n + 1) * sizeof(int)); - count[1] = 1; - count[2] = 2; return dfs(n, count); #else int i, a = 1, b = 2, c; diff --git a/0083_remove_duplicates_from_sorted_list/rm_dup.c b/0083_remove_duplicates_from_sorted_list/rm_dup.c index f5b7c7f..e8d7d4a 100644 --- a/0083_remove_duplicates_from_sorted_list/rm_dup.c +++ b/0083_remove_duplicates_from_sorted_list/rm_dup.c @@ -1,3 +1,4 @@ +#include #include #include @@ -9,16 +10,19 @@ struct ListNode { struct ListNode* deleteDuplicates(struct ListNode* head) { - struct ListNode *p, *q; - p = q = head; - while (p != NULL) { - while (q != NULL && q->val == p->val) { - q = q->next; + struct ListNode dummy; + struct ListNode *prev = &dummy; + dummy.val = INT_MIN; + + while (head != NULL) { + if (prev->val != head->val) { + prev->next = head; + prev = head; } - p->next = q; - p = q; + head = head->next; } - return head; + prev->next = head; + return dummy.next; } int main(int argc, char **argv) From eaa232d74578c2ce3c09012bdcedc1cde331e205 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 19 Dec 2023 16:02:37 +0800 Subject: [PATCH 19/33] Improvement Signed-off-by: begeekmyfriend --- 0042_trapping_rain_water/trap_water.c | 22 ++++++++---------- 0042_trapping_rain_water/trap_water.cc | 31 +++++++++++--------------- 0045_jump_game_ii/jump_game.c | 23 ++++++++++--------- 0045_jump_game_ii/jump_game.cc | 21 ++++++++--------- 0198_house_robber/robber.c | 6 +++-- 0198_house_robber/robber.cc | 6 +++-- 6 files changed, 54 insertions(+), 55 deletions(-) diff --git a/0042_trapping_rain_water/trap_water.c b/0042_trapping_rain_water/trap_water.c index a304e24..d0abc5b 100644 --- a/0042_trapping_rain_water/trap_water.c +++ b/0042_trapping_rain_water/trap_water.c @@ -35,22 +35,18 @@ static int trap(int* height, int heightSize) int res = 0; int l = 0, lmax = 0; int r = heightSize - 1, rmax = 0; + while (l < r) { - if (height[l] < height[r]) { - /* Only lmax is needed for lmax < rmax here */ - if (height[l] > lmax) { - lmax = height[l]; - } else { - res += lmax - height[l]; - } + /* lmax is the highest in height[0...l] and + * rmax is the highest in height[r...size - 1] + */ + lmax = height[l] > lmax ? height[l] : lmax; + rmax = height[r] > rmax ? height[r] : rmax; + if (lmax < rmax) { + res += lmax - height[l]; l++; } else { - /* Only rmax is needed for rmax < lmax here */ - if (height[r] > rmax) { - rmax = height[r]; - } else { - res += rmax - height[r]; - } + res += rmax - height[r]; r--; } } diff --git a/0042_trapping_rain_water/trap_water.cc b/0042_trapping_rain_water/trap_water.cc index dd91e7e..5649a61 100644 --- a/0042_trapping_rain_water/trap_water.cc +++ b/0042_trapping_rain_water/trap_water.cc @@ -9,25 +9,20 @@ class Solution { * water level of the position would be determined by the opposite side. */ int res = 0; - int left = 0, left_max = 0; - int right = height.size() - 1, right_max = 0; - while (left < right) { - if (height[left] < height[right]) { - /* Only lmax is needed for lmax < rmax here */ - if (height[left] > left_max) { - left_max = height[left]; - } else { - res += left_max - height[left]; - } - left++; + int l = 0, l_max = 0; + int r = height.size() - 1, r_max = 0; + + while (l < r) { + // lmax is the highest in height[0...l] and + // rmax is the highest in height[r...size - 1] + l_max = max(height[l], l_max); + r_max = max(height[r], r_max); + if (l_max < r_max) { + res += l_max - height[l]; + l++; } else { - /* Only rmax is needed for rmax < lmax here */ - if (height[right] > right_max) { - right_max = height[right]; - } else { - res += right_max - height[right]; - } - right--; + res += r_max - height[r]; + r--; } } diff --git a/0045_jump_game_ii/jump_game.c b/0045_jump_game_ii/jump_game.c index d315766..9de0eda 100644 --- a/0045_jump_game_ii/jump_game.c +++ b/0045_jump_game_ii/jump_game.c @@ -1,6 +1,7 @@ #include #include + static inline int max(int a, int b) { return a > b ? a : b; @@ -8,19 +9,21 @@ static inline int max(int a, int b) static int jump(int* nums, int numsSize) { - int i, lo = 0, hi = 0; + int i, right = 0; int steps = 0; - while (hi < numsSize - 1) { - int right = 0; - for (i = lo; i <= hi; i++) { - /* Assume right > hi for the purpose of the problem */ - right = max(i + nums[i], right); + int fartest = 0; + /* 1. Exhaust all the right boundries in the location range of [i...right] + * 2. When the search ends up with i==right, update the right boundry as + * the fartest position. + * 3. When the search ends up with i==right, it records as one jump step */ + for (i = 0; i < numsSize; i++) { + fartest = max(i + nums[i], fartest); + if (i == right) { + right = fartest; + steps++; } - /* [lo, hi] is the next location range */ - lo = hi + 1; - hi = right; - steps++; } + return steps; } diff --git a/0045_jump_game_ii/jump_game.cc b/0045_jump_game_ii/jump_game.cc index 77e6f2f..e561405 100644 --- a/0045_jump_game_ii/jump_game.cc +++ b/0045_jump_game_ii/jump_game.cc @@ -6,17 +6,18 @@ class Solution { public: int jump(vector& nums) { int steps = 0; - int lo = 0, hi = 0; - while (hi < nums.size() - 1) { - int right = 0; - for (int i = lo; i <= hi; i++) { - // right > hi for nums[i] > 0 - right = max(i + nums[i], right); + int right = 0; + int farthest = 0; + // 1. Exhaust all the right boundries in the location range of [i...right] + // 2. When the search ends up with i==right, update the right boundry as + // the fartest position. + // 3. When the search ends up with i==right, it records as one jump step */ + for (int i = 0; i < nums.size() - 1; i++) { + fartest = max(i + nums[i], fartest); + for (i == right) { + right = fartest; + steps++; } - // [lo, hi] is the next location range - lo = hi + 1; - hi = right; - steps++; } return steps; diff --git a/0198_house_robber/robber.c b/0198_house_robber/robber.c index d76228b..82fa8ad 100644 --- a/0198_house_robber/robber.c +++ b/0198_house_robber/robber.c @@ -14,10 +14,12 @@ static int rob(int* nums, int numsSize) int untaken = 0; /* Record max profits of nums[0...i] respectively */ for (i = 0; i < numsSize; i++) { - int tmp_taken = taken; + int last_taken = taken; /* Taken or untaken nums[i] */ + /* last taken + nums[i] */ taken = untaken + nums[i]; - untaken = max(tmp_taken, untaken); + /* max(last untaken, last taken) */ + untaken = max(last_taken, untaken); } return max(taken, untaken); diff --git a/0198_house_robber/robber.cc b/0198_house_robber/robber.cc index 3d2ffb5..010c571 100644 --- a/0198_house_robber/robber.cc +++ b/0198_house_robber/robber.cc @@ -8,9 +8,11 @@ class Solution { int taken = 0; int untaken = 0; for (int i = 0; i < nums.size(); i++) { - int tmp_taken = taken; + int last_taken = taken; + /* last untaken + nums[i]*/ taken = untaken + nums[i]; - untaken = max(untaken, tmp_taken); + /* max(last untaken, last taken) */ + untaken = max(untaken, last_taken); } return max(taken, untaken); } From 6de6ce558fa0f5a5f7320be805de16da1b5c2077 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 28 Dec 2023 18:35:45 +0800 Subject: [PATCH 20/33] Improvement Signed-off-by: begeekmyfriend --- .../bst_convert.c | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/0109_convert_sorted_list_to_binary_search_tree/bst_convert.c b/0109_convert_sorted_list_to_binary_search_tree/bst_convert.c index 965fdc1..88434f0 100644 --- a/0109_convert_sorted_list_to_binary_search_tree/bst_convert.c +++ b/0109_convert_sorted_list_to_binary_search_tree/bst_convert.c @@ -13,26 +13,29 @@ struct TreeNode { struct TreeNode *right; }; -static struct TreeNode *dfs(int *nums, int lo, int hi) +static struct TreeNode *dfs(struct ListNode **head, int lo, int hi) { + if (lo > hi) { + return NULL; + } + int mid = lo + (hi - lo) / 2; struct TreeNode *node = malloc(sizeof(*node)); - node->val = nums[mid]; - node->left = mid > lo ? dfs(nums, lo, mid - 1) : NULL; - node->right = mid < hi ? dfs(nums, mid + 1, hi) : NULL; + node->left = dfs(head, lo, mid - 1); + node->val = (*head)->val; + (*head) = (*head)->next; + node->right = dfs(head, mid + 1, hi); return node; } -static struct TreeNode *sortedListToBST(struct ListNode *head) +static struct TreeNode* sortedListToBST(struct ListNode* head) { - int i, nums[10000]; - for (i = 0; head != NULL; head = head->next, i++) { - nums[i] = head->val; - } - if (i == 0) { - return NULL; + struct ListNode *p; + int len = 0; + for (p = head; p != NULL; p = p->next) { + len++; } - return traverse(nums, 0, i - 1); + return dfs(&head, 0, len - 1); } int main(int argc, char **argv) From 587cc5c15392537af450803a34832b097032cadc Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 8 Jan 2024 17:17:53 +0800 Subject: [PATCH 21/33] Improvement Signed-off-by: begeekmyfriend --- 0072_edit_distance/edit_distance.c | 25 ++++++++++--------- 0072_edit_distance/edit_distance.cc | 1 + 0300_longest_increasing_subsequence/lis.c | 30 ++++++++++++++++++++++- 0322_coin_change/coin_change.c | 9 ++++--- 4 files changed, 49 insertions(+), 16 deletions(-) diff --git a/0072_edit_distance/edit_distance.c b/0072_edit_distance/edit_distance.c index b035609..92f96a8 100644 --- a/0072_edit_distance/edit_distance.c +++ b/0072_edit_distance/edit_distance.c @@ -31,23 +31,25 @@ static inline int min(int a, int b) static int minDistance(char* word1, char* word2) { int i, j; - int len1 = strlen(word1); - int len2 = strlen(word2); - int *table = malloc((len1 + 1) * (len2 + 1) * sizeof(int)); - int **dp = malloc((len1 + 1) * sizeof(int *)); - for (i = 0; i < len1 + 1; i++) { - dp[i] = table + i * (len2 + 1); + int l1 = strlen(word1); + int l2 = strlen(word2); + int *table = malloc((l1 + 1) * (l2 + 1) * sizeof(int)); + int **dp = malloc((l1 + 1) * sizeof(int *)); + + for (i = 0; i < l1 + 1; i++) { + dp[i] = table + i * (l2 + 1); } - for (i = 0; i < len2 + 1; i++) { + dp[0][0] = 0; + for (i = 1; i <= l2; i++) { dp[0][i] = i; } - for (i = 0; i < len1 + 1; i++) { + for (i = 1; i <= l1; i++) { dp[i][0] = i; } - for (i = 1; i < len1 + 1; i++) { - for (j = 1; j < len2 + 1; j++) { + for (i = 1; i <= l1; i++) { + for (j = 1; j <= l2; j++) { if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; } else { @@ -55,7 +57,8 @@ static int minDistance(char* word1, char* word2) } } } - return dp[len1][len2]; + + return dp[l1][l2]; } int main(int argc, char **argv) diff --git a/0072_edit_distance/edit_distance.cc b/0072_edit_distance/edit_distance.cc index deec40e..be8543a 100644 --- a/0072_edit_distance/edit_distance.cc +++ b/0072_edit_distance/edit_distance.cc @@ -26,6 +26,7 @@ class Solution { left_up = up; } } + return dp[l2]; } }; diff --git a/0300_longest_increasing_subsequence/lis.c b/0300_longest_increasing_subsequence/lis.c index b9a05cd..2713e88 100644 --- a/0300_longest_increasing_subsequence/lis.c +++ b/0300_longest_increasing_subsequence/lis.c @@ -2,6 +2,11 @@ #include +static int max(int a, int b) +{ + return a > b ? a : b; +} + static int binary_search(int *nums, int lo, int hi, int target) { while (lo + 1 < hi) { @@ -15,7 +20,9 @@ static int binary_search(int *nums, int lo, int hi, int target) return hi; } -int lengthOfLIS(int* nums, int numsSize){ +int lengthOfLIS(int* nums, int numsSize) +{ +#if 0 int i, piles = 0; int *tops = malloc(numsSize * sizeof(int)); for (i = 0; i < numsSize; i++) { @@ -26,6 +33,27 @@ int lengthOfLIS(int* nums, int numsSize){ tops[pos] = nums[i]; } return piles; +#else + int i, j, res = 0; + int *dp = malloc(numsSize * sizeof(int)); + + /* dp array records subsequence length of nums[0...i], so we need to + * initialize each dp[i] with one element length in the beginning. */ + for (i = 0; i < numsSize; i++) { + dp[i] = 1; + for (j = 0; j < i; j++) { + if (nums[j] > nums[i]) { + dp[i] = max(dp[i], dp[j] + 1); + } + } + } + + for (i = 0; i < numsSize; i++) { + res = max(res, dp[i]); + } + + return res; +#endif } int main(int argc, char **argv) diff --git a/0322_coin_change/coin_change.c b/0322_coin_change/coin_change.c index 10c8244..9eb270c 100644 --- a/0322_coin_change/coin_change.c +++ b/0322_coin_change/coin_change.c @@ -6,13 +6,14 @@ int coinChange(int* coins, int coinsSize, int amount) { int i, j; int *dp = malloc((amount + 1) * sizeof(int)); - for (i = 1; i <= amount; i++) { - /* INT_MAX */ - dp[i] = amount + 1; - } + /* The dp array records minimum coin number corresponding to the + * amount of coins. So we need to initialize each dp[i] with + * amount + 1 as an invalid value */ dp[0] = 0; for (i = 1; i <= amount; i++) { + /* initialized with INT_MAX */ + dp[i] = amount + 1; for (j = 0; j < coinsSize; j++) { if (i - coins[j] >= 0) { int tmp = 1 + dp[i - coins[j]]; From 2095ed97d0bfa468e251e5ec0387f162fb91f554 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 10 Jan 2024 09:13:25 +0800 Subject: [PATCH 22/33] Improvement Signed-off-by: begeekmyfriend --- .../window_substring.c | 30 +++++++++---------- .../anagrams_in_string.c | 11 ++++--- 0516_longest_palindromic_subsequence/lps.c | 3 ++ .../permutation_in_string.c | 12 ++++---- 4 files changed, 32 insertions(+), 24 deletions(-) diff --git a/0076_minimum_window_substring/window_substring.c b/0076_minimum_window_substring/window_substring.c index 41f5d0b..792e898 100644 --- a/0076_minimum_window_substring/window_substring.c +++ b/0076_minimum_window_substring/window_substring.c @@ -18,31 +18,31 @@ static char *minWindow(char *s, char *t) int i, j, count[256] = { 0 }; int slen = strlen(s); int tlen = strlen(t); + /* edges of sliding window */ + int l = 0, r = 0; + int min_len = slen + 1; + int start = 0; + int chars_to_meet = 0; + for (i = 0; i < tlen; i++) { count[t[i]]++; } - /* edges of sliding window */ - int lo = 0, hi = 0; - int min_len = slen + 1; - int start = 0; - int chars_to_meet = tlen; - while (hi < slen) { - if (--count[s[hi++]] >= 0) { + while (r < slen) { + if (--count[s[r++]] >= 0) { /* pattern found */ - chars_to_meet--; + chars_to_meet++; } - while (chars_to_meet == 0) { - if (hi - lo < min_len) { - min_len = hi - lo; - start = lo; + while (chars_to_meet == tlen) { + if (r - l < min_len) { + min_len = r - l; + start = l; } /* Chars with negative count are not included in the pattern string */ - if (++count[s[lo++]] > 0) { - /* chars_to_meet == 1 */ - chars_to_meet++; + if (++count[s[l++]] > 0) { + chars_to_meet--; } } } diff --git a/0438_find_all_anagrams_in_a_string/anagrams_in_string.c b/0438_find_all_anagrams_in_a_string/anagrams_in_string.c index 9a3ec67..f780591 100644 --- a/0438_find_all_anagrams_in_a_string/anagrams_in_string.c +++ b/0438_find_all_anagrams_in_a_string/anagrams_in_string.c @@ -5,23 +5,26 @@ /** * Note: The returned array must be malloced, assume caller calls free(). */ -int* findAnagrams(char * s, char * p, int* returnSize){ +int* findAnagrams(char * s, char * p, int* returnSize) +{ *returnSize = 0; int *res = malloc(11000 * sizeof(int)); int i, pat_len = 0; int count[128] = { 0 }; + int l = 0, r = 0, len = 0; + for (i = 0; p[i] != '\0'; i++) { count[p[i]]++; } pat_len = i; - int l = 0, r = 0, len = 0; while (s[r] != '\0') { if (--count[s[r++]] >= 0) { len++; } - if (r - l >= pat_len) { - if (len == pat_len) { + + while (len >= pat_len) { + if (r - l == pat_len) { res[(*returnSize)++] = l; } if (++count[s[l++]] > 0) { diff --git a/0516_longest_palindromic_subsequence/lps.c b/0516_longest_palindromic_subsequence/lps.c index b8518b9..9972a01 100644 --- a/0516_longest_palindromic_subsequence/lps.c +++ b/0516_longest_palindromic_subsequence/lps.c @@ -13,6 +13,9 @@ int longestPalindromeSubseq(char * s) int i, j, k; int len = strlen(s); int **dp = malloc(len * sizeof(int *)); + + /* The dp array indicates the length of palindrome subsequence of + * nums[i...j] */ for (i = 0; i < len; i++) { dp[i] = malloc(len * sizeof(int)); memset(dp[i], 0, len * sizeof(int)); diff --git a/0567_permutation_in_string/permutation_in_string.c b/0567_permutation_in_string/permutation_in_string.c index a20fa55..bdb4ea8 100644 --- a/0567_permutation_in_string/permutation_in_string.c +++ b/0567_permutation_in_string/permutation_in_string.c @@ -6,19 +6,21 @@ bool checkInclusion(char * s1, char * s2) { - int i, count[128] = { -1 }, pat_len = 0; + int i, count[128] = { 0 }, pat_len; + int l = 0, r = 0, len = 0; + for (i = 0; s1[i] != '\0'; i++) { count[s1[i]]++; - pat_len++; } + pat_len = i; - int l = 0, r = 0, len = 0; while (s2[r] != '\0') { if (--count[s2[r++]] >= 0) { len++; } - while (r - l >= pat_len) { - if (len == pat_len) { + + while (len >= pat_len) { + if (r - l == pat_len) { return true; } if (++count[s2[l++]] > 0) { From 4dbb91b0a7e2e5082692d03d9dd7fd0588db047a Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 20 Feb 2024 22:44:01 +0800 Subject: [PATCH 23/33] Add 0912 Signed-off-by: begeekmyfriend --- 0912_sort_an_array/Makefile | 2 ++ 0912_sort_an_array/sort.c | 67 +++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 0912_sort_an_array/Makefile create mode 100644 0912_sort_an_array/sort.c diff --git a/0912_sort_an_array/Makefile b/0912_sort_an_array/Makefile new file mode 100644 index 0000000..b959cec --- /dev/null +++ b/0912_sort_an_array/Makefile @@ -0,0 +1,2 @@ +all: + gcc -o test sort.c diff --git a/0912_sort_an_array/sort.c b/0912_sort_an_array/sort.c new file mode 100644 index 0000000..7f11deb --- /dev/null +++ b/0912_sort_an_array/sort.c @@ -0,0 +1,67 @@ +#include +#include + + +static void show(int *nums, int lo, int hi) +{ + int i; + for (i = lo; i <= hi; i++) { + printf("%d ", nums[i]); + } + printf("\n"); +} + +static inline void swap(int *a, int *b) +{ + int t = *a; + *a = *b; + *b = t; +} + +static void quick_sort(int *nums, int lo, int hi) +{ + int i, j, mid, pivot; + + if (lo >= hi) { + return; + } + + /* shuffle the pivot */ + mid = lo + (hi - lo) / 2; + swap(&nums[mid], &nums[hi]); + + i = lo - 1; + j = hi; + pivot = nums[hi]; + while (i < j) { + /* For case of large amounts of consecutive duplicate elements, we + * shall make the partition in the middle of the array as far as + * possible. If the partition is located in the head or tail, the + * performance might well be very bad for it. + */ + while (i < hi && nums[++i] < pivot) {} + while (j > lo && nums[--j] > pivot) {} + if (i < j) { + swap(&nums[i], &nums[j]); + } + } + + /* Loop invariant: i == j + 1 or i == j */ + swap(&nums[i], &nums[hi]); + quick_sort(nums, lo, i - 1); + quick_sort(nums, i + 1, hi); +} + +int main(int argc, char **argv) +{ + int i, count = argc - 1; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 1]); + } + + quick_sort(nums, 0, count - 1); + show(nums, 0, count - 1); + + return 0; +} From 5af6c04a1b64b00ea5c54ac3d43d2d192d8f1ddc Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 21 Feb 2024 11:58:52 +0800 Subject: [PATCH 24/33] Improvement Signed-off-by: begeekmyfriend --- 0912_sort_an_array/sort.c | 68 +++++++++++++++++++++++++++++++++++---- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/0912_sort_an_array/sort.c b/0912_sort_an_array/sort.c index 7f11deb..107783a 100644 --- a/0912_sort_an_array/sort.c +++ b/0912_sort_an_array/sort.c @@ -4,11 +4,11 @@ static void show(int *nums, int lo, int hi) { - int i; - for (i = lo; i <= hi; i++) { - printf("%d ", nums[i]); - } - printf("\n"); + int i; + for (i = lo; i <= hi; i++) { + printf("%d ", nums[i]); + } + printf("\n"); } static inline void swap(int *a, int *b) @@ -52,16 +52,70 @@ static void quick_sort(int *nums, int lo, int hi) quick_sort(nums, i + 1, hi); } +static void merge(int *nums, int lo, int mid, int hi) +{ + int i, j, k, size = hi - mid; + int *tmp = malloc(size * sizeof(int)); + + for (j = 0; j < size; j++) { + tmp[j] = nums[mid + 1 + j]; + } + + i = mid; + j = size - 1; + k = hi; + while (i >= lo && j >= 0) { + if (tmp[j] >= nums[i]) { + nums[k--] = tmp[j--]; + } else { + nums[k--] = nums[i--]; + } + } + + while (j >= 0) { + nums[k--] = tmp[j--]; + } + + free(tmp); +} + +static void merge_sort(int *nums, int lo, int hi) +{ + int mid; + + if (lo >= hi) { + return; + } + + mid = lo + (hi - lo) / 2; + + merge_sort(nums, lo, mid); + merge_sort(nums, mid + 1, hi); + + merge(nums, lo, mid, hi); +} + +int *sortArray(int *nums, int numsSize, int *returnSize) +{ +#if 1 + quick_sort(nums, 0, numsSize - 1); +#else + merge_sort(nums, 0, numsSize - 1); +#endif + *returnSize = numsSize; + return nums; +} + int main(int argc, char **argv) { int i, count = argc - 1; + int ret_size = 0; int *nums = malloc(count * sizeof(int)); for (i = 0; i < count; i++) { nums[i] = atoi(argv[i + 1]); } - quick_sort(nums, 0, count - 1); - show(nums, 0, count - 1); + show(sortArray(nums, count, &ret_size), 0, ret_size - 1); return 0; } From a01d82fb4eeddd0b75ce3e12699d904dd47484b7 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 18 Jan 2024 23:33:11 +0800 Subject: [PATCH 25/33] Improvement Signed-off-by: begeekmyfriend --- .../rm_dup.c | 13 +++++-------- .../rm_dup.cc | 13 +++++-------- 0070_climbing_stairs/climb_stairs.c | 18 +++++++++--------- .../window_substring.c | 8 ++++---- 4 files changed, 23 insertions(+), 29 deletions(-) diff --git a/0026_remove_duplicates_from_sorted_array/rm_dup.c b/0026_remove_duplicates_from_sorted_array/rm_dup.c index 95b2e0b..1bc5764 100644 --- a/0026_remove_duplicates_from_sorted_array/rm_dup.c +++ b/0026_remove_duplicates_from_sorted_array/rm_dup.c @@ -1,20 +1,17 @@ #include #include + static int removeDuplicates(int* nums, int numsSize) { - if (numsSize <= 1) { - return numsSize; - } - - int i, count = 1; + int i, size = 0; for (i = 1; i < numsSize; i++) { - if (nums[i - 1] != nums[i]) { - nums[count++] = nums[i]; + if (nums[size] != nums[i]) { + nums[++size] = nums[i]; } } - return count; + return size + 1; } int main(int argc, char **argv) diff --git a/0026_remove_duplicates_from_sorted_array/rm_dup.cc b/0026_remove_duplicates_from_sorted_array/rm_dup.cc index 2ceef80..ebfc556 100644 --- a/0026_remove_duplicates_from_sorted_array/rm_dup.cc +++ b/0026_remove_duplicates_from_sorted_array/rm_dup.cc @@ -5,16 +5,13 @@ using namespace std; class Solution { public: int removeDuplicates(vector& nums) { - if (nums.size() == 0) { - return 0; - } - - int count = 1; + int size = 0; for (int i = 1; i < nums.size(); i++) { - if (nums[i - 1] != nums[i]) { - nums[count++] = nums[i]; + if (nums[size] != nums[i]) { + nums[++size] = nums[i]; } } - return count; + + return size + 1; } }; diff --git a/0070_climbing_stairs/climb_stairs.c b/0070_climbing_stairs/climb_stairs.c index e1e05ea..31b1904 100644 --- a/0070_climbing_stairs/climb_stairs.c +++ b/0070_climbing_stairs/climb_stairs.c @@ -2,18 +2,18 @@ #include #include -static int dfs(int n, int *count) +static int dfs(int n, int *steps) { if (n == 1) { return 1; } else if (n == 2) { return 2; - } else if (count[n] > 0) { - return count[n]; + } else if (steps[n] > 0) { + return steps[n]; } else { - count[n] += dfs(n - 1, count); - count[n] += dfs(n - 2, count); - return count[n]; + steps[n] += dfs(n - 1, steps); + steps[n] += dfs(n - 2, steps); + return steps[n]; } } @@ -21,9 +21,9 @@ static int climbStairs(int n) { #if 1 if (n < 1) return 0; - int *count = malloc((n + 1) * sizeof(int)); - memset(count, 0, (n + 1) * sizeof(int)); - return dfs(n, count); + int *steps = malloc((n + 1) * sizeof(int)); + memset(steps, 0, (n + 1) * sizeof(int)); + return dfs(n, steps); #else int i, a = 1, b = 2, c; for (i = 3; i <= n; i++) { diff --git a/0076_minimum_window_substring/window_substring.c b/0076_minimum_window_substring/window_substring.c index 792e898..cd7f525 100644 --- a/0076_minimum_window_substring/window_substring.c +++ b/0076_minimum_window_substring/window_substring.c @@ -22,7 +22,7 @@ static char *minWindow(char *s, char *t) int l = 0, r = 0; int min_len = slen + 1; int start = 0; - int chars_to_meet = 0; + int len = 0; for (i = 0; i < tlen; i++) { count[t[i]]++; @@ -31,10 +31,10 @@ static char *minWindow(char *s, char *t) while (r < slen) { if (--count[s[r++]] >= 0) { /* pattern found */ - chars_to_meet++; + len++; } - while (chars_to_meet == tlen) { + while (len >= tlen) { if (r - l < min_len) { min_len = r - l; start = l; @@ -42,7 +42,7 @@ static char *minWindow(char *s, char *t) /* Chars with negative count are not included in the pattern string */ if (++count[s[l++]] > 0) { - chars_to_meet--; + len--; } } } From bda342caf7145b3a9e6c7025d2a1c2d7a8ad643e Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 23 Jan 2024 17:27:54 +0800 Subject: [PATCH 26/33] Improvement Signed-off-by: begeekmyfriend --- 0224_basic_calculator/calculator.c | 97 ++++++++++++++++-------------- 1 file changed, 51 insertions(+), 46 deletions(-) diff --git a/0224_basic_calculator/calculator.c b/0224_basic_calculator/calculator.c index e4cfac5..5c39e16 100644 --- a/0224_basic_calculator/calculator.c +++ b/0224_basic_calculator/calculator.c @@ -1,60 +1,65 @@ +#include #include #include -static int calculator(char *s) + +static int dfs(char **input) { - int n; - int pos1 = 0; - int pos2 = 0; - int *nums = malloc(1000 * sizeof(int)); - char *signs = malloc(1000 * sizeof(char)); + int i, res = 0; + int num = 0; + int stk[700], pos = 0; + char sign = '+'; + char *s = *input; - nums[pos1++] = 0; while (*s != '\0') { - switch (*s) { - case '+': - case '-': - case '(': - signs[pos2++] = *s; - break; - case ')': - --pos2; - if (pos1 >= 2 && pos2 > 0 && signs[pos2 - 1] != '(') { - n = nums[--pos1]; - int a = nums[--pos1]; - if (signs[--pos2] == '+') { - n = a + n; - } else { - n = a - n; - } - } - nums[pos1++] = n; - break; - case ' ': - break; - default: - n = 0; - while(*s >= '0' && *s <= '9') { - n = n * 10 + (*s - '0'); - s++; - } - s--; + char c = *s++; + if (isdigit(c)) { + num = 10 * num + (c - '0'); + } + + if (c == '(') { + /* dfs("2*(1+3)") = 2 * dfs("1+3") */ + num = dfs(&s); + } - if (pos1 >= 2 && signs[pos2 - 1] != '(' && signs[pos2 - 1] != '(') { - int a = nums[--pos1]; - if (signs[--pos2] == '+') { - n = a + n; - } else { - n = a - n; - } + if (!isdigit(c) && c != ' ' || *s == '\0') { + switch (sign) { + case '+': + stk[pos++] = num; + break; + case '-': + stk[pos++] = -num; + break; + case '*': + stk[pos - 1] *= num; + break; + case '/': + stk[pos - 1] /= num; + break; } - nums[pos1++] = n; - break; + /* update the sign and reset the number */ + sign = c; + num = 0; } - s++; + + /* return from the dfs */ + if (c == ')') + break; + } + + /* update position */ + *input = s; + + while (pos > 0) { + res += stk[--pos]; } - return n; + return res; +} + +static int calculator(char *s) +{ + return dfs(&s); } int main(int argc, char **argv) From 545e87d7580d0d4e5ab33f3e71fb6bce9d8631ca Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 23 Jan 2024 17:55:52 +0800 Subject: [PATCH 27/33] Add new problem Signed-off-by: begeekmyfriend --- 0560_subarray_sum_equals_k/subarray_sum.cc | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 0560_subarray_sum_equals_k/subarray_sum.cc diff --git a/0560_subarray_sum_equals_k/subarray_sum.cc b/0560_subarray_sum_equals_k/subarray_sum.cc new file mode 100644 index 0000000..e7fcced --- /dev/null +++ b/0560_subarray_sum_equals_k/subarray_sum.cc @@ -0,0 +1,28 @@ +#include + +using namespace std; + +class Solution { +public: + int subarraySum(vector& nums, int k) { + int res = 0, sum = 0; + unordered_map pre_sum_cnt; + + // The prefix sum array records the sum of nums[0...i], so we have + // presum[j] - presum[j] = k when the sum of nums[i...j] equals k. + // The presum[0] should always be 0. And pre_sum_cnt[0] = 1. + pre_sum_cnt[0] = 1; + for (const auto n : nums) { + // Here the sum means sum of nums[0...j] and the sum0 means sum + // of nums[0...i] then there will be sum - sum0 = k. + sum += n; + int sum0 = sum - k; + if (ht.count(sum0)) { + res += pre_sum_cnt[sum0]; + } + pre_sum_cnt[sum]++; + } + + return res; + } +}; From 0d16d6eb6c1604394ba94f5c3012c1ca95203a63 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 8 Apr 2024 20:52:15 +0800 Subject: [PATCH 28/33] Improvement Signed-off-by: begeekmyfriend --- .../kth_elem.c | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/0215_kth_largest_element_in_an_array/kth_elem.c b/0215_kth_largest_element_in_an_array/kth_elem.c index bf9ea50..b14d278 100644 --- a/0215_kth_largest_element_in_an_array/kth_elem.c +++ b/0215_kth_largest_element_in_an_array/kth_elem.c @@ -2,6 +2,15 @@ #include +static void show(int *nums, int lo, int hi) +{ + int i; + for (i = lo; i <= hi; i++) { + printf("%d ", nums[i]); + } + printf("\n"); +} + static inline void swap(int *a, int *b) { int t = *a; @@ -38,41 +47,43 @@ static void build_max_heap(int *nums, int size) } } -static int quick_select(int *nums, int lo, int hi, int k) +static void quick_select(int *nums, int lo, int hi, int k) { if (lo >= hi) { - return hi; + return; } int i = lo - 1; - int j = hi + 1; - int pivot = nums[lo]; + int j = hi; + int pivot = nums[hi]; + while (i < j) { /* For case of large amounts of consecutive duplicate elements, we * shall make the partition in the middle of the array as far as * possible. If the partition is located in the head or tail, the * performance might well be very bad for it. */ - while (nums[++i] > pivot) {} - while (nums[--j] < pivot) {} + while (i < hi && nums[++i] > pivot) {} + while (j > lo && nums[--j] < pivot) {} if (i < j) { swap(&nums[i], &nums[j]); } } /* invariant: i == j + 1 or i == j */ - if (j >= k - 1) { - return quick_select(nums, lo, j, k); + swap(&nums[i], &nums[hi]); + if (i + 1 >= k) { + quick_select(nums, lo, i - 1, k); } else { - return quick_select(nums, j + 1, hi, k); + quick_select(nums, i + 1, hi, k); } } int findKthLargest(int* nums, int numsSize, int k) { -#if 0 - int i = quick_select(nums, 0, numsSize - 1, k); - return nums[i]; +#if 1 + quick_select(nums, 0, numsSize - 1, k); + return nums[k - 1]; #else int i; From ea7312c7511d1b8a663df02167281c93ac039a29 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 5 May 2024 10:28:56 +0800 Subject: [PATCH 29/33] Improvement Signed-off-by: begeekmyfriend --- 0025_reverse_nodes_in_k_group/reverse_nodes.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/0025_reverse_nodes_in_k_group/reverse_nodes.c b/0025_reverse_nodes_in_k_group/reverse_nodes.c index c28dab0..ecbe9a1 100644 --- a/0025_reverse_nodes_in_k_group/reverse_nodes.c +++ b/0025_reverse_nodes_in_k_group/reverse_nodes.c @@ -14,21 +14,21 @@ static struct ListNode* reverseKGroup(struct ListNode* head, int k) dummy.next = head; for (; head != NULL; head = head->next) { if (++len % k == 0) { - /* t always the original first one */ - struct ListNode *t = prev->next; + /* p always the original first one */ + struct ListNode *p = prev->next; /* loop condition implicits the final state */ while (prev->next != head) { /* the new segment head */ - struct ListNode *h = t->next; + struct ListNode *q = p->next; /* deletion */ - t->next = h->next; + p->next = q->next; /* insertion */ - h->next = prev->next; - prev->next = h; + q->next = prev->next; + prev->next = q; } /* For iteration */ - prev = t; - head = t; + prev = p; + head = p; } } return dummy.next; From 4fab7e0a488ac63f4e5542952104467684e60614 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 12 Jun 2024 11:51:32 +0800 Subject: [PATCH 30/33] Improvement Signed-off-by: begeekmyfriend --- 0015_three_sum/three_sum.c | 12 ++++++++---- 0018_four_sum/four_sum.c | 7 +++++-- 0046_permutations/permutations.c | 6 +++--- 0047_permutations_ii/permutations.c | 6 +++--- 0199_binary_tree_right_side_view/bst_right.c | 4 +--- 5 files changed, 20 insertions(+), 15 deletions(-) diff --git a/0015_three_sum/three_sum.c b/0015_three_sum/three_sum.c index 53cd947..5b096c1 100644 --- a/0015_three_sum/three_sum.c +++ b/0015_three_sum/three_sum.c @@ -43,7 +43,7 @@ int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes int i, j, capacity = 50000; int **results = malloc(capacity * sizeof(int *)); for (i = 0; i < numsSize - 2; i++) { - if (i == 0 || i > 0 && nums[i] != nums[i - 1]) { + if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { two_sum(nums, i + 1, numsSize - 1, -nums[i], results, returnSize); } } @@ -58,14 +58,18 @@ int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes int main(void) { - int i, count; + int i, j, count; //int nums[] = { -1, 0, 1, 2, -1, -4 }; //int nums[] = { 0, 0, 0 }; //int nums[] = { -1, 0, 1, 0 }; int nums[] = {-2,0,0,2,2}; - int **triplets = threeSum(nums, sizeof(nums) / sizeof(*nums), &count); + int *col_sizes; + int **triplets = threeSum(nums, sizeof(nums) / sizeof(*nums), &count, &col_sizes); for (i = 0; i < count; i++) { - printf("%d %d %d\n", triplets[i][0], triplets[i][1], triplets[i][2]); + for (j = 0; j < col_sizes[i]; j++) { + printf("%d \n", triplets[i][j]); + } + printf("\n"); } return 0; diff --git a/0018_four_sum/four_sum.c b/0018_four_sum/four_sum.c index 8b8a182..8b06eaf 100644 --- a/0018_four_sum/four_sum.c +++ b/0018_four_sum/four_sum.c @@ -68,13 +68,16 @@ int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** return int main(void) { - int i, count, target = 11, *col_sizes; + int i, j, count, target = 11, *col_sizes; //int nums[] = { 1, 0, -1, 0, -2, 2 }; //int nums[] = { -3, -2, -1, 0, 0, 1, 2, 3 }; int nums[] = { 0, 1, 5, 0, 1, 5, 5, -4 }; int **quadruplets = fourSum(nums, sizeof(nums) / sizeof(*nums), target, &count, &col_sizes); for (i = 0; i < count; i++) { - printf("%d %d %d %d\n", quadruplets[i][0], quadruplets[i][1], quadruplets[i][2], quadruplets[i][3]); + for (j = 0; j < col_sizes[i]; j++) { + printf("%d ", quadruplets[i][j]); + } + printf("\n"); } return 0; diff --git a/0046_permutations/permutations.c b/0046_permutations/permutations.c index 9f9ca36..49b0b73 100644 --- a/0046_permutations/permutations.c +++ b/0046_permutations/permutations.c @@ -88,10 +88,10 @@ int main(int argc, char **argv) nums[i] = atoi(argv[i + 1]); } - int *size; - int **lists = permute(nums, argc - 1, &count, &size); + int *col_sizes; + int **lists = permute(nums, argc - 1, &count, &col_sizes); for (i = 0; i < count; i++) { - for (j = 0; j < argc - 1; j++) { + for (j = 0; j < col_sizes[i]; j++) { printf("%d", lists[i][j]); } putchar('\n'); diff --git a/0047_permutations_ii/permutations.c b/0047_permutations_ii/permutations.c index 96688cb..612867b 100644 --- a/0047_permutations_ii/permutations.c +++ b/0047_permutations_ii/permutations.c @@ -72,10 +72,10 @@ int main(int argc, char **argv) nums[i] = atoi(argv[i + 1]); } - int *size; - int **lists = permute(nums, argc - 1, &count, &size); + int *col_sizes; + int **lists = permute(nums, argc - 1, &count, &col_sizes); for (i = 0; i < count; i++) { - for (j = 0; j < argc - 1; j++) { + for (j = 0; j < col_sizes[i]; j++) { printf("%d", lists[i][j]); } putchar('\n'); diff --git a/0199_binary_tree_right_side_view/bst_right.c b/0199_binary_tree_right_side_view/bst_right.c index f8fdbf4..2be03cd 100644 --- a/0199_binary_tree_right_side_view/bst_right.c +++ b/0199_binary_tree_right_side_view/bst_right.c @@ -90,9 +90,7 @@ static void node_free(struct queue_node *qn, struct list_head *free_list) } /** - ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *returnColumnSizes array. - ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). + ** The returned array must be malloced, assume caller calls free(). **/ static int* rightSideView(struct TreeNode* root, int* returnSize) { From 15d6c5fcbb0c25cf74b8868f078e4301a39e458f Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 7 May 2025 07:30:58 +0800 Subject: [PATCH 31/33] Improvement Signed-off-by: begeekmyfriend --- 0039_combination_sum/combination_sum.cc | 2 +- 0045_jump_game_ii/jump_game.c | 8 ++++---- 0045_jump_game_ii/jump_game.cc | 14 +++++++------- 0069_sqrt/sqrt.c | 3 +++ 0069_sqrt/sqrt.cc | 3 +++ .../window_substring.cc | 15 ++++++++++----- 0137_single_number_ii/single_number.c | 1 + 0190_reverse_bits/reverse_bits.c | 19 +++++++++++-------- 8 files changed, 40 insertions(+), 25 deletions(-) diff --git a/0039_combination_sum/combination_sum.cc b/0039_combination_sum/combination_sum.cc index a45abf8..a95ab08 100644 --- a/0039_combination_sum/combination_sum.cc +++ b/0039_combination_sum/combination_sum.cc @@ -20,7 +20,7 @@ class Solution { } else { for (int i = start; i < candidates.size(); i++) { stack.push_back(candidates[i]); - /* The elements in solution can be duplicate for the purpose of the problem */ + /* The elements in solution can be taken as many times as you can for the purpose of the problem */ dfs(candidates, i, target - candidates[i], res); stack.pop_back(); } diff --git a/0045_jump_game_ii/jump_game.c b/0045_jump_game_ii/jump_game.c index 9de0eda..0d9ffb2 100644 --- a/0045_jump_game_ii/jump_game.c +++ b/0045_jump_game_ii/jump_game.c @@ -12,10 +12,10 @@ static int jump(int* nums, int numsSize) int i, right = 0; int steps = 0; int fartest = 0; - /* 1. Exhaust all the right boundries in the location range of [i...right] - * 2. When the search ends up with i==right, update the right boundry as - * the fartest position. - * 3. When the search ends up with i==right, it records as one jump step */ + /* 1. Exhaust all the right boundries in the location range of [i...farthest] + * 2. When i reaches the farthest boundary, update the farthest boundry + * and the step number. + * 3. Apply condition i < size - 1 and iterator i++ to avoid overflow. */ for (i = 0; i < numsSize; i++) { fartest = max(i + nums[i], fartest); if (i == right) { diff --git a/0045_jump_game_ii/jump_game.cc b/0045_jump_game_ii/jump_game.cc index e561405..cf61281 100644 --- a/0045_jump_game_ii/jump_game.cc +++ b/0045_jump_game_ii/jump_game.cc @@ -8,14 +8,14 @@ class Solution { int steps = 0; int right = 0; int farthest = 0; - // 1. Exhaust all the right boundries in the location range of [i...right] - // 2. When the search ends up with i==right, update the right boundry as - // the fartest position. - // 3. When the search ends up with i==right, it records as one jump step */ + // 1. Exhaust all the right boundries in the location range of [i...farthest] + // 2. When i reaches the farthest boundary, update the farthest boundry + // and the step number. + // 3. Apply condition i < size - 1 and iterator i++ to avoid overflow. for (int i = 0; i < nums.size() - 1; i++) { - fartest = max(i + nums[i], fartest); - for (i == right) { - right = fartest; + right = max(i + nums[i], right); + if (i == farthest) { + farthest = right; steps++; } } diff --git a/0069_sqrt/sqrt.c b/0069_sqrt/sqrt.c index e4fdcd0..70a8411 100644 --- a/0069_sqrt/sqrt.c +++ b/0069_sqrt/sqrt.c @@ -60,6 +60,9 @@ int mySqrt(int x) unsigned int lo = 1; unsigned int hi = (unsigned int) x; unsigned int mid = lo + (hi - lo) / 2; + // Firstly test mid > x / mid to decide whether hi = mid; + // else then test mid + 1 > x / (mid + 1) to decide whether the mid is located; + // Otherwise assign low = mid. for (; ;) { if (mid > x/mid) { hi = mid; diff --git a/0069_sqrt/sqrt.cc b/0069_sqrt/sqrt.cc index 8e47bf6..40445ce 100644 --- a/0069_sqrt/sqrt.cc +++ b/0069_sqrt/sqrt.cc @@ -11,6 +11,9 @@ class Solution { unsigned int lo = 1, hi = x; unsigned int mid = (lo + hi) / 2; + // Firstly test mid > x / mid to decide whether hi = mid; + // else then test mid + 1 > x / (mid + 1) to decide whether the mid is located; + // Otherwise assign low = mid. for (; ;) { if (mid > x / mid) { hi = mid; diff --git a/0076_minimum_window_substring/window_substring.cc b/0076_minimum_window_substring/window_substring.cc index d419221..8fd41bd 100644 --- a/0076_minimum_window_substring/window_substring.cc +++ b/0076_minimum_window_substring/window_substring.cc @@ -11,20 +11,25 @@ class Solution { } int l = 0, r = 0; - int need_to_meet = t.length(); - int start, min_len = INT_MAX; + int hit_num = 0; + int start = 0, min_len = INT_MAX; while (r < s.length()) { + // counting each letter in the string. The zero and positive + // countings indicate ones in pattern. And the negative ones + // indicate those out of the pattern. if (--count[s[r++]] >= 0) { - need_to_meet--; + hit_num++; } - while (need_to_meet == 0) { + while (hit_num == t.length()) { if (r - l < min_len) { start = l; min_len = r - l; } + // The countings of the letter larger than zero shall be + // the ones in the pattern. if (++count[s[l++]] > 0) { - need_to_meet++; + hit_num--; } } } diff --git a/0137_single_number_ii/single_number.c b/0137_single_number_ii/single_number.c index bf5beae..b02f66f 100644 --- a/0137_single_number_ii/single_number.c +++ b/0137_single_number_ii/single_number.c @@ -39,6 +39,7 @@ static int singleNumber(int *nums, int numsSize) count[i]++; } } + /* The specified bit counting should be multiple of 3 without the outlier */ mask |= (count[i] % 3) << i; } return mask; diff --git a/0190_reverse_bits/reverse_bits.c b/0190_reverse_bits/reverse_bits.c index 5fcf123..8ba7cff 100644 --- a/0190_reverse_bits/reverse_bits.c +++ b/0190_reverse_bits/reverse_bits.c @@ -4,14 +4,17 @@ static uint32_t reverseBits(uint32_t n) { - int i; - uint32_t res = 0; - for (i = 0; i < 32; i++) { - res <<= 1; - res |= n & 0x1; - n >>= 1; - } - return res; + const uint32_t MASK1 = 0x55555555; + const uint32_t MASK2 = 0x33333333; + const uint32_t MASK4 = 0x0f0f0f0f; + const uint32_t MASK8 = 0x00ff00ff; + + // Extract and swap the even and odd bit groups. + n = (n & MASK1) << 1 | ((n >> 1) & MASK1); + n = (n & MASK2) << 2 | ((n >> 2) & MASK2); + n = (n & MASK4) << 4 | ((n >> 4) & MASK4); + n = (n & MASK8) << 8 | ((n >> 8) & MASK8); + return n << 16 | n >> 16; } int main(int argc, char **argv) From 0e4fa45e8e34511d8a9b8c4dea503d2cbe6f4e88 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 13 May 2025 09:13:12 +0800 Subject: [PATCH 32/33] Improvement Signed-off-by: begeekmyfriend --- 0031_next_permutation/next_permutation.c | 8 ++++---- 0031_next_permutation/next_permutation.cc | 5 +++++ 0912_sort_an_array/sort.c | 12 ++++++++---- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/0031_next_permutation/next_permutation.c b/0031_next_permutation/next_permutation.c index 49ddbe5..8cd3024 100644 --- a/0031_next_permutation/next_permutation.c +++ b/0031_next_permutation/next_permutation.c @@ -21,15 +21,13 @@ static void reverse(int *a, int size) static void nextPermutation(int* nums, int numsSize) { - if (numsSize <= 1) { - return; - } - + // find the first smaller element in decreasing sequence from back to forth. int i = numsSize - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { i--; } + // if found, find the first bigger element from back to forth and swap them. if (i >= 0) { int j = numsSize - 1; while (j >= 0 && nums[j] <= nums[i]) { @@ -37,6 +35,8 @@ static void nextPermutation(int* nums, int numsSize) } swap(nums + i, nums + j); } + + // reverse the subsequence into increasing one. reverse(nums + i + 1, numsSize - i - 1); } diff --git a/0031_next_permutation/next_permutation.cc b/0031_next_permutation/next_permutation.cc index 5b8256c..f12077d 100644 --- a/0031_next_permutation/next_permutation.cc +++ b/0031_next_permutation/next_permutation.cc @@ -5,11 +5,15 @@ using namespace std; class Solution { public: void nextPermutation(vector& nums) { + // find the first smaller element in decreasing sequence from back to + // forth. int i = nums.size() - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { i--; } + // if found, find the first bigger element from back to forth and swap + // them. if (i >= 0) { int j = nums.size() - 1; while (j >= 0 && nums[i] >= nums[j]) { @@ -18,6 +22,7 @@ class Solution { swap(nums[i], nums[j]); } + // reverse the subsequence into increasing one. reverse(nums.begin() + i + 1, nums.end()); } }; diff --git a/0912_sort_an_array/sort.c b/0912_sort_an_array/sort.c index 107783a..304ffaf 100644 --- a/0912_sort_an_array/sort.c +++ b/0912_sort_an_array/sort.c @@ -26,7 +26,7 @@ static void quick_sort(int *nums, int lo, int hi) return; } - /* shuffle the pivot */ + /* shuffle the pivot as it is a must for performance */ mid = lo + (hi - lo) / 2; swap(&nums[mid], &nums[hi]); @@ -38,11 +38,15 @@ static void quick_sort(int *nums, int lo, int hi) * shall make the partition in the middle of the array as far as * possible. If the partition is located in the head or tail, the * performance might well be very bad for it. + * + * Note: Do NOT use nums[++i] <= pivot or nums[--j] >= pivot as the + * loop condition because it leads to redundant operations in each + * recusive iteration when there are many duplicate elements. */ - while (i < hi && nums[++i] < pivot) {} - while (j > lo && nums[--j] > pivot) {} + while (i < j && nums[++i] < pivot) {} + while (i < j && nums[--j] > pivot) {} if (i < j) { - swap(&nums[i], &nums[j]); + swap(&nums[i], &nums[j]); } } From 02b17696de11195db74e6c1fde809185b58e8240 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 13 May 2025 09:33:18 +0800 Subject: [PATCH 33/33] Improvement Signed-off-by: begeekmyfriend --- 0215_kth_largest_element_in_an_array/kth_elem.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/0215_kth_largest_element_in_an_array/kth_elem.c b/0215_kth_largest_element_in_an_array/kth_elem.c index b14d278..dd049b5 100644 --- a/0215_kth_largest_element_in_an_array/kth_elem.c +++ b/0215_kth_largest_element_in_an_array/kth_elem.c @@ -62,6 +62,10 @@ static void quick_select(int *nums, int lo, int hi, int k) * shall make the partition in the middle of the array as far as * possible. If the partition is located in the head or tail, the * performance might well be very bad for it. + * + * Note: Do NOT use nums[++i] <= pivot or nums[--j] >= pivot as the + * loop condition because it leads to redundant operations in each + * recusive iteration when there are many duplicate elements. */ while (i < hi && nums[++i] > pivot) {} while (j > lo && nums[--j] < pivot) {} @@ -72,7 +76,8 @@ static void quick_select(int *nums, int lo, int hi, int k) /* invariant: i == j + 1 or i == j */ swap(&nums[i], &nums[hi]); - if (i + 1 >= k) { + /* compare index [i] with [k - 1] to locate the kth element */ + if (i > k - 1) { quick_select(nums, lo, i - 1, k); } else { quick_select(nums, i + 1, hi, k);