From 8a9ad6f6cd6c9005a29304784b6da473fdff62e0 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 13 Nov 2017 09:39:15 +0800 Subject: [PATCH 001/211] Find minimum in rotated sorted array Signed-off-by: begeekmyfriend --- .../Makefile | 2 ++ .../minimum.c | 31 +++++++++++++++++++ .../Makefile | 2 ++ .../minimum.c | 27 ++++++++++++++++ 4 files changed, 62 insertions(+) create mode 100644 153_find_minimum_in_rotated_sorted_array/Makefile create mode 100644 153_find_minimum_in_rotated_sorted_array/minimum.c create mode 100644 154_find_minimum_in_rotated_sorted_array_ii/Makefile create mode 100644 154_find_minimum_in_rotated_sorted_array_ii/minimum.c diff --git a/153_find_minimum_in_rotated_sorted_array/Makefile b/153_find_minimum_in_rotated_sorted_array/Makefile new file mode 100644 index 0000000..b6eb212 --- /dev/null +++ b/153_find_minimum_in_rotated_sorted_array/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test minimum.c diff --git a/153_find_minimum_in_rotated_sorted_array/minimum.c b/153_find_minimum_in_rotated_sorted_array/minimum.c new file mode 100644 index 0000000..1073f1f --- /dev/null +++ b/153_find_minimum_in_rotated_sorted_array/minimum.c @@ -0,0 +1,31 @@ +#include +#include +#include + +static int findMin(int* nums, int numsSize) +{ + int lo = 0; + int hi = numsSize - 1; + int min = INT_MAX; + while (lo <= hi) { + int mid = lo + (hi - lo) / 2; + min = min < nums[mid] ? min : nums[mid]; + if (nums[mid] > nums[hi]) { + lo = mid + 1; + } else { + hi = mid - 1; + } + } + return min; +} + +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]); + } + printf("%d\n", findMin(nums, count)); + return 0; +} diff --git a/154_find_minimum_in_rotated_sorted_array_ii/Makefile b/154_find_minimum_in_rotated_sorted_array_ii/Makefile new file mode 100644 index 0000000..b6eb212 --- /dev/null +++ b/154_find_minimum_in_rotated_sorted_array_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test minimum.c diff --git a/154_find_minimum_in_rotated_sorted_array_ii/minimum.c b/154_find_minimum_in_rotated_sorted_array_ii/minimum.c new file mode 100644 index 0000000..a1ec893 --- /dev/null +++ b/154_find_minimum_in_rotated_sorted_array_ii/minimum.c @@ -0,0 +1,27 @@ +#include +#include + +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]; + } + } + return nums[0]; +} + +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]); + } + printf("%d\n", findMin(nums, count)); + return 0; +} From 8a2b8f15d92eea6280e9b66d8ed72659ae380fc5 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 14 Nov 2017 10:52:43 +0800 Subject: [PATCH 002/211] Maximum gap Signed-off-by: begeekmyfriend --- 164_maximum_gap/Makefile | 2 ++ 164_maximum_gap/max_gap.c | 67 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 164_maximum_gap/Makefile create mode 100644 164_maximum_gap/max_gap.c diff --git a/164_maximum_gap/Makefile b/164_maximum_gap/Makefile new file mode 100644 index 0000000..e011d5f --- /dev/null +++ b/164_maximum_gap/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test max_gap.c diff --git a/164_maximum_gap/max_gap.c b/164_maximum_gap/max_gap.c new file mode 100644 index 0000000..00e9237 --- /dev/null +++ b/164_maximum_gap/max_gap.c @@ -0,0 +1,67 @@ +#include +#include +#include + +static int maximumGap(int* nums, int numsSize) +{ + if (numsSize < 2) { + return 0; + } + + int i; + int min = INT_MAX; + int max = INT_MIN; + for (i = 0; i < numsSize; i++) { + min = nums[i] < min ? nums[i] : min; + max = nums[i] > max ? nums[i] : max; + } + + /* the max gap size must be larger than or equal to the average */ + double buck_size = 1.0 * (max - min) / (numsSize - 1); + /* In case of all elememnts are the same number */ + if (buck_size == 0) { + return 0; + } + + int buck_cnt = (max - min) / buck_size + 1; + int *max_buck = malloc(buck_cnt * sizeof(int)); + int *min_buck = malloc(buck_cnt * sizeof(int)); + for (i = 0; i < buck_cnt; i++) { + max_buck[i] = INT_MIN; + min_buck[i] = INT_MAX; + } + + for (i = 0; i < numsSize; i++) { + int id = (nums[i] - min) / buck_size; + max_buck[id] = nums[i] > max_buck[id] ? nums[i] : max_buck[id]; + min_buck[id] = nums[i] < min_buck[id] ? nums[i] : min_buck[id]; + } + + int max_gap = 0; + /* Must not be empty */ + int last_max = max_buck[0]; + for (i = 1; i < buck_cnt; i++) { + if (min_buck[i] != INT_MAX) { + /* What we care about is the difference between the last element + * in the last max bucket and the first element in the next min + * bucket since the max gap must be larger or equal than the average + * while the differences of elements in one bucket must less than + * the average */ + max_gap = min_buck[i] - last_max > max_gap ? min_buck[i] - last_max : max_gap; + last_max = max_buck[i]; + } + } + + return max_gap; +} + +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]); + } + printf("%d\n", maximumGap(nums, count)); + return 0; +} From a659c7991baaef845b1e83ef5f3047a4b58676dd Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 15 Nov 2017 09:38:07 +0800 Subject: [PATCH 003/211] Reverse words in a string Signed-off-by: begeekmyfriend --- 151_reverse_words_in_a_string/Makefile | 2 + 151_reverse_words_in_a_string/reverse.c | 49 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 151_reverse_words_in_a_string/Makefile create mode 100644 151_reverse_words_in_a_string/reverse.c diff --git a/151_reverse_words_in_a_string/Makefile b/151_reverse_words_in_a_string/Makefile new file mode 100644 index 0000000..60a46ef --- /dev/null +++ b/151_reverse_words_in_a_string/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test reverse.c diff --git a/151_reverse_words_in_a_string/reverse.c b/151_reverse_words_in_a_string/reverse.c new file mode 100644 index 0000000..dab5480 --- /dev/null +++ b/151_reverse_words_in_a_string/reverse.c @@ -0,0 +1,49 @@ +#include +#include +#include + +static reverse(char *s, int lo, int hi) +{ + while (lo < hi) { + char c = s[lo]; + s[lo] = s[hi]; + s[hi] = c; + lo++; + hi--; + } +} + +static void reverseWords(char *s) +{ + int i = 0, j = 0; + while (s[i] != '\0') { + while (s[i] == ' ') { + i++; + } + if (s[i] == '\0') break; + while (s[i] != '\0' && s[i] != ' ') { + s[j++] = s[i++]; + } + s[j++] = s[i]; + } + s[j] = '\0'; + s[--j] = '\0'; + reverse(s, 0, j - 1); + + for (i = 0, j = 0; s[i] != '\0';) { + for (j = i; s[j] != '\0' && s[j] != ' '; j++) {} + reverse(s, i, j - 1); + for (i = j; s[i] != '\0' && s[i] == ' '; i++) {} + } +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test string\n"); + exit(-1); + } + reverseWords(argv[1]); + printf("%s\n", argv[1]); + return 0; +} From 32473f8629c789adf2e641d5ad80fbeb078456b4 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 16 Nov 2017 09:39:30 +0800 Subject: [PATCH 004/211] Maximum product subarray Signed-off-by: begeekmyfriend --- 152_maximum_product_subarray/Makefile | 2 ++ 152_maximum_product_subarray/subarray.c | 43 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 152_maximum_product_subarray/Makefile create mode 100644 152_maximum_product_subarray/subarray.c diff --git a/152_maximum_product_subarray/Makefile b/152_maximum_product_subarray/Makefile new file mode 100644 index 0000000..59aa57a --- /dev/null +++ b/152_maximum_product_subarray/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test subarray.c diff --git a/152_maximum_product_subarray/subarray.c b/152_maximum_product_subarray/subarray.c new file mode 100644 index 0000000..c791807 --- /dev/null +++ b/152_maximum_product_subarray/subarray.c @@ -0,0 +1,43 @@ +#include +#include + +static int maxProduct(int* nums, int numsSize) +{ + if (numsSize == 0) { + return 0; + } + + int i, global_max = nums[0], product; + int local_min = 1, local_max = 1; + for (i = 0; i < numsSize; i++) { + if (nums[i] > 0) { + product = local_max * nums[i]; + global_max = product > global_max ? product : global_max; + local_max *= nums[i]; + local_min *= nums[i]; + } else if (nums[i] < 0) { + product = local_min * nums[i]; + global_max = product > global_max ? product : global_max; + int tmp = local_max; + local_max = product > 1 ? product : 1; + local_min = tmp * nums[i]; + } else { + global_max = global_max > 0 ? global_max : 0; + local_max = 1; + local_min = 1; + } + } + + return global_max; +} + +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]); + } + printf("%d\n", maxProduct(nums, count)); + return 0; +} From b1e31afbd247f2bc09c10266c7c32156477a2437 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 17 Nov 2017 09:47:46 +0800 Subject: [PATCH 005/211] Find peak element Signed-off-by: begeekmyfriend --- 162_find_peak_element/Makefile | 2 ++ 162_find_peak_element/peak.c | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 162_find_peak_element/Makefile create mode 100644 162_find_peak_element/peak.c diff --git a/162_find_peak_element/Makefile b/162_find_peak_element/Makefile new file mode 100644 index 0000000..3e53c7d --- /dev/null +++ b/162_find_peak_element/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test peak.c diff --git a/162_find_peak_element/peak.c b/162_find_peak_element/peak.c new file mode 100644 index 0000000..bb1d2f5 --- /dev/null +++ b/162_find_peak_element/peak.c @@ -0,0 +1,24 @@ +#include +#include + +static int findPeakElement(int* nums, int numsSize) +{ + if (numsSize == 1) { + return nums[0]; + } + + int i; + for (i = 1; i < numsSize && nums[i] > nums[i - 1]; i++) {} + return i - 1; +} + +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]); + } + printf("%d\n", findPeakElement(nums, count)); + return 0; +} From c40a44395cc845d26eaddf51559c16a56c57b7a1 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sat, 18 Nov 2017 10:39:33 +0800 Subject: [PATCH 006/211] Excel sheet column Signed-off-by: Leo Ma --- 168_excel_sheet_column_title/Makefile | 2 ++ 168_excel_sheet_column_title/sheet_column.c | 36 ++++++++++++++++++++ 171_excel_sheet_column_number/Makefile | 2 ++ 171_excel_sheet_column_number/sheet_column.c | 24 +++++++++++++ 4 files changed, 64 insertions(+) create mode 100644 168_excel_sheet_column_title/Makefile create mode 100644 168_excel_sheet_column_title/sheet_column.c create mode 100644 171_excel_sheet_column_number/Makefile create mode 100644 171_excel_sheet_column_number/sheet_column.c diff --git a/168_excel_sheet_column_title/Makefile b/168_excel_sheet_column_title/Makefile new file mode 100644 index 0000000..fd0a780 --- /dev/null +++ b/168_excel_sheet_column_title/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test sheet_column.c diff --git a/168_excel_sheet_column_title/sheet_column.c b/168_excel_sheet_column_title/sheet_column.c new file mode 100644 index 0000000..bc05ef8 --- /dev/null +++ b/168_excel_sheet_column_title/sheet_column.c @@ -0,0 +1,36 @@ +#include +#include + +static char *convertToTitle(int n) +{ + if (n <= 0) { + return ""; + } + + char *result = malloc(1024); + int len = 0; + do { + result[len++] = ((n - 1) % 26) + 'A'; + n = (n - 1) / 26; + } while (n > 0); + result[len] = '\0'; + + int i, j; + for (i = 0, j = len - 1; i < j; i++, j--) { + char c = result[i]; + result[i] = result[j]; + result[j] = c; + } + return result; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test n\n"); + exit(-1); + } + + printf("%s\n", convertToTitle(atoi(argv[1]))); + return 0; +} diff --git a/171_excel_sheet_column_number/Makefile b/171_excel_sheet_column_number/Makefile new file mode 100644 index 0000000..fd0a780 --- /dev/null +++ b/171_excel_sheet_column_number/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test sheet_column.c diff --git a/171_excel_sheet_column_number/sheet_column.c b/171_excel_sheet_column_number/sheet_column.c new file mode 100644 index 0000000..2df5623 --- /dev/null +++ b/171_excel_sheet_column_number/sheet_column.c @@ -0,0 +1,24 @@ +#include +#include + +static int titleToNumber(char *s) +{ + int n = 0; + while (*s != '\0') { + n *= 26; + n += *s++ - 'A' + 1; + } + + return n; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test ABC\n"); + exit(-1); + } + + printf("%d\n", titleToNumber(argv[1])); + return 0; +} From 39f34868796dd303ccaed0f44173817f5387728e Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 19 Nov 2017 09:00:36 +0800 Subject: [PATCH 007/211] Intersection of two linked lists Signed-off-by: Leo Ma --- 160_intersection_of_two_linked_list/Makefile | 2 + .../intersection.c | 53 +++++++++++++++++++ 167_two_sum_ii/Makefile | 2 + 167_two_sum_ii/two_sum.c | 50 +++++++++++++++++ 4 files changed, 107 insertions(+) create mode 100644 160_intersection_of_two_linked_list/Makefile create mode 100644 160_intersection_of_two_linked_list/intersection.c create mode 100644 167_two_sum_ii/Makefile create mode 100644 167_two_sum_ii/two_sum.c diff --git a/160_intersection_of_two_linked_list/Makefile b/160_intersection_of_two_linked_list/Makefile new file mode 100644 index 0000000..8a7201e --- /dev/null +++ b/160_intersection_of_two_linked_list/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test intersection.c diff --git a/160_intersection_of_two_linked_list/intersection.c b/160_intersection_of_two_linked_list/intersection.c new file mode 100644 index 0000000..d33de4f --- /dev/null +++ b/160_intersection_of_two_linked_list/intersection.c @@ -0,0 +1,53 @@ +#include +#include +#include + +struct ListNode { + int val; + struct ListNode *next; +}; + +static struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) +{ + struct ListNode *p; + for (p = headA; p->next != NULL; p = p->next) {} + p->next = headB; + + bool first = true; + struct ListNode *p0, *p1; + for (p0 = headA, p1 = headA; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) { + if (p0 == p1 && !first) { + p0 = headA; + while (p0 != p1) { + p0 = p0->next; + p1 = p1->next; + } + p->next = NULL; + return p0; + } + first = false; + } + + p->next = NULL; + return NULL; +} + +int main(int argc, char **argv) +{ + struct ListNode *headA = malloc(sizeof(*headA)); + struct ListNode *headB = malloc(sizeof(*headB)); + struct ListNode *common = malloc(sizeof(*common)); + + headA->val = 1; + headB->val = 2; + common->val = 4; + headA->next = common; + headB->next = common; + common->next = NULL; + + struct ListNode *p = getIntersectionNode(headA, headB); + if (p != NULL) { + printf("%d\n", p->val); + } + return 0; +} diff --git a/167_two_sum_ii/Makefile b/167_two_sum_ii/Makefile new file mode 100644 index 0000000..ffb6456 --- /dev/null +++ b/167_two_sum_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test two_sum.c diff --git a/167_two_sum_ii/two_sum.c b/167_two_sum_ii/two_sum.c new file mode 100644 index 0000000..38eb52d --- /dev/null +++ b/167_two_sum_ii/two_sum.c @@ -0,0 +1,50 @@ +#include +#include + +/** + * Return an array of size *returnSize. + * Note: The returned array must be malloced, assume caller calls free(). + */ +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]; + if (diff < numbers[j]) { + while (i < --j && numbers[j + 1] == numbers[j]) {} + } else if (diff > numbers[j]) { + while (++i < j && numbers[i - 1] == numbers[i]) {} + } else { + *returnSize = 2; + int *indexes = malloc(*returnSize * sizeof(int)); + indexes[0] = i + 1; + indexes[1] = j + 1; + return indexes; + } + } + + *returnSize = 0; + return NULL; +} + +int main(int argc, char **argv) +{ + if (argc < 3) { + fprintf(stderr, "Usage: ./test target n1 n2..."); + exit(-1); + } + + int i, count = argc - 2; + int target = atoi(argv[1]); + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 2]); + } + + int number = 0; + int *indexes = twoSum(nums, count, target, &number); + if (indexes != NULL) { + printf("%d %d\n", indexes[0], indexes[1]); + } + return 0; +} From 579cd4d07ba4e3f0cf78b89f4c62888b796ba77f Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Mon, 20 Nov 2017 09:35:29 +0800 Subject: [PATCH 008/211] majority element Signed-off-by: Leo Ma --- 169_majority_element/Makefile | 2 ++ 169_majority_element/majority.c | 37 +++++++++++++++++++++++++++ 172_factorial_trailing_zeros/Makefile | 2 ++ 172_factorial_trailing_zeros/zeroes.c | 18 +++++++++++++ 4 files changed, 59 insertions(+) create mode 100644 169_majority_element/Makefile create mode 100644 169_majority_element/majority.c create mode 100644 172_factorial_trailing_zeros/Makefile create mode 100644 172_factorial_trailing_zeros/zeroes.c diff --git a/169_majority_element/Makefile b/169_majority_element/Makefile new file mode 100644 index 0000000..9741c71 --- /dev/null +++ b/169_majority_element/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test majority.c diff --git a/169_majority_element/majority.c b/169_majority_element/majority.c new file mode 100644 index 0000000..53aee52 --- /dev/null +++ b/169_majority_element/majority.c @@ -0,0 +1,37 @@ +#include +#include + +static int majorityElement(int* nums, int numsSize) +{ + int i, count = 1; + int major = nums[0]; + for (i = 1; i < numsSize; i++) { + if (count == 0) { + major = nums[i]; + count++; + } else if (major == nums[i]) { + count++; + } else { + count--; + } + } + + return major; +} + +int main(int argc, char **argv) +{ + if (argc < 2) { + fprintf(stderr, "Usage: ./test target n1 n2...\n"); + exit(-1); + } + + int i, count = argc - 1; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 1]); + } + + printf("%d\n", majorityElement(nums, count)); + return 0; +} diff --git a/172_factorial_trailing_zeros/Makefile b/172_factorial_trailing_zeros/Makefile new file mode 100644 index 0000000..24a32d9 --- /dev/null +++ b/172_factorial_trailing_zeros/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test zeroes.c diff --git a/172_factorial_trailing_zeros/zeroes.c b/172_factorial_trailing_zeros/zeroes.c new file mode 100644 index 0000000..cc75bff --- /dev/null +++ b/172_factorial_trailing_zeros/zeroes.c @@ -0,0 +1,18 @@ +#include +#include + +static int trailingZeroes(int n) +{ + return n == 0 ? 0 : trailingZeroes(n / 5); +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test n\n"); + exit(-1); + } + + printf("%d\n", trailingZeroes(atoi(argv[1]))); + return 0; +} From 6721671ab412420441124c1a82fa6476c935357b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 21 Nov 2017 09:46:50 +0800 Subject: [PATCH 009/211] Compare version number Signed-off-by: begeekmyfriend --- 165_compare_version_numbers/Makefile | 2 ++ 165_compare_version_numbers/version.c | 50 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 165_compare_version_numbers/Makefile create mode 100644 165_compare_version_numbers/version.c diff --git a/165_compare_version_numbers/Makefile b/165_compare_version_numbers/Makefile new file mode 100644 index 0000000..a373113 --- /dev/null +++ b/165_compare_version_numbers/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test version.c diff --git a/165_compare_version_numbers/version.c b/165_compare_version_numbers/version.c new file mode 100644 index 0000000..803fe8a --- /dev/null +++ b/165_compare_version_numbers/version.c @@ -0,0 +1,50 @@ +#include +#include + +static int compareVersioin(char *v1, char *v2) +{ + int ret = 0; + while (*v1 != '\0' || *v2 != '\0') { + while (*v1 != '\0' && *v1 == '0') { + v1++; + } + while (*v2 != '\0' && *v2 == '0') { + v2++; + } + + int n1 = 0; + while (*v1 != '\0' && *v1 != '.') { + n1 = n1 * 10 + (*v1 - '0'); + v1++; + } + + int n2 = 0; + while (*v2 != '\0' && *v2 != '.') { + n2 = n2 * 10 + (*v2 - '0'); + v2++; + } + + ret = n1 - n2; + if (ret != 0) { + return ret > 0 ? 1 : -1; + } + + if (*v1 == '.') { + v1++; + } + if (*v2 == '.') { + v2++; + } + } + return ret; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test versioin1 version2\n"); + exit(-1); + } + printf("%d\n", compareVersioin(argv[1], argv[2])); + return 0; +} From 75bb89c60679142d090405d0830bc8e74d0cfafe Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 22 Nov 2017 11:04:29 +0800 Subject: [PATCH 010/211] Binary search tree iterator Signed-off-by: begeekmyfriend --- 173_binary_search_tree_iterator/Makefile | 2 + 173_binary_search_tree_iterator/bst_iter.c | 134 +++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 173_binary_search_tree_iterator/Makefile create mode 100644 173_binary_search_tree_iterator/bst_iter.c diff --git a/173_binary_search_tree_iterator/Makefile b/173_binary_search_tree_iterator/Makefile new file mode 100644 index 0000000..9a51897 --- /dev/null +++ b/173_binary_search_tree_iterator/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test bst_iter.c diff --git a/173_binary_search_tree_iterator/bst_iter.c b/173_binary_search_tree_iterator/bst_iter.c new file mode 100644 index 0000000..bfe2955 --- /dev/null +++ b/173_binary_search_tree_iterator/bst_iter.c @@ -0,0 +1,134 @@ +#include +#include +#include + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +struct ListNode { + int val; + struct ListNode *next; +}; + +struct BSTIterator { + struct ListNode dummy; + struct ListNode *p; +}; + +static void bst_iter_generater(struct TreeNode *node, struct BSTIterator *iter) +{ + if (node->left != NULL) { + bst_iter_generater(node->left, iter); + } + + struct ListNode *new = malloc(sizeof(*new)); + new->val = node->val; + new->next = NULL; + if (iter->p != NULL) { + iter->p->next = new; + } else { + iter->dummy.next = new; + } + iter->p = new; + + if (node->right != NULL) { + bst_iter_generater(node->right, iter); + } +} + +static struct BSTIterator *bstIteratorCreate(struct TreeNode *root) +{ + struct BSTIterator *iter = malloc(sizeof(*iter)); + if (root != NULL) { + iter->p = NULL; + bst_iter_generater(root, iter); + } + iter->p = &iter->dummy; + return iter; +} + +/** @return whether we have a next smallest number */ +static bool bstIteratorHasNext(struct BSTIterator *iter) +{ + return iter->p->next != NULL; +} + +/** @return the next smallest number */ +static int bstIteratorNext(struct BSTIterator *iter) +{ + iter->p = iter->p->next; + return iter->p->val; +} + +/** Deallocates memory iteriously allocated for the iterator */ +static void bstIteratorFree(struct BSTIterator *iter) +{ + iter->p = iter->dummy.next; + while (iter->p != NULL) { + iter->dummy.next = iter->p->next; + free(iter->p); + iter->p = iter->dummy.next; + } +} + +int main(void) +{ +#if 1 + struct TreeNode root; + root.val = 7; + + struct TreeNode node1[2]; + node1[0].val = 3; + node1[1].val = 15; + + struct TreeNode node2[4]; + node2[2].val = 9; + node2[3].val = 20; + + root.left = &node1[0]; + root.right = &node1[1]; + + node1[0].left = NULL; + node1[0].right = NULL; + node1[1].left = &node2[2]; + node1[1].right = &node2[3]; +#else + struct TreeNode root; + root.val = 1; + + struct TreeNode node1[2]; + node1[0].val = 2; + node1[1].val = 3; + + struct TreeNode node2[4]; + node2[0].val = 4; + node2[3].val = 5; + + root.left = &node1[0]; + root.right = &node1[1]; + + node1[0].left = &node2[0]; + node1[0].right = NULL; + node1[1].left = NULL; + node1[1].right = &node2[3]; +#endif + + node2[0].left = NULL; + node2[0].right = NULL; + node2[1].left = NULL; + node2[1].right = NULL; + node2[2].left = NULL; + node2[2].right = NULL; + node2[3].left = NULL; + node2[3].right = NULL; + + struct BSTIterator *i = bstIteratorCreate(&root); + while (bstIteratorHasNext(i)) { + printf("%d\n", bstIteratorNext(i)); + } + bstIteratorFree(i); + return 0; +} From f6ce20de6342585523acf33cf80a1c2336e694a1 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 23 Nov 2017 11:34:04 +0800 Subject: [PATCH 011/211] Fraction to recurring decimal Signed-off-by: begeekmyfriend --- .../valid_parentheses.c | 22 +- 166_fraction_to_recurring_decimal/Makefile | 2 + 166_fraction_to_recurring_decimal/fraction.c | 194 ++++++++++++++++++ 3 files changed, 210 insertions(+), 8 deletions(-) create mode 100644 166_fraction_to_recurring_decimal/Makefile create mode 100644 166_fraction_to_recurring_decimal/fraction.c diff --git a/032_longest_valid_parentheses/valid_parentheses.c b/032_longest_valid_parentheses/valid_parentheses.c index 525c186..4f381e8 100644 --- a/032_longest_valid_parentheses/valid_parentheses.c +++ b/032_longest_valid_parentheses/valid_parentheses.c @@ -1,43 +1,49 @@ #include #include -static int longestValidParentheses(char* s) { +static int longestValidParentheses(char* s) +{ int cap = 1, error = -1; int length = 0, max_length = 0; char *p = s; int *stack = malloc(cap * sizeof(int)); int *top = stack; - while (*s != '\0') { - if (*s == '(') { + while (*p != '\0') { + if (*p == '(') { if (top + 1 - stack >= cap) { cap *= 2; stack = realloc(stack, cap * sizeof(int)); } - *top++ = s - p; + *top++ = p - s; } else { if (top > stack) { if (--top == stack) { /* The stack never keep ')' so we use 'error' to record index */ - length = s - p - error; + length = p - (s + error); } else { /* The *(top - 1) is the index of the last kept '(' */ - length = s - p - *(top - 1); + length = p - (s + *(top - 1)); } if (length > max_length) { max_length = length; } } else { - error = s - p; + error = p - s; } } - s++; + p++; } return max_length; } int main(int argc, char **argv) { + if (argc != 2) { + fprintf(stderr, "Usage: ./test parathesis\n"); + exit(-1); + } + printf("%d\n", longestValidParentheses(argv[1])); return 0; } diff --git a/166_fraction_to_recurring_decimal/Makefile b/166_fraction_to_recurring_decimal/Makefile new file mode 100644 index 0000000..75c36fa --- /dev/null +++ b/166_fraction_to_recurring_decimal/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test fraction.c diff --git a/166_fraction_to_recurring_decimal/fraction.c b/166_fraction_to_recurring_decimal/fraction.c new file mode 100644 index 0000000..fbb1db5 --- /dev/null +++ b/166_fraction_to_recurring_decimal/fraction.c @@ -0,0 +1,194 @@ +#include +#include +#include +#include + +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + +#define hlist_for_each_safe(pos, n, head) \ + for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) + +struct hlist_node; + +struct hlist_head { + struct hlist_node *first; +}; + +struct hlist_node { + struct hlist_node *next, **pprev; +}; + +static inline void INIT_HLIST_HEAD(struct hlist_head *h) +{ + h->first = NULL; +} + +static inline int hlist_empty(struct hlist_head *h) +{ + return !h->first; +} + +static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +{ + if (h->first != NULL) { + h->first->pprev = &n->next; + } + n->next = h->first; + n->pprev = &h->first; + h->first = n; +} + +static inline void hlist_del(struct hlist_node *n) +{ + struct hlist_node *next = n->next; + struct hlist_node **pprev = n->pprev; + *pprev = next; + if (next != NULL) { + next->pprev = pprev; + } +} + +struct rem_node { + struct hlist_node node; + int key; + int index; +}; + +static int find(struct hlist_head *heads, int size, int key) +{ + int hash = key % size; + struct hlist_node *pos; + hlist_for_each(pos, &heads[hash]) { + struct rem_node *node = list_entry(pos, struct rem_node, node); + if (key == node->key) { + return node->index; + } + } + return -1; +} + +static char* fractionToDecimal(int numerator, int denominator) +{ + int size = 1024; + char *result = malloc(size); + char *p = result; + + if (denominator == 0) { + result[0] = '\0'; + return result; + } + + if (numerator == 0) { + result[0] = '0'; + result[1] = '\0'; + return result; + } + + /* using long long type make sure there has no integer overflow */ + long long n = numerator; + long long d = denominator; + + /* deal with negtive cases */ + if (n < 0) { + n = -n; + } + if (d < 0) { + d = -d; + } + + bool sign = (float) numerator / denominator >= 0; + if (!sign){ + *p++ = '-'; + } + + long long remainder = n % d; + long long division = n / d; + + sprintf(p, "%ld", division > 0 ? (long) division : (long) -division); + if (remainder == 0) { + return result; + } + + p = result + strlen(result); + *p++ = '.'; + + /* Using a map to record all of reminders and their position. + * if the reminder appeared before, which means the repeated loop begin, + */ + + int i, j; + char *decimal = malloc(size); + memset(decimal, 0, size); + char *q = decimal; + + size = 1333; + struct hlist_head *heads = malloc(size * sizeof(*heads)); + for (i = 0; i < size; i++) { + INIT_HLIST_HEAD(&heads[i]); + } + + i = 0; + while (remainder != 0) { + int pos = find(heads, size, remainder); + if (pos >= 0) { + while (pos-- > 0) { + *p++ = *decimal++; + } + *p++ = '('; + while (*decimal != '\0') { + *p++ = *decimal++; + } + *p++ = ')'; + *p = '\0'; + return result; + } + struct rem_node *node = malloc(sizeof(*node)); + node->key = remainder; + node->index = i; + + int hash = remainder % size; + hlist_add_head(&node->node, &heads[hash]); + + *q++ = (remainder * 10) / d + '0'; + remainder = (remainder * 10) % d; + i++; + } + + strcpy(p, decimal); + return result; +} + +int main(int argc, char** argv) +{ +#if 1 + if (argc != 3) { + fprintf(stderr, "Usage: ./test numerator denominator\n"); + exit(-1); + } + + printf("%s\n", fractionToDecimal(atoi(argv[1]), atoi(argv[2]))); +#else + printf("%s\n", fractionToDecimal(1, 6)); + printf("%s\n", fractionToDecimal(100, 6)); + printf("%s\n", fractionToDecimal(-1, 4)); + printf("%s\n", fractionToDecimal(1, -3)); + printf("%s\n", fractionToDecimal(-1, -6)); + printf("%s\n", fractionToDecimal(25, 99)); + printf("%s\n", fractionToDecimal(1, 7)); + printf("%s\n", fractionToDecimal(10, 7)); + printf("%s\n", fractionToDecimal(100, 7)); + printf("%s\n", fractionToDecimal(1, 17)); + printf("%s\n", fractionToDecimal(1, 1024)); + printf("%s\n", fractionToDecimal(-2147483648, -1999)); + printf("%s\n", fractionToDecimal(-1, -2147483648)); + +#endif + return 0; +} From bede715c344769916a07b287f1584399147b0290 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 24 Nov 2017 09:58:38 +0800 Subject: [PATCH 012/211] Dungeon game Signed-off-by: begeekmyfriend --- 174_dungeon_game/Makefile | 2 ++ 174_dungeon_game/dungeon.c | 63 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 174_dungeon_game/Makefile create mode 100644 174_dungeon_game/dungeon.c diff --git a/174_dungeon_game/Makefile b/174_dungeon_game/Makefile new file mode 100644 index 0000000..d36477a --- /dev/null +++ b/174_dungeon_game/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test dungeon.c diff --git a/174_dungeon_game/dungeon.c b/174_dungeon_game/dungeon.c new file mode 100644 index 0000000..9e78f73 --- /dev/null +++ b/174_dungeon_game/dungeon.c @@ -0,0 +1,63 @@ +#include +#include +#include + +static int calculateMinimumHP(int** dungeon, int dungeonRowSize, int dungeonColSize) +{ + int i, j; + int **dp = malloc(dungeonRowSize * sizeof(int *)); + for (i = 0; i < dungeonRowSize; i++) { + dp[i] = malloc(dungeonColSize * sizeof(int)); + } + + for (i = dungeonRowSize - 1; i >= 0; i--) { + for (j = dungeonColSize - 1; j >= 0; j--) { + if (i == dungeonRowSize - 1 && j == dungeonColSize - 1) { + dp[i][j] = 1 - dungeon[i][j] > 1 ? 1 - dungeon[i][j] : 1; + } else { + int hp1 = i == dungeonRowSize - 1 ? INT_MAX : (dp[i + 1][j] - dungeon[i][j] > 1 ? dp[i + 1][j] - dungeon[i][j] : 1); + int hp2 = j == dungeonColSize - 1 ? INT_MAX : (dp[i][j + 1] - dungeon[i][j] > 1 ? dp[i][j + 1] - dungeon[i][j] : 1); + dp[i][j] = hp1 < hp2 ? hp1 : hp2; + } + } + } + + return dp[0][0]; +} + +int main(void) +{ + int row_size = 3, col_size = 3; + int i, j, **dungeon = malloc(row_size * sizeof(int *)); + for (i = 0; i < row_size; i++) { + dungeon[i] = malloc(col_size * sizeof(int)); + } +#if 1 + dungeon[0][0] = 1; + dungeon[0][1] = -3; + dungeon[0][2] = 3; + dungeon[1][0] = 0; + dungeon[1][1] = -2; + dungeon[1][2] = 0; + dungeon[2][0] = -3; + dungeon[2][1] = -3; + dungeon[2][2] = -3; +#else + dungeon[0][0] = 3; + dungeon[0][1] = -20; + dungeon[0][2] = 30; + dungeon[1][0] = -3; + dungeon[1][1] = 4; + dungeon[1][2] = 0; +#endif + + printf("dungeon:\n"); + for (i = 0; i < row_size; i++) { + for (j = 0; j < col_size; j++) { + printf("%d ", dungeon[i][j]); + } + printf("\n"); + } + printf("%d\n", calculateMinimumHP(dungeon, row_size, col_size)); + return 0; +} From 55ba51b987ce381ee83b65660dc6faecaf5b8ed1 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sat, 25 Nov 2017 07:59:16 +0800 Subject: [PATCH 013/211] Rotate array Signed-off-by: Leo Ma --- 189_rotate_array/Makefile | 2 ++ 189_rotate_array/rotate_array.c | 49 +++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 189_rotate_array/Makefile create mode 100644 189_rotate_array/rotate_array.c diff --git a/189_rotate_array/Makefile b/189_rotate_array/Makefile new file mode 100644 index 0000000..8a313f9 --- /dev/null +++ b/189_rotate_array/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test rotate_array.c diff --git a/189_rotate_array/rotate_array.c b/189_rotate_array/rotate_array.c new file mode 100644 index 0000000..354763c --- /dev/null +++ b/189_rotate_array/rotate_array.c @@ -0,0 +1,49 @@ +#include +#include + +static void reverse(int *nums, int lo, int hi) +{ + while (lo < hi) { + int tmp = nums[lo]; + nums[lo] = nums[hi]; + nums[hi] = tmp; + lo++; + hi--; + } +} + +static void rotate(int* nums, int numsSize, int k) +{ + k %= numsSize; + if (k == 0) { + return; + } + + reverse(nums, 0, numsSize - 1 - k); + reverse(nums, numsSize - k, numsSize - 1); + reverse(nums, 0, numsSize - 1); +} + +int main(int argc, char **argv) +{ + if (argc < 2) { + fprintf(stderr, "Usage: ./test k n1 n2...\n"); + exit(-1); + } + + int k = atoi(argv[1]); + int i, count = argc - 2; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 2]); + } + + rotate(nums, count, k); + + for (i = 0; i < count; i++) { + printf("%d ", nums[i]); + } + printf("\n"); + + return 0; +} From 621e77cb5978189f0a218d79b5f1c419618716a2 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 26 Nov 2017 08:10:40 +0800 Subject: [PATCH 014/211] Number of one bits Signed-off-by: Leo Ma --- 190_reverse_bits/Makefile | 2 ++ 190_reverse_bits/reverse_bits.c | 26 +++++++++++++++++++++++++ 191_number_of_one_bits/Makefile | 2 ++ 191_number_of_one_bits/hamming_weight.c | 24 +++++++++++++++++++++++ 4 files changed, 54 insertions(+) create mode 100644 190_reverse_bits/Makefile create mode 100644 190_reverse_bits/reverse_bits.c create mode 100644 191_number_of_one_bits/Makefile create mode 100644 191_number_of_one_bits/hamming_weight.c diff --git a/190_reverse_bits/Makefile b/190_reverse_bits/Makefile new file mode 100644 index 0000000..d693eb9 --- /dev/null +++ b/190_reverse_bits/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test reverse_bits.c diff --git a/190_reverse_bits/reverse_bits.c b/190_reverse_bits/reverse_bits.c new file mode 100644 index 0000000..5fcf123 --- /dev/null +++ b/190_reverse_bits/reverse_bits.c @@ -0,0 +1,26 @@ +#include +#include +#include + +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; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test n\n"); + exit(-1); + } + + printf("%u\n", reverseBits(atoi(argv[1]))); + return 0; +} diff --git a/191_number_of_one_bits/Makefile b/191_number_of_one_bits/Makefile new file mode 100644 index 0000000..c73d03b --- /dev/null +++ b/191_number_of_one_bits/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test hamming_weight.c diff --git a/191_number_of_one_bits/hamming_weight.c b/191_number_of_one_bits/hamming_weight.c new file mode 100644 index 0000000..ec9a517 --- /dev/null +++ b/191_number_of_one_bits/hamming_weight.c @@ -0,0 +1,24 @@ +#include +#include +#include + +static int hammingWeight(uint32_t n) +{ + int count = 0; + while (n > 0) { + n = n & (n - 1); + count++; + } + return count; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test n\n"); + exit(-1); + } + + printf("%d\n", hammingWeight(atoi(argv[1]))); + return 0; +} From 76bb9cbadf7609bcb2fe8f97b55090c0246eb4cf Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 27 Nov 2017 15:26:50 +0800 Subject: [PATCH 015/211] Implement trie Signed-off-by: begeekmyfriend --- 208_implement_trie/Makefile | 2 + 208_implement_trie/trie.c | 92 +++++++++++++++++++++++++++++ 211_add_and_search_word/Makefile | 2 + 211_add_and_search_word/word_dict.c | 89 ++++++++++++++++++++++++++++ 4 files changed, 185 insertions(+) create mode 100644 208_implement_trie/Makefile create mode 100644 208_implement_trie/trie.c create mode 100644 211_add_and_search_word/Makefile create mode 100644 211_add_and_search_word/word_dict.c diff --git a/208_implement_trie/Makefile b/208_implement_trie/Makefile new file mode 100644 index 0000000..45a3810 --- /dev/null +++ b/208_implement_trie/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test trie.c diff --git a/208_implement_trie/trie.c b/208_implement_trie/trie.c new file mode 100644 index 0000000..8a1a312 --- /dev/null +++ b/208_implement_trie/trie.c @@ -0,0 +1,92 @@ +#include +#include +#include +#include + +typedef struct Trie { + struct Trie *subs[27]; + char letters[27]; +} Trie; + +/** Initialize your data structure here. */ +static Trie* trieCreate() +{ + Trie *obj = malloc(sizeof(*obj)); + memset(obj->letters, 0xff, sizeof(obj->letters)); + memset(&obj->subs[0], 0, sizeof(obj->subs)); + return obj; +} + +/** Inserts a word into the trie. */ +static void trieInsert(Trie* obj, char* word) +{ + while (*word != '\0') { + int pos = *word - 'a' + 1; + obj->letters[pos] = *word++; + if (obj->subs[pos] == NULL) { + obj->subs[pos] = trieCreate(); + } + obj = obj->subs[pos]; + } + obj->letters[0] = '\0'; +} + +/** Returns if the word is in the trie. */ +static bool trieSearch(Trie* obj, char* word) +{ + while (obj != NULL) { + int pos = *word == '\0' ? 0 : *word - 'a' + 1; + if (obj->letters[pos] != *word) { + return false; + } + word++; + obj = obj->subs[pos]; + } + return true; +} + +/** Returns if there is any word in the trie that starts with the given prefix. */ +static bool trieStartsWith(Trie* obj, char* prefix) +{ + while (*prefix != '\0') { + int pos = *prefix - 'a' + 1; + if (pos < 0 || obj->letters[pos] != *prefix) { + return false; + } + if (*++prefix != '\0') { + if (obj->subs[pos] == NULL) { + return false; + } + obj = obj->subs[pos]; + } + } + return true; +} + +static void trieFree(Trie* obj) +{ + int i; + for (i = 0; i < sizeof(obj->letters); i++) { + if (obj->subs[i] != NULL) { + trieFree(obj->subs[i]); + } + } + free(obj); +} + +int main(void) +{ + char *word1 = "abc"; + char *word2 = "ab"; + + Trie* obj = trieCreate(); + trieInsert(obj, word1); + printf("%s\n", trieSearch(obj, word1) ? "true" : "false"); + printf("%s\n", trieSearch(obj, word2) ? "true" : "false"); + trieInsert(obj, word2); + printf("%s\n", trieSearch(obj, word2) ? "true" : "false"); + trieInsert(obj, word2); + printf("%s\n", trieStartsWith(obj, word2) ? "true" : "false"); + trieFree(obj); + return 0; +} diff --git a/211_add_and_search_word/Makefile b/211_add_and_search_word/Makefile new file mode 100644 index 0000000..d5b19d5 --- /dev/null +++ b/211_add_and_search_word/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test word_dict.c diff --git a/211_add_and_search_word/word_dict.c b/211_add_and_search_word/word_dict.c new file mode 100644 index 0000000..d989901 --- /dev/null +++ b/211_add_and_search_word/word_dict.c @@ -0,0 +1,89 @@ +#include +#include +#include +#include + +typedef struct WordDictionary { + struct WordDictionary *subs[27]; + char letters[27]; +} WordDictionary; + +/** Initialize your data structure here. */ +static WordDictionary* wordDictionaryCreate() +{ + WordDictionary *obj = malloc(sizeof(*obj)); + memset(obj->letters, 0xff, sizeof(obj->letters)); + memset(&obj->subs[0], 0, sizeof(obj->subs)); + return obj; +} + +/** Inserts a word into the wordDictionary. */ +static void wordDictionaryInsert(WordDictionary* obj, char* word) +{ + while (*word != '\0') { + int pos = *word - 'a' + 1; + obj->letters[pos] = *word++; + if (obj->subs[pos] == NULL) { + obj->subs[pos] = wordDictionaryCreate(); + } + obj = obj->subs[pos]; + } + obj->letters[0] = '\0'; +} + +/** Returns if the word is in the wordDictionary. */ +static bool wordDictionarySearch(WordDictionary* obj, char* word) +{ + int i; + while (obj != NULL) { + if (*word == '.') { + bool found; + for (i = 1; i < sizeof(obj->letters); i++) { + if (obj->subs[i] != NULL) { + found = wordDictionarySearch(obj->subs[i], word + 1); + if (found) { + return true; + } + } + } + return false; + } else { + int pos = *word == '\0' ? 0 : *word - 'a' + 1; + if (obj->letters[pos] != *word) { + return false; + } + word++; + obj = obj->subs[pos]; + } + } + return true; +} + +static void wordDictionaryFree(WordDictionary* obj) +{ + int i; + for (i = 0; i < sizeof(obj->letters); i++) { + if (obj->subs[i] != NULL) { + wordDictionaryFree(obj->subs[i]); + } + } + free(obj); +} + +int main(void) +{ + char *word1 = "abc"; + char *word2 = "ab"; + char *word3 = "..."; + + WordDictionary* obj = wordDictionaryCreate(); + wordDictionaryInsert(obj, word1); + printf("%s\n", wordDictionarySearch(obj, word1) ? "true" : "false"); + printf("%s\n", wordDictionarySearch(obj, word2) ? "true" : "false"); + wordDictionaryInsert(obj, word2); + printf("%s\n", wordDictionarySearch(obj, word2) ? "true" : "false"); + wordDictionaryInsert(obj, word2); + printf("%s\n", wordDictionarySearch(obj, word3) ? "true" : "false"); + wordDictionaryFree(obj); + return 0; +} From ba25cdcc4e0cfff806d3b67709670ed4b584063e Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 28 Nov 2017 09:44:46 +0800 Subject: [PATCH 016/211] Largest number Signed-off-by: begeekmyfriend --- 179_largest_number/Makefile | 2 + 179_largest_number/largest_number.c | 73 +++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 179_largest_number/Makefile create mode 100644 179_largest_number/largest_number.c diff --git a/179_largest_number/Makefile b/179_largest_number/Makefile new file mode 100644 index 0000000..a78cc73 --- /dev/null +++ b/179_largest_number/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test largest_number.c diff --git a/179_largest_number/largest_number.c b/179_largest_number/largest_number.c new file mode 100644 index 0000000..cdf5bb8 --- /dev/null +++ b/179_largest_number/largest_number.c @@ -0,0 +1,73 @@ +#include +#include +#include + +struct object { + char buf[16]; + int index; +}; + +static int compare(const char *c1, const char *c2) +{ + char p1[32]; + char p2[32]; + p1[0] = '\0'; + p2[1] = '\0'; + strcat(p1, c1); + strcat(p1, c2); + strcat(p2, c2); + strcat(p2, c1); + return strcmp(p1, p2); +} + +static void bubble_sort(struct object *objs, int size) +{ + int i, flag = size; + while (flag) { + int len = flag; + flag = 0; + for (i = 1; i < len; i++) { + if (compare(objs[i].buf, objs[i - 1].buf) > 0) { + struct object tmp = objs[i]; + objs[i] = objs[i - 1]; + objs[i - 1] = tmp; + flag = i; + } + } + } +} + +static char* largestNumber(int* nums, int numsSize) +{ + int i; + struct object *objs = malloc(numsSize * sizeof(*objs)); + memset(objs, 0, sizeof(*objs)); + for (i = 0; i < numsSize; i++) { + objs[i].index = i; + sprintf(objs[i].buf, "%d", nums[i]); + } + + bubble_sort(objs, numsSize); + if (objs[0].buf[0] == '0') { + return "0"; + } + + char *result = malloc(numsSize * 16); + result[0] = '\0'; + for (i = 0; i < numsSize; i++) { + strcat(result, objs[i].buf); + } + + return result; +} + +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]); + } + printf("%s\n", largestNumber(nums, count)); + return 0; +} From 2ca5464d9c090d080357fc68966a386084664df5 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Wed, 29 Nov 2017 09:28:44 +0800 Subject: [PATCH 017/211] Best time to buy and sell stock Signed-off-by: Leo Ma --- .../Makefile | 2 + .../stock.c | 103 ++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 188_best_time_to_buy_and_sell_stock_iv/Makefile create mode 100644 188_best_time_to_buy_and_sell_stock_iv/stock.c diff --git a/188_best_time_to_buy_and_sell_stock_iv/Makefile b/188_best_time_to_buy_and_sell_stock_iv/Makefile new file mode 100644 index 0000000..c638fbb --- /dev/null +++ b/188_best_time_to_buy_and_sell_stock_iv/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test stock.c diff --git a/188_best_time_to_buy_and_sell_stock_iv/stock.c b/188_best_time_to_buy_and_sell_stock_iv/stock.c new file mode 100644 index 0000000..625ce78 --- /dev/null +++ b/188_best_time_to_buy_and_sell_stock_iv/stock.c @@ -0,0 +1,103 @@ +#include +#include +#include + +static inline int max(int a, int b) +{ + return a > b ? a : b; +} + +static int maxProfit(int k, int* prices, int pricesSize) +{ + if (pricesSize == 0) { + return 0; + } + + int i, j; + if (k > pricesSize / 2) { + /* We can make transactions as many as we can */ + int total = 0; + for (i = 1; i < pricesSize; i++) { + if (prices[i] > prices[i - 1]) { + total += prices[i] - prices[i - 1]; + } + } + return total; + } else { +#if 1 + /* DP solution - O(kn) complexity + * dp[i, j] = max (dp[i, j-1], // same times transactions, but one days before. + * dp[i-1, t] + prices[j] - prices[t+1]) // for all of (0 <= t < j ) + * // this means find max profit from previous any of days + */ + int **dp = malloc((k + 1) * sizeof(int *)); + for (i = 0; i <= k; i++) { + dp[i] = malloc((pricesSize + 1) * sizeof(int)); + memset(dp[i], 0, (pricesSize + 1) * sizeof(int)); + } + + for (i = 1; i <= k; i++) { +//printf("i:%d\n", i); +//printf("\tprev_profit = %d - %d\n", dp[i - 1][0], prices[0]); + int prev_profit = dp[i - 1][0] - prices[0]; + for (j = 1; j <= pricesSize; j++) { +//printf("\tj:%d\n", j); + dp[i][j] = max(dp[i][j - 1], prev_profit + prices[j - 1]); /* prices[j - 1] means sell on Day j for dp[i][j] */ +//printf("\tdp[%d][%d] = max(%d, %d + %d)\n", i, j, dp[i][j - 1], prev_profit, prices[j - 1]); + if (j < pricesSize) { +//printf("\tprev_profit = max(%d, %d - %d)\n", prev_profit, dp[i - 1][j], prices[j]); + prev_profit = max(prev_profit, dp[i - 1][j] - prices[j]); + } + } + } +#if 0 + printf(" "); + for (i = 0; i < pricesSize; i++) { + printf("%d ", prices[i]); + } + printf("\n"); + for (i = 0; i <= k; i++) { + for (j = 0; j <= pricesSize; j++) { + printf("%d ", dp[i][j]); + } + printf("\n"); + } +#endif + + return dp[k][pricesSize]; +#else + /* local[i][j] j transactions at most and the last max profix until Day i */ + int *local = malloc((k + 1) * sizeof(int)); + /* global[i][j] j transactions at most until Day i */ + int *global = malloc((k + 1) * sizeof(int)); + memset(local, 0, (k + 1) * sizeof(int)); + memset(global, 0, (k + 1) * sizeof(int)); + for (i = 0; i < pricesSize - 1; i++) { + int diff = prices[i + 1] - prices[i]; + for (j = k; j >= 1; j--) { + int tmp1 = global[j - 1] + (diff > 0 ? diff : 0); + int tmp2 = local[j] + diff; + local[j] = tmp1 > tmp2 ? tmp1 : tmp2; + global[j] = global[j] > local[j] ? global[j] : local[j]; + } + } + return global[k]; +#endif + } +} + +int main(int argc, char **argv) +{ + if (argc < 2) { + fprintf(stderr, "Usage: ./test k n1 n2...\n"); + exit(-1); + } + + int i, count = argc - 2; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 2]); + } + printf("%d\n", maxProfit(atoi(argv[1]), nums, count)); + return 0; +} From 33a7380f44e5031780b36bd59db6e45b417f27a6 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Thu, 30 Nov 2017 10:29:18 +0800 Subject: [PATCH 018/211] Binary tree right side view Signed-off-by: Leo Ma --- 199_binary_tree_right_side_view/Makefile | 2 + 199_binary_tree_right_side_view/bst_right.c | 194 ++++++++++++++++++++ 2 files changed, 196 insertions(+) create mode 100644 199_binary_tree_right_side_view/Makefile create mode 100644 199_binary_tree_right_side_view/bst_right.c diff --git a/199_binary_tree_right_side_view/Makefile b/199_binary_tree_right_side_view/Makefile new file mode 100644 index 0000000..0304665 --- /dev/null +++ b/199_binary_tree_right_side_view/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test bst_right.c diff --git a/199_binary_tree_right_side_view/bst_right.c b/199_binary_tree_right_side_view/bst_right.c new file mode 100644 index 0000000..9956c90 --- /dev/null +++ b/199_binary_tree_right_side_view/bst_right.c @@ -0,0 +1,194 @@ +#include +#include +#include + +#define BST_MAX_LEVEL 800 + +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) +#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) + +#define list_for_each(p, head) \ + for (p = (head)->prev; p != (head); p = p->prev) + +#define list_for_each_safe(p, n, head) \ + for (p = (head)->prev, n = p->prev; p != (head); p = n, n = p->prev) + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +struct list_head { + struct list_head *next, *prev; +}; + +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list->prev = list; +} + +static inline int list_empty(const struct list_head *head) +{ + return (head->next == head); +} + +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +static inline void list_add(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head, head->next); +} + +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} + +static inline void __list_del(struct list_head *entry) +{ + entry->next->prev = entry->prev; + entry->prev->next = entry->next; +} + +static inline void list_del(struct list_head *entry) +{ + __list_del(entry); + entry->next = entry->prev = NULL; +} + +struct bfs_node { + struct TreeNode *node; + struct list_head link; +}; + +static struct bfs_node *node_new(struct list_head *free_list, struct TreeNode *node) +{ + struct bfs_node *new; + if (list_empty(free_list)) { + new = malloc(sizeof(*new)); + } else { + new = list_first_entry(free_list, struct bfs_node, link); + list_del(&new->link); + } + new->node = node; + return new; +} + +static void queue(struct list_head *parents, struct list_head *children, + struct list_head *free_list, int *results, int *count) +{ + struct list_head *p, *n; + list_for_each(p, parents) { + struct bfs_node *new; + struct bfs_node *parent = list_entry(p, struct bfs_node, link); + if (parent->node->right != NULL) { + new = node_new(free_list, parent->node->right); + list_add(&new->link, children); + } + if (parent->node->left != NULL) { + new = node_new(free_list, parent->node->left); + list_add(&new->link, children); + } + } + + int first = 1; + list_for_each_safe(p, n, parents) { + struct bfs_node *parent = list_entry(p, struct bfs_node, link); + if (first) { + first = 0; + results[(*count)++] = parent->node->val; + } + list_del(p); + list_add(p, free_list); + } +} + +/** + ** Return an array of arrays of size *returnSize. + ** The sizes of the arrays are returned as *columnSizes array. + ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + **/ +static int* rightSideView(struct TreeNode* root, int* returnSize) +{ + if (root == NULL) { + *returnSize = 0; + return NULL; + } + + struct list_head q0; + struct list_head q1; + struct list_head free_list; + INIT_LIST_HEAD(&q0); + INIT_LIST_HEAD(&q1); + INIT_LIST_HEAD(&free_list); + + int level = 0; + *returnSize = 0; + int *results = malloc(BST_MAX_LEVEL * sizeof(int)); + struct bfs_node *new = node_new(&free_list, root); + list_add_tail(&new->link, &q0); + + while (!list_empty(&q0) || !list_empty(&q1)) { + if (level & 0x1) { + queue(&q1, &q0, &free_list, results, returnSize); + } else { + queue(&q0, &q1, &free_list, results, returnSize); + } + level++; + } + + return results; +} + +int main(void) +{ + struct TreeNode root; + root.val = 3; + + struct TreeNode node1[2]; + node1[0].val = 9; + node1[1].val = 20; + + struct TreeNode node2[4]; + node2[2].val = 15; + //node2[3].val = 7; + + root.left = &node1[0]; + root.right = &node1[1]; + + node1[0].left = NULL; + node1[0].right = NULL; + node1[1].left = &node2[2]; + node1[1].right = NULL;//&node2[3]; + + node2[0].left = NULL; + node2[0].right = NULL; + node2[1].left = NULL; + node2[1].right = NULL; + node2[2].left = NULL; + node2[2].right = NULL; + node2[3].left = NULL; + node2[3].right = NULL; + + int i, count = 0; + int *lists = rightSideView(&root, &count); + for (i = 0; i < count; i++) { + printf("%d ", lists[i]); + } + printf("\n"); + + return 0; +} From 7fa2b54f6b3e3d4f2df71d73f0fa4b5ec1bbbd7c Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Fri, 15 Dec 2017 15:59:40 +0800 Subject: [PATCH 019/211] Number of island Signed-off-by: Leo Ma --- 002_add_two_numbers/add_two_numbers.c | 8 +++- 200_number_of_islands/Makefile | 2 + 200_number_of_islands/islands.c | 59 +++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 200_number_of_islands/Makefile create mode 100644 200_number_of_islands/islands.c diff --git a/002_add_two_numbers/add_two_numbers.c b/002_add_two_numbers/add_two_numbers.c index 3c5e2a2..3e7872b 100644 --- a/002_add_two_numbers/add_two_numbers.c +++ b/002_add_two_numbers/add_two_numbers.c @@ -8,7 +8,8 @@ struct ListNode { struct ListNode *next; }; -struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { +static struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) +{ int carry_num = 0; int first = 1; struct ListNode *res = NULL; @@ -90,6 +91,11 @@ static void show(struct ListNode *ln) int main(int argc, char **argv) { + if (argc < 3) { + fprintf(stderr, "Usage: ./test n1 n2\n"); + exit(-1); + } + struct ListNode *l1 = node_build(argv[1]); struct ListNode *l2 = node_build(argv[2]); struct ListNode *res = addTwoNumbers(l1, l2); diff --git a/200_number_of_islands/Makefile b/200_number_of_islands/Makefile new file mode 100644 index 0000000..05ad586 --- /dev/null +++ b/200_number_of_islands/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test islands.c diff --git a/200_number_of_islands/islands.c b/200_number_of_islands/islands.c new file mode 100644 index 0000000..5dbb67d --- /dev/null +++ b/200_number_of_islands/islands.c @@ -0,0 +1,59 @@ +#include +#include +#include + +static void recursive(char** grid, int row_size, int col_size, int row, int col) +{ + grid[row][col] = '0'; + + if (row > 0 && grid[row - 1][col] == '1') { + recursive(grid, row_size, col_size, row - 1, col); + } + + if (row < row_size - 1 && grid[row + 1][col] == '1') { + recursive(grid, row_size, col_size, row + 1, col); + } + + if (col > 0 && grid[row][col - 1] == '1') { + recursive(grid, row_size, col_size, row, col - 1); + } + + if (col < col_size - 1 && grid[row][col + 1] == '1') { + recursive(grid, row_size, col_size, row, col + 1); + } +} + +static int numIslands(char** grid, int gridRowSize, int gridColSize) +{ + int i, j, count = 0; + for (i = 0; i < gridRowSize; i++) { + for (j = 0; j < gridColSize; j++) { + if (grid[i][j] == '1') { + recursive(grid, gridRowSize, gridColSize, i, j); + count++; + } + } + } + + return count; +} + +int main(int argc, char **argv) +{ + if (argc < 2) { + fprintf(stderr, "Usage: ./test 11000 11000 00100 00011\n"); + exit(-1); + } + + int i, j; + int row_size = argc - 1; + int col_size = strlen(argv[1]); + char **grid = malloc(row_size * sizeof(char *)); + for (i = 0; i < row_size; i++) { + grid[i] = malloc(col_size); + memcpy(grid[i], argv[i + 1], col_size); + } + + printf("%d\n", numIslands(grid, row_size, col_size)); + return 0; +} From 409d00bf1ab2aa5e79ad0999f4020fcb60c1a6f4 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Tue, 19 Dec 2017 12:09:17 +0800 Subject: [PATCH 020/211] Improvement Signed-off-by: Leo Ma --- .../rect_in_histogram.c | 34 +++++++++++++------ 169_majority_element/majority.c | 6 ++-- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/084_largest_rectangle_in_histogram/rect_in_histogram.c b/084_largest_rectangle_in_histogram/rect_in_histogram.c index 7036579..de31162 100644 --- a/084_largest_rectangle_in_histogram/rect_in_histogram.c +++ b/084_largest_rectangle_in_histogram/rect_in_histogram.c @@ -3,22 +3,34 @@ static int largestRectangleArea(int* heights, int heightsSize) { - int i, max_area = 0; + int *indexes = malloc(heightsSize * sizeof(int)); + int *left = malloc(heightsSize * sizeof(int)); + int *right = malloc(heightsSize * sizeof(int)); + + int i, pos = 0; for (i = 0; i < heightsSize; i++) { - if (i > 0 && heights[i - 1] == heights[i]) { - continue; - } - int low = i; - int high = i; - while (low - 1 >= 0 && heights[low - 1] >= heights[i]) { - low--; + while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { + pos--; } - while (high + 1 < heightsSize && heights[high + 1] >= heights[i]) { - high++; + left[i] = pos == 0 ? -1 : indexes[pos - 1]; + indexes[pos++] = i; + } + + pos = 0; + for (i = heightsSize - 1; i >= 0; i--) { + while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { + pos--; } - int area = (high - low + 1) * heights[i]; + right[i] = pos == 0 ? heightsSize : indexes[pos - 1]; + indexes[pos++] = i; + } + + int max_area = 0; + for (i = 0; i < heightsSize; i++) { + int area = heights[i] * (right[i] - left[i] - 1); max_area = area > max_area ? area : max_area; } + return max_area; } diff --git a/169_majority_element/majority.c b/169_majority_element/majority.c index 53aee52..95b5014 100644 --- a/169_majority_element/majority.c +++ b/169_majority_element/majority.c @@ -3,9 +3,8 @@ static int majorityElement(int* nums, int numsSize) { - int i, count = 1; - int major = nums[0]; - for (i = 1; i < numsSize; i++) { + int i, major, count = 0; + for (i = 0; i < numsSize; i++) { if (count == 0) { major = nums[i]; count++; @@ -15,7 +14,6 @@ static int majorityElement(int* nums, int numsSize) count--; } } - return major; } From 048ee99dad205d287f83e9658d9698e64cd58447 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Wed, 20 Dec 2017 00:00:04 +0800 Subject: [PATCH 021/211] House robber Signed-off-by: Leo Ma --- 198_house_robber/Makefile | 2 ++ 198_house_robber/robber.c | 37 +++++++++++++++++++++++++++ 213_house_robber_ii/Makefile | 2 ++ 213_house_robber_ii/robber.c | 48 ++++++++++++++++++++++++++++++++++++ 4 files changed, 89 insertions(+) create mode 100644 198_house_robber/Makefile create mode 100644 198_house_robber/robber.c create mode 100644 213_house_robber_ii/Makefile create mode 100644 213_house_robber_ii/robber.c diff --git a/198_house_robber/Makefile b/198_house_robber/Makefile new file mode 100644 index 0000000..b7bb446 --- /dev/null +++ b/198_house_robber/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test robber.c diff --git a/198_house_robber/robber.c b/198_house_robber/robber.c new file mode 100644 index 0000000..b7b0db2 --- /dev/null +++ b/198_house_robber/robber.c @@ -0,0 +1,37 @@ +#include +#include +#include + +static inline int max(int a, int b) +{ + return a > b ? a : b; +} + +static int rob(int* nums, int numsSize) +{ + int i; + int **money = malloc((numsSize + 1) * sizeof(int *)); + for (i = 0; i < numsSize + 1; i++) { + money[i] = malloc(2 * sizeof(int)); + memset(money[i], 0, 2 * sizeof(int)); + } + + for (i = 1; i <= numsSize; i++) { + int cash = nums[i - 1]; + money[i][0] = max(money[i - 1][0], money[i - 1][1]); + money[i][1] = money[i - 1][0] + cash; + } + + return max(money[numsSize][0], money[numsSize][1]); +} + +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]); + } + printf("%d\n", rob(nums, count)); + return 0; +} diff --git a/213_house_robber_ii/Makefile b/213_house_robber_ii/Makefile new file mode 100644 index 0000000..b7bb446 --- /dev/null +++ b/213_house_robber_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test robber.c diff --git a/213_house_robber_ii/robber.c b/213_house_robber_ii/robber.c new file mode 100644 index 0000000..8e95b23 --- /dev/null +++ b/213_house_robber_ii/robber.c @@ -0,0 +1,48 @@ +#include +#include +#include + +static inline int max(int a, int b) +{ + return a > b ? a : b; +} + +static int _rob(int* nums, int numsSize) +{ + int i; + int **money = malloc((numsSize + 1) * sizeof(int *)); + for (i = 0; i < numsSize + 1; i++) { + money[i] = malloc(2 * sizeof(int)); + memset(money[i], 0, 2 * sizeof(int)); + } + + for (i = 1; i <= numsSize; i++) { + int cash = nums[i - 1]; + money[i][0] = max(money[i - 1][0], money[i - 1][1]); + money[i][1] = money[i - 1][0] + cash; + } + + return max(money[numsSize][0], money[numsSize][1]); +} + +static int rob(int* nums, int numsSize) +{ + if (numsSize == 0) { + return 0; + } else if (numsSize == 1) { + return nums[0]; + } else { + return max(_rob(nums + 1, numsSize - 1), _rob(nums, numsSize - 1)); + } +} + +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]); + } + printf("%d\n", rob(nums, count)); + return 0; +} From e29e0fa73a5e3dcc340a1853cea985ab11c32baf Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sat, 23 Dec 2017 22:21:20 +0800 Subject: [PATCH 022/211] Biswise AND number of range Signed-off-by: Leo Ma --- 201_bitwise_and_of_numbers_range/Makefile | 2 ++ 201_bitwise_and_of_numbers_range/and.c | 28 +++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 201_bitwise_and_of_numbers_range/Makefile create mode 100644 201_bitwise_and_of_numbers_range/and.c diff --git a/201_bitwise_and_of_numbers_range/Makefile b/201_bitwise_and_of_numbers_range/Makefile new file mode 100644 index 0000000..cc9cd33 --- /dev/null +++ b/201_bitwise_and_of_numbers_range/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test and.c diff --git a/201_bitwise_and_of_numbers_range/and.c b/201_bitwise_and_of_numbers_range/and.c new file mode 100644 index 0000000..4cf2a8c --- /dev/null +++ b/201_bitwise_and_of_numbers_range/and.c @@ -0,0 +1,28 @@ +#include +#include + +static int rangeBitwiseAnd(int m, int n) +{ + int i, res = 0; + for (i = 0; m > 0 && n > 0; i++) { + if (m == n && (m & 1)) { + res |= 1 << i; + } + + m = m >> 1; + n = n >> 1; + } + + return res; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test m n\n"); + exit(-1); + } + + printf("%d\n", rangeBitwiseAnd(atoi(argv[1]), atoi(argv[2]))); + return 0; +} From fa6daefb971836d0d67dd0b7f7cdae134bc001b6 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 25 Dec 2017 17:58:43 +0800 Subject: [PATCH 023/211] Shortest palindrome Signed-off-by: begeekmyfriend --- 214_shortest_palindrome/Makefile | 2 + 214_shortest_palindrome/shortest_palindrome.c | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 214_shortest_palindrome/Makefile create mode 100644 214_shortest_palindrome/shortest_palindrome.c diff --git a/214_shortest_palindrome/Makefile b/214_shortest_palindrome/Makefile new file mode 100644 index 0000000..7e3dc1a --- /dev/null +++ b/214_shortest_palindrome/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test shortest_palindrome.c diff --git a/214_shortest_palindrome/shortest_palindrome.c b/214_shortest_palindrome/shortest_palindrome.c new file mode 100644 index 0000000..e754b96 --- /dev/null +++ b/214_shortest_palindrome/shortest_palindrome.c @@ -0,0 +1,50 @@ +#include +#include +#include +#include + +static inline char *rev_cpy(char *dst, char *src, int size) +{ + while (size-- > 0) { + *--dst = *src++; + } + return dst; +} + +static char *shortestPalindrome(char *s) +{ + int i, j, len = strlen(s); + char *result = malloc(2 * len + 2); + + strcpy(result, s); + result[len] = '#'; + rev_cpy(result + 2 * len + 1, s, len); + + int res_len = 2 * len + 1; + int *next = malloc(res_len * sizeof(int)); + memset(next, 0, res_len * sizeof(int)); + for (i = 1; i < res_len; i++) { + int j = next[i - 1]; + while (j > 0 && result[i] != result[j]) { + j = next[j - 1]; + } + j += result[i] == result[j]; + next[i] = j; + } + + memmove(result, result + len + 1, len + 1); + int start = len - next[res_len - 1]; + strcpy(result + start, s); + return result; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test string\n"); + exit(-1); + } + + printf("%s\n", shortestPalindrome(argv[1])); + return 0; +} From af54c0822445b675cf6fa12a063ca54391267581 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 26 Dec 2017 16:57:56 +0800 Subject: [PATCH 024/211] Minimum size subarrya sum Signed-off-by: begeekmyfriend --- 209_minimum_size_subarray_sum/Makefile | 2 ++ 209_minimum_size_subarray_sum/mini_size.c | 43 +++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 209_minimum_size_subarray_sum/Makefile create mode 100644 209_minimum_size_subarray_sum/mini_size.c diff --git a/209_minimum_size_subarray_sum/Makefile b/209_minimum_size_subarray_sum/Makefile new file mode 100644 index 0000000..4584902 --- /dev/null +++ b/209_minimum_size_subarray_sum/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test mini_size.c diff --git a/209_minimum_size_subarray_sum/mini_size.c b/209_minimum_size_subarray_sum/mini_size.c new file mode 100644 index 0000000..7e915b9 --- /dev/null +++ b/209_minimum_size_subarray_sum/mini_size.c @@ -0,0 +1,43 @@ +#include +#include +#include + +static int minSubArrayLen(int s, int* nums, int numsSize) +{ + int i, j, sum = 0, min = INT_MAX; + for (i = 0, j = 0; i < numsSize; i++) { + sum += nums[i]; + if (sum >= s) { + while (j <= i) { + sum -= nums[j++]; + if (sum < s) { + int interv = i - j + 2; + min = interv < min ? interv : min; + if (min == 1) { + return 1; + } + break; + } + } + } + } + + return min == INT_MAX ? 0 : min; +} + +int main(int argc, char **argv) +{ + if (argc < 3) { + fprintf(stderr, "Usage: ./test sum n1 n2...\n"); + exit(-1); + } + + int i, count = argc - 2; + int sum = atoi(argv[1]); + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 2]); + } + printf("%d\n", minSubArrayLen(sum, nums, count)); + return 0; +} From 45a99879d6762237b6f5939d691419e6c0849013 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 27 Dec 2017 18:39:01 +0800 Subject: [PATCH 025/211] Kth largest element in an array Signed-off-by: begeekmyfriend --- 215_kth_largest_element_in_an_array/Makefile | 2 ++ .../kth_elem.c | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 215_kth_largest_element_in_an_array/Makefile create mode 100644 215_kth_largest_element_in_an_array/kth_elem.c diff --git a/215_kth_largest_element_in_an_array/Makefile b/215_kth_largest_element_in_an_array/Makefile new file mode 100644 index 0000000..9d8632c --- /dev/null +++ b/215_kth_largest_element_in_an_array/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test kth_elem.c diff --git a/215_kth_largest_element_in_an_array/kth_elem.c b/215_kth_largest_element_in_an_array/kth_elem.c new file mode 100644 index 0000000..208050f --- /dev/null +++ b/215_kth_largest_element_in_an_array/kth_elem.c @@ -0,0 +1,29 @@ +#include +#include + +static int compare(const void *a, const void *b) +{ + return *(int *) a - *(int *) b; +} + +int findKthLargest(int* nums, int numsSize, int k) { + qsort(nums, numsSize, sizeof(int), compare); + return nums[numsSize - k]; +} + + +int main(int argc, char **argv) +{ + if (argc < 3) { + fprintf(stderr, "Usage: ./test k n1 n2...\n"); + exit(-1); + } + + int i, count = argc - 2; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 2]); + } + printf("%d\n", findKthLargest(nums, count, atoi(argv[1]))); + return 0; +} From 2811c70ee50a5b8e1e1261bb01756c3aff7454ef Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 2 Jan 2018 18:30:31 +0800 Subject: [PATCH 026/211] Improve Signed-off-by: begeekmyfriend --- 001_two_sum/two_sum.c | 45 +++--- .../longest_substring_without_repeat.c | 34 +++-- .../median_of_two_sorted_array.c | 31 ++-- 014_longest_common_prefix/common_prefix.c | 21 +-- 015_three_sum/three_sum.c | 23 ++- 016_three_sum_closest/three_sum_closest.c | 18 +-- 018_four_sum/four_sum.c | 28 ++-- .../remove_end.c | 14 +- 022_generate_paratheses/parentheses.c | 10 +- 023_merge_k_sorted_lists/merge_lists.c | 3 +- 024_swap_nodes_in_pairs/swap_nodes.c | 11 +- 025_reverse_nodes_in_k_group/reverse_nodes.c | 52 ++----- 028_implement_strstr/strstr.c | 4 +- .../concatenation.c | 137 ++++++++++++------ 031_next_permutation/next_permutation.c | 3 +- .../valid_parentheses.c | 2 +- .../rotated_array.c | 3 +- 034_search_for_a_range/range_search.c | 2 +- 039_combination_sum/combination_sum.c | 72 +++------ 040_combination_sum_ii/combination_sum.c | 63 +++----- 041_first_missing_positive/missing_positive.c | 3 +- 043_multiply_strings/multiply_strings.c | 3 +- 045_jump_game_ii/jump_game.c | 35 ++--- 046_permutations/permutations.c | 83 ++++------- 047_permutations_II/Makefile | 2 - 047_permutations_II/permutations_unique.c | 99 ------------- 047_permutations_ii/Makefile | 2 + 047_permutations_ii/permutations.c | 73 ++++++++++ 049_group_anagrams/anagrams.c | 89 ++---------- 050_pow/pow.c | 43 ++---- 30 files changed, 411 insertions(+), 597 deletions(-) delete mode 100644 047_permutations_II/Makefile delete mode 100644 047_permutations_II/permutations_unique.c create mode 100644 047_permutations_ii/Makefile create mode 100644 047_permutations_ii/permutations.c diff --git a/001_two_sum/two_sum.c b/001_two_sum/two_sum.c index 10f1319..82a2770 100644 --- a/001_two_sum/two_sum.c +++ b/001_two_sum/two_sum.c @@ -1,48 +1,39 @@ #include #include -static void bubble_sort(int *nums, int *indexes, int size) +struct object { + int val; + int index; +}; + +static int compare(const void *a, const void *b) { - int i, flag = size; - while (flag > 0) { - int len = flag; - flag = 0; - for (i = 1; i < len; i++) { - if (nums[i] < nums[i - 1]) { - int tmp = nums[i]; - nums[i] = nums[i - 1]; - nums[i - 1] = tmp; - tmp = indexes[i]; - indexes[i] = indexes[i - 1]; - indexes[i - 1] = tmp; - flag = i; - } - } - } + return ((struct object *) a)->val - ((struct object *) b)->val; } static int * twosum(int *nums, int numsSize, int target) { int i, j; - int *indexes = malloc(numsSize * sizeof(int)); + struct object *objs = malloc(numsSize * sizeof(*objs)); for (i = 0; i < numsSize; i++) { - indexes[i] = i; + objs[i].val = nums[i]; + objs[i].index = i; } - bubble_sort(nums, indexes, numsSize); + qsort(objs, numsSize, sizeof(*objs), compare); int count = 0; int *results = malloc(2 * sizeof(int)); i = 0; j = numsSize - 1; while (i < j) { - int diff = target - nums[i]; - if (diff > nums[j]) { - while (++i < j && nums[i] == nums[i - 1]) {} - } else if (diff < nums[j]) { - while (--j > i && nums[j] == nums[j + 1]) {} + int diff = target - objs[i].val; + if (diff > objs[j].val) { + while (++i < j && objs[i].val == objs[i - 1].val) {} + } else if (diff < objs[j].val) { + while (--j > i && objs[j].val == objs[j + 1].val) {} } else { - results[0] = indexes[i]; - results[1] = indexes[j]; + results[0] = objs[i].index; + results[1] = objs[j].index; return results; } } diff --git a/003_longest_substring_without_repeat/longest_substring_without_repeat.c b/003_longest_substring_without_repeat/longest_substring_without_repeat.c index 52284b3..27fc434 100644 --- a/003_longest_substring_without_repeat/longest_substring_without_repeat.c +++ b/003_longest_substring_without_repeat/longest_substring_without_repeat.c @@ -2,32 +2,40 @@ #include #include -static int lengthOfLongestSubstring(char *s) { +static int lengthOfLongestSubstring(char *s) +{ int offset[128]; int max_len = 0; - char *p, *q; int len = 0; + int index = 0; + memset(offset, 0xff, sizeof(offset)); - for (p = s; *p != '\0'; p++) { - for (q = p; *q != '\0'; q++) { - if (offset[*q] == -1) { - offset[*q] = q - s; - if (++len > max_len) { - max_len = len; - } + while (*s != '\0') { + if (offset[*s] == -1) { + len++; + } else { + if (index - offset[*s] > len) { + len++; } else { - len = 0; - p = offset[*q] + s; - memset(offset, 0xff, sizeof(offset)); - break; + len = index - offset[*s]; } } + if (len > max_len) { + max_len = len; + } + offset[*s++] = index++; } + return max_len; } int main(int argc, char **argv) { + if (argc != 2) { + fprintf(stderr, "Usage: ./test string\n"); + exit(-1); + } + printf("%d\n", lengthOfLongestSubstring(argv[1])); return 0; } diff --git a/004_median_of_two_sorted_array/median_of_two_sorted_array.c b/004_median_of_two_sorted_array/median_of_two_sorted_array.c index 4f614a2..05c2998 100644 --- a/004_median_of_two_sorted_array/median_of_two_sorted_array.c +++ b/004_median_of_two_sorted_array/median_of_two_sorted_array.c @@ -1,32 +1,37 @@ #include #include -static double find_kth(int a[], int m, int b[], int n, int k) +static double find_kth(int a[], int alen, int b[], int blen, int k) { - /* Always assume that m is equal or smaller than n */ - if (m > n) { - return find_kth(b, n, a, m, k); + /* Always assume that alen is equal or smaller than blen */ + if (alen > blen) { + return find_kth(b, blen, a, alen, k); } - if (m == 0) { + + if (alen == 0) { return b[k - 1]; } + if (k == 1) { return a[0] < b[0] ? a[0] : b[0]; } /* Divide k into two parts */ - int i = k / 2 < m ? k / 2 : m; - int j = k - i; - if (a[i - 1] < b[j - 1]) { - return find_kth(a + i, m - i, b, n, k - i); - } else if (a[i - 1] > b[j - 1]) { - return find_kth(a, m, b + j, n - j, k - j); + int ia = k / 2 < alen ? k / 2 : alen; + int ib = k - ia; + if (a[ia - 1] < b[ib - 1]) { + /* a[ia - 1] must be ahead of k-th */ + return find_kth(a + ia, alen - ia, b, blen, k - ia); + } else if (a[ia - 1] > b[ib - 1]) { + /* b[ib - 1] must be ahead of k-th */ + return find_kth(a, alen, b + ib, blen - ib, k - ib); } else { - return a[i - 1]; + return a[ia - 1]; } } -double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { +static double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) +{ int half = (nums1Size + nums2Size) / 2; if ((nums1Size + nums2Size) & 0x1) { return find_kth(nums1, nums1Size, nums2, nums2Size, half + 1); diff --git a/014_longest_common_prefix/common_prefix.c b/014_longest_common_prefix/common_prefix.c index aa1c63a..595effd 100644 --- a/014_longest_common_prefix/common_prefix.c +++ b/014_longest_common_prefix/common_prefix.c @@ -4,22 +4,17 @@ static char* longestCommonPrefix(char** strs, int strsSize) { - int i, capacity = 50, count = 0; - char *result = malloc(50); - bool go_on = true; - while (strsSize > 0 && go_on) { - char temp = strs[0][count]; + int i, count = 0; + char *result = malloc(100); + while (strsSize > 0) { + char c = strs[0][count]; for (i = 1; i < strsSize; i++) { - if (temp != strs[i][count]) break; + if (c != strs[i][count]) break; } - if (i == strsSize && temp != '\0') { - if (count + 1 + 1 >= capacity) { - capacity *= 2; - result = realloc(result, capacity + 1); - } - result[count++] = temp; + if (i == strsSize && c != '\0') { + result[count++] = c; } else { - go_on = false; + break; } } result[count++] = '\0'; diff --git a/015_three_sum/three_sum.c b/015_three_sum/three_sum.c index 0962842..4a47c8a 100644 --- a/015_three_sum/three_sum.c +++ b/015_three_sum/three_sum.c @@ -1,16 +1,9 @@ #include #include -static void insert_sort(int *nums, int len) +static int compare(const void *a, const void *b) { - int i, j; - for (i = 1; i < len; i++) { - int tmp = nums[i]; - for (j = i - 1; j >= 0 && nums[j] > tmp; j--) { - nums[j + 1] = nums[j]; - } - nums[j + 1] = tmp; - } + return *(int *) a - *(int *) b; } static void two_sum(int *nums, int low, int high, int target, int **results, int *count) @@ -37,20 +30,22 @@ 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(). **/ -static int** threeSum(int* nums, int numsSize, int* returnSize) { +static int** threeSum(int* nums, int numsSize, int* returnSize) +{ if (numsSize < 3) { return NULL; } - insert_sort(nums, numsSize); - int i, j, count = 0, capacity = 50000; + qsort(nums, numsSize, sizeof(*nums), compare); + + *returnSize = 0; + int i, j, capacity = 50000; int **results = malloc(capacity * sizeof(int *)); for (i = 0; i < numsSize; i++) { if (i == 0 || i > 0 && nums[i] != nums[i - 1]) { - two_sum(nums, i + 1, numsSize - 1, -nums[i], results, &count); + two_sum(nums, i + 1, numsSize - 1, -nums[i], results, returnSize); } } - *returnSize = count; return results; } diff --git a/016_three_sum_closest/three_sum_closest.c b/016_three_sum_closest/three_sum_closest.c index f27f231..ae0eb6c 100644 --- a/016_three_sum_closest/three_sum_closest.c +++ b/016_three_sum_closest/three_sum_closest.c @@ -3,26 +3,20 @@ #include #include -static void insert_sort(int *a, int size) +static int compare(const void *a, const void *b) { - int i, j; - for (i = 1; i < size; i++) { - int tmp = a[i]; - for (j = i - 1; j >= 0 && a[j] > tmp; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = tmp; - } + return *(int *) a - *(int *) b; } -static int threeSumClosest(int* nums, int numsSize, int target) { +static int threeSumClosest(int* nums, int numsSize, int target) +{ int i, min_diff = INT_MAX; if (numsSize < 3) { return min_diff; } - insert_sort(nums, numsSize); + qsort(nums, numsSize, sizeof(*nums), compare); for (i = 0; i < numsSize - 2; i++) { int left = i + 1; @@ -37,7 +31,7 @@ static int threeSumClosest(int* nums, int numsSize, int target) { } else if (diff > 0) { right--; } else { - break; + return target; } } } diff --git a/018_four_sum/four_sum.c b/018_four_sum/four_sum.c index ec72733..f3032e1 100644 --- a/018_four_sum/four_sum.c +++ b/018_four_sum/four_sum.c @@ -2,20 +2,13 @@ #include #include -static void insert_sort(int *nums, int len) +static int compare(const void *a, const void *b) { - int i, j; - for (i = 1; i < len; i++) { - int tmp = nums[i]; - for (j = i - 1; j >= 0 && nums[j] > tmp; j--) { - nums[j + 1] = nums[j]; - } - nums[j + 1] = tmp; - } + 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) +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 i; if (k == 2) { @@ -51,16 +44,19 @@ static void k_sum(int *nums, int low, int high, int target, int total, int k, ** Return an array of arrays of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ -static int** fourSum(int* nums, int numsSize, int target, int* returnSize) { +static int** fourSum(int* nums, int numsSize, int target, int* returnSize) +{ if (numsSize < 4) { return NULL; } - insert_sort(nums, numsSize); - int i, j, count = 0, capacity = 50000; + + qsort(nums, numsSize, sizeof(*nums), compare); + + *returnSize = 0; + int i, j, capacity = 50000; int **results = malloc(capacity * sizeof(int *)); int *stack = malloc(4 * sizeof(int)); - k_sum(nums, 0, numsSize - 1, target, 4, 4, stack, 0, results, &count); - *returnSize = count; + k_sum(nums, 0, numsSize - 1, target, 4, 4, stack, 0, results, returnSize); return results; } diff --git a/019_remove_nth_node_from_end_of_list/remove_end.c b/019_remove_nth_node_from_end_of_list/remove_end.c index 4c96721..ce0743d 100644 --- a/019_remove_nth_node_from_end_of_list/remove_end.c +++ b/019_remove_nth_node_from_end_of_list/remove_end.c @@ -1,15 +1,16 @@ #include #include - struct ListNode { - int val; - struct ListNode *next; - }; +struct ListNode { + int val; + struct ListNode *next; +}; -struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { - struct ListNode *p, *prev, dummy; +static struct ListNode* removeNthFromEnd(struct ListNode* head, int n) +{ if (n < 1) return NULL; + struct ListNode *p, *prev, dummy; dummy.next = head; p = prev = &dummy; while (n-- > 0) { @@ -26,7 +27,6 @@ struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { if (tmp == head) { head = tmp->next; } - free(tmp); return head; } diff --git a/022_generate_paratheses/parentheses.c b/022_generate_paratheses/parentheses.c index f9103ed..2f95228 100644 --- a/022_generate_paratheses/parentheses.c +++ b/022_generate_paratheses/parentheses.c @@ -6,8 +6,9 @@ ** Return an array of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ -char** generateParenthesis(int n, int* returnSize) { - int left, right, cap = 1, count = 0; +static char** generateParenthesis(int n, int* returnSize) +{ + int left, right, cap = 5000, count = 0; char *stack = malloc(2 * n + 1); char **parentheses = malloc(cap * sizeof(char *)); @@ -18,11 +19,6 @@ char** generateParenthesis(int n, int* returnSize) { /* begin and end condition of loop */ while (p != stack || count == 0) { if (left == n && right == n) { - /* new stacks */ - if (count + 1 >= cap) { - cap *= 2; - parentheses = realloc(parentheses, cap * sizeof(char *)); - } parentheses[count] = malloc(2 * n + 1); strcpy(parentheses[count], stack); count++; diff --git a/023_merge_k_sorted_lists/merge_lists.c b/023_merge_k_sorted_lists/merge_lists.c index 8c81669..58a099e 100644 --- a/023_merge_k_sorted_lists/merge_lists.c +++ b/023_merge_k_sorted_lists/merge_lists.c @@ -7,7 +7,8 @@ struct ListNode { struct ListNode *next; }; -struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) { +static struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) +{ if (listsSize == 0) { return NULL; } diff --git a/024_swap_nodes_in_pairs/swap_nodes.c b/024_swap_nodes_in_pairs/swap_nodes.c index c491b22..b94fa29 100644 --- a/024_swap_nodes_in_pairs/swap_nodes.c +++ b/024_swap_nodes_in_pairs/swap_nodes.c @@ -6,15 +6,16 @@ struct ListNode { struct ListNode *next; }; -static struct ListNode* swapPairs(struct ListNode* head) { - struct ListNode dummy, *p, *prev, *next; +static struct ListNode* swapPairs(struct ListNode* head) +{ if (head == NULL) { return NULL; } + struct ListNode dummy; dummy.next = head; - prev = &dummy; - p = dummy.next; - next = p->next; + struct ListNode *prev = &dummy; + struct ListNode *p = dummy.next; + struct ListNode *next = p->next; while (p != NULL && next != NULL) { prev->next = next; p->next = next->next; diff --git a/025_reverse_nodes_in_k_group/reverse_nodes.c b/025_reverse_nodes_in_k_group/reverse_nodes.c index 680889b..7517559 100644 --- a/025_reverse_nodes_in_k_group/reverse_nodes.c +++ b/025_reverse_nodes_in_k_group/reverse_nodes.c @@ -6,45 +6,25 @@ struct ListNode { struct ListNode *next; }; -static struct ListNode* reverseKGroup(struct ListNode* head, int k) { - if (head == NULL || k <= 1) { - return head; - } - - int first = 1; +static struct ListNode* reverseKGroup(struct ListNode* head, int k) +{ + int i, len = 0; struct ListNode dummy; + struct ListNode *p = head; + struct ListNode *prev = &dummy; dummy.next = head; - struct ListNode *dhead = &dummy; - struct ListNode *prev = head; - struct ListNode *p = head->next; - struct ListNode *next = p == NULL ? NULL : p->next; - while (p != NULL) { - int i; - struct ListNode *end = dhead->next; - for (i = 0; end != NULL && i < k; i++) { - end = end->next; - } - if (i < k) { - break; - } - - while (p != end) { - p->next = dhead->next; - dhead->next = p; - prev->next = next; - p = next; - next = p == NULL ? NULL : p->next; - } - - if (first) { - first = 0; - dummy.next = dhead->next; + for (p = head; p != NULL; p = p->next) { + if (++len % k == 0) { + struct ListNode *begin = prev->next; + for (i = 1; i < k; i++) { + struct ListNode *next = begin->next; + begin->next = next->next; + next->next = prev->next; + prev->next = next; + } + p = begin; + prev = p; } - - dhead = prev; - prev = p; - p = p == NULL ? NULL : p->next; - next = p == NULL ? NULL : p->next; } return dummy.next; } diff --git a/028_implement_strstr/strstr.c b/028_implement_strstr/strstr.c index b314b50..060d915 100644 --- a/028_implement_strstr/strstr.c +++ b/028_implement_strstr/strstr.c @@ -74,7 +74,6 @@ int strStr(char *haystack, char *needle) static int strStr(char *haystack, char *needle) { - int i, j, found = 1; unsigned int hlen = strlen(haystack); unsigned int nlen = strlen(needle); @@ -83,7 +82,9 @@ static int strStr(char *haystack, char *needle) } /* Brute force */ + int i, j; for (i = 0; i < hlen; i++) { + int found = 1; if (haystack[i] == needle[0]) { for (j = 1; j < nlen; j++) { if (i + j < hlen) { @@ -99,7 +100,6 @@ static int strStr(char *haystack, char *needle) return i; } } - found = 1; } return -1; diff --git a/030_substring_with_concatenation_of_all_words/concatenation.c b/030_substring_with_concatenation_of_all_words/concatenation.c index ababaa9..25039b0 100644 --- a/030_substring_with_concatenation_of_all_words/concatenation.c +++ b/030_substring_with_concatenation_of_all_words/concatenation.c @@ -3,14 +3,52 @@ #include #include -struct word_hash { +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + +struct hlist_node; + +struct hlist_head { + struct hlist_node *first; +}; + +struct hlist_node { + struct hlist_node *next, **pprev; +}; + +static inline void INIT_HLIST_HEAD(struct hlist_head *h) { + h->first = NULL; +} + +static inline int hlist_empty(struct hlist_head *h) { + return !h->first; +} + +static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +{ + if (h->first != NULL) { + h->first->pprev = &n->next; + } + n->next = h->first; + n->pprev = &h->first; + h->first = n; +} + +struct word_node { + struct hlist_node node; char *word; - int freq; + int index; }; static inline int BKDRHash(char *s, size_t size) { - int seed = 31; /* 131 1313 13131... */ + int seed = 131; /* 131 1313 13131... */ unsigned long hash = 0; while (*s != '\0') { hash = hash * seed + *s++; @@ -18,27 +56,36 @@ static inline int BKDRHash(char *s, size_t size) return hash % size; } -static int find(char *word, struct word_hash *table, int size) +static int find(char *word, struct hlist_head *heads, int size) { int hash = BKDRHash(word, size); - int i = hash; - do { - if (table[i].freq > 0 && !strcmp(table[i].word, word)) { - return i; + struct hlist_node *pos; + hlist_for_each(pos, &heads[hash]) { + struct word_node *wn = list_entry(pos, struct word_node, node); + if (!strcmp(wn->word, word)) { + return wn->index; } - i = ++i % size; - } while (i != hash); + } return -1; } -static void add(char *word, struct word_hash *table, int size) +static void add(char **words, int index, struct hlist_head *heads, int size, int *freqs) { - int i, hash = BKDRHash(word, size); - for (i = hash; table[i].freq > 0 && strcmp(table[i].word, word); i = ++i % size) {} - if (table[i].freq == 0) { - table[i].word = word; + int hash = BKDRHash(words[index], size); + struct hlist_node *pos; + struct word_node *wn; + hlist_for_each(pos, &heads[hash]) { + wn = list_entry(pos, struct word_node, node); + if (!strcmp(wn->word, words[index])) { + freqs[wn->index]++; + return; } - table[i].freq++; + } + wn = malloc(sizeof(*wn)); + wn->word = words[index]; + wn->index = index; + hlist_add_head(&wn->node, &heads[hash]); + freqs[wn->index]++; } /** @@ -52,45 +99,47 @@ static int *findSubstring(char *s, char **words, int wordsSize, int *returnSize) return NULL; } - int i, j, cap = 500, count = 0; - char *start = s; - struct word_node *wn; - int hash_size = wordsSize * 2; - int len = strlen(words[0]); - char *word = malloc(len + 1); - int *indexes = malloc(cap * sizeof(int)); + int i, j, cap = 10000, count = 0; + int hash_size = wordsSize; + struct hlist_head *heads = malloc(hash_size * sizeof(*heads)); + for (i = 0; i < hash_size; i++) { + INIT_HLIST_HEAD(&heads[i]); + } + int *freqs = malloc(wordsSize * sizeof(int)); - struct word_hash *table = malloc(hash_size * sizeof(*table)); + memset(freqs, 0, wordsSize * sizeof(int)); - memset(table, 0, hash_size * sizeof(*table)); for (i = 0; i < wordsSize; i++) { - add(words[i], table, hash_size); + add(words, i, heads, hash_size, freqs); } - word[len] = '\0'; + int len = strlen(words[0]); int length = len * wordsSize - 1; - while (s[length] != '\0') { - memset(freqs, 0, hash_size * sizeof(int)); - for (i = 0; i < wordsSize; i++) { - memcpy(word, s + i * len, len); - int index = find(word, table, hash_size); - if (index < 0) { + char *word = malloc(len + 1); + word[len] = '\0'; + int *indexes = malloc(cap * sizeof(int)); + for (i = 0; s[i] != '\0'; i++) { + memcpy(word, s + i, len); + indexes[i] = find(word, heads, hash_size); + } + + int *results = malloc(cap * sizeof(int)); + int *fqs = malloc(wordsSize * sizeof(int)); + for (i = 0; s[i + length] != '\0'; i++) { + memset(fqs, 0, wordsSize * sizeof(int)); + for (j = 0; j < wordsSize; j++) { + int index = indexes[i + j * len]; + if (index < 0 || ++fqs[index] > freqs[index]) { break; - } else { - if (++freqs[index] > table[index].freq) { - break; - } } } - - if (i == wordsSize) { - indexes[count++] = s - start; + if (j == wordsSize) { + results[count++] = i; } - s++; } *returnSize = count; - return indexes; + return results; } int main(int argc, char **argv) @@ -101,9 +150,9 @@ int main(int argc, char **argv) } int i, count = 0; - int *indexes = findSubstring(argv[1], argv + 2, argc - 2, &count); + int *results = findSubstring(argv[1], argv + 2, argc - 2, &count); for (i = 0; i < count; i++) { - printf("%d ", indexes[i]); + printf("%d ", results[i]); } printf("\n"); return 0; diff --git a/031_next_permutation/next_permutation.c b/031_next_permutation/next_permutation.c index 19b0afe..c73b768 100644 --- a/031_next_permutation/next_permutation.c +++ b/031_next_permutation/next_permutation.c @@ -14,7 +14,8 @@ static void reverse(int *a, int size) } } -void nextPermutation(int* nums, int numsSize) { +static void nextPermutation(int* nums, int numsSize) +{ if (numsSize <= 1) { return; } diff --git a/032_longest_valid_parentheses/valid_parentheses.c b/032_longest_valid_parentheses/valid_parentheses.c index 4f381e8..f4854d3 100644 --- a/032_longest_valid_parentheses/valid_parentheses.c +++ b/032_longest_valid_parentheses/valid_parentheses.c @@ -3,7 +3,7 @@ static int longestValidParentheses(char* s) { - int cap = 1, error = -1; + int cap = 8000, error = -1; int length = 0, max_length = 0; char *p = s; int *stack = malloc(cap * sizeof(int)); diff --git a/033_search_in_rotated_sorted_array/rotated_array.c b/033_search_in_rotated_sorted_array/rotated_array.c index 84c32ce..b022f7b 100644 --- a/033_search_in_rotated_sorted_array/rotated_array.c +++ b/033_search_in_rotated_sorted_array/rotated_array.c @@ -36,7 +36,8 @@ static int start_find(int *nums, int size) return low; } -static int search(int* nums, int numsSize, int target) { +static int search(int* nums, int numsSize, int target) +{ if (numsSize <= 0) { return -1; } diff --git a/034_search_for_a_range/range_search.c b/034_search_for_a_range/range_search.c index 115c0e1..96b8214 100644 --- a/034_search_for_a_range/range_search.c +++ b/034_search_for_a_range/range_search.c @@ -47,6 +47,7 @@ static int binary_search_end(int *a, int size, int target) **/ int* searchRange(int* nums, int numsSize, int target, int* returnSize) { int *range = malloc(2 * sizeof(int)); + *returnSize = 2; if (numsSize == 0) { range[0] = range[1] = -1; @@ -55,7 +56,6 @@ int* searchRange(int* nums, int numsSize, int target, int* returnSize) { range[0] = binary_search_start(nums, numsSize, target); range[1] = binary_search_end(nums, numsSize, target); - *returnSize = 2; return range; } diff --git a/039_combination_sum/combination_sum.c b/039_combination_sum/combination_sum.c index 2687ff5..d47dcb6 100644 --- a/039_combination_sum/combination_sum.c +++ b/039_combination_sum/combination_sum.c @@ -2,42 +2,23 @@ #include #include -static void insert_sort(int *a, int size) -{ - int i, j; - for (i = 1; i < size; i++) { - int tmp = a[i]; - for (j = i - 1; j >= 0 && tmp < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = tmp; - } -} - -static void combination_recursive(int *nums, int size, int start, int target, - int *solution, int len, - int **results, int *column_sizes, int *count) +static void dfs(int *nums, int size, int start, int target, int *stack, + int len, int **results, int *column_sizes, int *count) { int i; - if (target > 0) { + if (target == 0) { + results[*count] = malloc(len * sizeof(int)); + memcpy(results[*count], stack, len * sizeof(int)); + column_sizes[*count] = len; + (*count)++; + } else if (target > 0) { for (i = start; i < size; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } - /* You may dump the content of the solution here, and you would find - * the order of element represents the number of nested layers, and - * the element at the specific order represents the iteration from - * the start in the current recursive layer. - */ - solution[len++] = nums[i]; - combination_recursive(nums, size, i, target - nums[i], solution, len, results, column_sizes, count); - len--; + stack[len] = nums[i]; + dfs(nums, size, i, target - nums[i], stack, len + 1, results, column_sizes, count); } - } else if (target == 0) { - results[*count] = malloc(len * sizeof(int)); - memcpy(results[*count], solution, len * sizeof(int)); - column_sizes[*count] = len; - (*count)++; } } @@ -46,34 +27,15 @@ static void combination_recursive(int *nums, int size, int start, int target, ** The sizes of the arrays are returned as *columnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -int** combinationSum(int* candidates, int candidatesSize, int target, int** columnSizes, int* returnSize) { - insert_sort(candidates, candidatesSize); - - int *solution = malloc(target * sizeof(int)); - int **results = malloc(100 * sizeof(int *)); - *columnSizes = malloc(100 * sizeof(int)); +static int** combinationSum(int* candidates, int candidatesSize, int target, int** columnSizes, int* returnSize) +{ + int cap = 100; + int *stack = malloc(target * sizeof(int)); + int **results = malloc(cap * sizeof(int *)); + *columnSizes = malloc(cap * sizeof(int)); *returnSize = 0; - combination_recursive(candidates, candidatesSize, 0, target, solution, 0, results, *columnSizes, returnSize); + dfs(candidates, candidatesSize, 0, target, stack, 0, results, *columnSizes, returnSize); return results; - //for (i = 0; i < candidatesSize; i++) { - // //int *columns = malloc(); - // for (j = 1; candidates[i] * j < target, j++) { - // for (k = i + 1; k < candidatesSize; k++) { - // - // } - // int remain = target - candidates[i] * j; - // if (remain == 0) { - // int *column = malloc(sizeof(int)); - // if (count + 1 >= cap) { - // cap *= 2; - // columnSizes = realloc(columnSizes, cap * sizeof(int *)); - // } - // columnSizes[count++] = column; - // } else { - // k = i + 1; - // } - // } - //} } int main(int argc, char **argv) diff --git a/040_combination_sum_ii/combination_sum.c b/040_combination_sum_ii/combination_sum.c index 52f3083..bf62cae 100644 --- a/040_combination_sum_ii/combination_sum.c +++ b/040_combination_sum_ii/combination_sum.c @@ -3,52 +3,29 @@ #include #include -static bool exist(int **results, int count, int *solution, int len) +static int compare(const void *a, const void *b) { - int i; - for (i = 0; i < count; i++) { - if (!memcmp(results[i], solution, len * sizeof(int))) { - return true; - } - } - return false; -} - -static void insert_sort(int *a, int size) -{ - int i, j; - for (i = 1; i < size; i++) { - int tmp = a[i]; - for (j = i - 1; j >= 0 && tmp < a[j]; j--) { - a[j + 1] = a[j]; - } - a[j + 1] = tmp; - } + return *(int *) a - *(int *) b; } -static void combination_recursive(int *nums, int size, int start, int target, - int *solution, int len, - int **results, int *column_sizes, int *count) +static void dfs(int *nums, int size, int start, int target, int *solution, int len, + bool *used, int **results, int *column_sizes, int *count) { int i; - if (target > 0) { + if (target == 0) { + results[*count] = malloc(len * sizeof(int)); + memcpy(results[*count], solution, len * sizeof(int)); + column_sizes[*count] = len; + (*count)++; + } else if (target > 0) { for (i = start; i < size; i++) { - /* You may dump the content of the solution here, and you would find - * the order of element represents the number of nested layers, and - * the element at the specific order represents the iteration from - * the start in the current recursive layer. - */ - solution[len++] = nums[i]; - combination_recursive(nums, size, i + 1, target - nums[i], solution, - len, results, column_sizes, count); - len--; - } - } else if (target == 0) { - if (!exist(results, *count, solution, len)) { - results[*count] = malloc(len * sizeof(int)); - memcpy(results[*count], solution, len * sizeof(int)); - column_sizes[*count] = len; - (*count)++; + if (!used[i]) { + if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) continue; + used[i] = true; + solution[len] = nums[i]; + dfs(nums, size, i + 1, target - nums[i], solution, len + 1, used, results, column_sizes, count); + used[i] = false; + } } } } @@ -60,13 +37,15 @@ static void combination_recursive(int *nums, int size, int start, int target, **/ static int** combinationSum(int* candidates, int candidatesSize, int target, int** columnSizes, int* returnSize) { - insert_sort(candidates, candidatesSize); + qsort(candidates, candidatesSize, sizeof(int), compare); int *solution = malloc(target * sizeof(int)); int **results = malloc(100 * sizeof(int *)); + bool *used = malloc(candidatesSize); + memset(used, false, candidatesSize); *columnSizes = malloc(100 * sizeof(int)); *returnSize = 0; - combination_recursive(candidates, candidatesSize, 0, target, solution, 0, results, *columnSizes, returnSize); + dfs(candidates, candidatesSize, 0, target, solution, 0, used, results, *columnSizes, returnSize); return results; } diff --git a/041_first_missing_positive/missing_positive.c b/041_first_missing_positive/missing_positive.c index 4e23b3f..fc3339b 100644 --- a/041_first_missing_positive/missing_positive.c +++ b/041_first_missing_positive/missing_positive.c @@ -8,7 +8,8 @@ static void swap(int *a, int *b) *b = tmp; } -static int firstMissingPositive(int* nums, int numsSize) { +static int firstMissingPositive(int* nums, int numsSize) +{ if (numsSize < 1) { return 1; } diff --git a/043_multiply_strings/multiply_strings.c b/043_multiply_strings/multiply_strings.c index be32919..469014f 100644 --- a/043_multiply_strings/multiply_strings.c +++ b/043_multiply_strings/multiply_strings.c @@ -15,7 +15,8 @@ static void reverse(char *s, int len) } } -static char* multiply(char* num1, char* num2) { +static char* multiply(char* num1, char* num2) +{ if (*num1 == '\0') { return num1; } diff --git a/045_jump_game_ii/jump_game.c b/045_jump_game_ii/jump_game.c index 53a8128..30a0202 100644 --- a/045_jump_game_ii/jump_game.c +++ b/045_jump_game_ii/jump_game.c @@ -1,28 +1,25 @@ #include #include -static int jump(int* nums, int numsSize) { - if (numsSize <= 1) { - return 0; - } - - int i; - int pos = numsSize - 1; - int *indexes = malloc(numsSize * sizeof(int)); - int *p = indexes; +static inline int max(int a, int b) +{ + return a > b ? a : b; +} - *p++ = numsSize - 1; - while (--pos >= 0) { - for (i = 0; i < p - indexes; i++) { - if (nums[pos] >= indexes[i] - pos) { - indexes[i + 1] = pos; - p = indexes + i + 2; - break; - } +static int jump(int* nums, int numsSize) +{ + int i, lo = 0, hi = 0; + int steps = 0; + while (hi < numsSize - 1) { + int right = 0; + for (i = lo; i <= hi; i++) { + right = max(i + nums[i], right); } + lo = hi + 1; + hi = right; + steps++; } - - return p - indexes - 1; + return steps; } int main(int argc, char **argv) diff --git a/046_permutations/permutations.c b/046_permutations/permutations.c index 7eb4c9e..8ffc9d9 100644 --- a/046_permutations/permutations.c +++ b/046_permutations/permutations.c @@ -1,70 +1,42 @@ #include #include +#include #include -static void reverse(int *a, int size) +static void swap(int *a, int *b) { - int left = 0; - int right = size - 1; - while (left < right) { - int tmp = a[left]; - a[left] = a[right]; - a[right] = tmp; - left++; - right--; - } + int tmp = *a; + *a = *b; + *b = tmp; } -static void next_permute(int* nums, int numsSize) { - if (numsSize <= 1) { - return; - } - - int *p = nums + numsSize - 1; - int *q = nums + numsSize - 1; - - while (p != nums && *(p - 1) >= *p) { - p--; - } - - if (p != nums) { - int n = *(p - 1); - while (*q <= n) { - q--; +static void dfs(int *nums, int size, int start, int **results, int *count) +{ + int i; + if (start == size) { + results[*count] = malloc(size * sizeof(int)); + memcpy(results[*count], nums, size * sizeof(int)); + (*count)++; + } else { + for (i = start; i < size; i++) { + swap(nums + start, nums + i); + dfs(nums, size, start + 1, results, count); + swap(nums + start, nums + i); } - - int tmp = *q; - *q = *(p - 1); - *(p - 1) = tmp; } - reverse(p, numsSize - (p - nums)); } /** ** Return an array of arrays of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ -static int** permute(int* nums, int numsSize, int* returnSize) { - if (numsSize == 0) { - return NULL; - } - - int i, count = 1, size = numsSize; - while (size > 0) { - count *= size--; - } - - int **permutations = malloc(count * sizeof(int *)); - permutations[0] = malloc(numsSize * sizeof(int)); - memcpy(permutations[0], nums, numsSize * sizeof(int)); - for (i = 1; i < count; i++) { - permutations[i] = malloc(numsSize * sizeof(int)); - memcpy(permutations[i], permutations[i - 1], numsSize * sizeof(int)); - next_permute(permutations[i], numsSize); - } - - *returnSize = count; - return permutations; +static int **permute(int* nums, int numsSize, int* returnSize) +{ + int count = 0, cap = 5000; + int **results = malloc(cap * sizeof(int *)); + *returnSize = 0; + dfs(nums, numsSize, 0, results, returnSize); + return results; } int main(int argc, char **argv) @@ -74,14 +46,13 @@ int main(int argc, char **argv) exit(-1); } - int i, j, count; - int *nums = malloc(sizeof(int)); - for (i = 0; i < argc - 1; i++) { + int i, j, count = argc - 1; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { nums[i] = atoi(argv[i + 1]); } int **lists = permute(nums, argc - 1, &count); - for (i = 0; i < count; i++) { for (j = 0; j < argc - 1; j++) { printf("%d", lists[i][j]); diff --git a/047_permutations_II/Makefile b/047_permutations_II/Makefile deleted file mode 100644 index 35f7ea7..0000000 --- a/047_permutations_II/Makefile +++ /dev/null @@ -1,2 +0,0 @@ -all: - gcc -O2 -o test permutations_unique.c diff --git a/047_permutations_II/permutations_unique.c b/047_permutations_II/permutations_unique.c deleted file mode 100644 index e51b695..0000000 --- a/047_permutations_II/permutations_unique.c +++ /dev/null @@ -1,99 +0,0 @@ -#include -#include -#include - -static void reverse(int *a, int size) -{ - int left = 0; - int right = size - 1; - while (left < right) { - int tmp = a[left]; - a[left] = a[right]; - a[right] = tmp; - left++; - right--; - } -} - -static void next_permute(int* nums, int numsSize) { - if (numsSize <= 1) { - return; - } - - int *p = nums + numsSize - 1; - int *q = nums + numsSize - 1; - - while (p != nums && *(p - 1) >= *p) { - p--; - } - - if (p != nums) { - int n = *(p - 1); - while (*q <= n) { - q--; - } - - int tmp = *q; - *q = *(p - 1); - *(p - 1) = tmp; - } - reverse(p, numsSize - (p - nums)); -} - -/** - ** Return an array of arrays of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static int** permute_unique(int* nums, int numsSize, int* returnSize) { - if (numsSize == 0) { - return NULL; - } - - int cap = 1, count = 0, stop = 0; - int **permutations = malloc(cap * sizeof(int *)); - permutations[count] = malloc(numsSize * sizeof(int)); - memcpy(permutations[count], nums, numsSize * sizeof(int)); - count++; - - while (!stop) { - int *permutation = malloc(numsSize * sizeof(int)); - memcpy(permutation, permutations[count - 1], numsSize * sizeof(int)); - next_permute(permutation, numsSize); - if (memcmp(permutation, nums, numsSize * sizeof(int))) { - if (count + 1 >= cap) { - cap *= 2; - permutations = realloc(permutations, cap * sizeof(int *)); - } - permutations[count++] = permutation; - } else { - stop = 1; - } - } - - *returnSize = count; - return permutations; -} - -int main(int argc, char **argv) -{ - if (argc <= 1) { - fprintf(stderr, "Usage: ./test ...\n"); - exit(-1); - } - - int i, j, count; - int *nums = malloc(sizeof(int)); - for (i = 0; i < argc - 1; i++) { - nums[i] = atoi(argv[i + 1]); - } - - int **lists = permute_unique(nums, argc - 1, &count); - for (i = 0; i < count; i++) { - for (j = 0; j < argc - 1; j++) { - printf("%d", lists[i][j]); - } - putchar('\n'); - } - - return 0; -} diff --git a/047_permutations_ii/Makefile b/047_permutations_ii/Makefile new file mode 100644 index 0000000..25f7501 --- /dev/null +++ b/047_permutations_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test permutations.c diff --git a/047_permutations_ii/permutations.c b/047_permutations_ii/permutations.c new file mode 100644 index 0000000..b357ef1 --- /dev/null +++ b/047_permutations_ii/permutations.c @@ -0,0 +1,73 @@ +#include +#include +#include +#include + +static int compare(const void *a, const void *b) +{ + return *(int *) a - *(int *) b; +} + +static void dfs(int *nums, int size, int *stack, int len, + bool *used, int **results, int *count) +{ + int i; + if (len == size) { + results[*count] = malloc(len * sizeof(int)); + memcpy(results[*count], stack, len * sizeof(int)); + (*count)++; + } else { + for (i = 0; i < size; i++) { + if (!used[i]) { + if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; + used[i] = true; + stack[len] = nums[i]; + dfs(nums, size, stack, len + 1, used, results, count); + used[i] = false; + } + } + } +} + +/** + ** Return an array of arrays of size *returnSize. + ** Note: The returned array must be malloced, assume caller calls free(). + **/ +static int **permute(int* nums, int numsSize, int* returnSize) +{ + qsort(nums, numsSize, sizeof(int), compare); + + int count = 0, cap = 10000; + int *stack = malloc(numsSize * sizeof(int)); + int **results = malloc(cap * sizeof(int *)); + bool *used = malloc(numsSize); + memset(used, false, numsSize); + *returnSize = 0; + dfs(nums, numsSize, stack, 0, used, results, returnSize); + return results; +} + +int main(int argc, char **argv) +{ + if (argc <= 1) { + fprintf(stderr, "Usage: ./test ...\n"); + exit(-1); + } + + int i, j, count = argc - 1; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 1]); + printf("%d\n", nums[i]); + } + + int **lists = permute(nums, argc - 1, &count); + for (i = 0; i < count; i++) { + for (j = 0; j < argc - 1; j++) { + printf("%d", lists[i][j]); + } + putchar('\n'); + } + + return 0; +} diff --git a/049_group_anagrams/anagrams.c b/049_group_anagrams/anagrams.c index 7e225e8..710b4d6 100644 --- a/049_group_anagrams/anagrams.c +++ b/049_group_anagrams/anagrams.c @@ -2,65 +2,15 @@ #include #include -struct hlist_node; - -struct hlist_head { - struct hlist_node *first; -}; - -struct hlist_node { - struct hlist_node *next, **pprev; -}; - -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; -} - -static inline int hlist_empty(struct hlist_head *h) { - return !h->first; -} - -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) -{ - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; -} - -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -struct word_node { - struct hlist_node node; - int index; -}; - struct word_hash { - struct hlist_head head; char *word; int num; + int indexes[10]; }; -static void insert_sort(char *s, int len) +static int compare(const void *a, const void *b) { - int i, j; - for (i = 1; i < len; i++) { - char tmp = s[i]; - j = i - 1; - for (; j >= 0 && s[j] > tmp; j--) { - s[j + 1] = s[j]; - } - s[j + 1] = tmp; - } + return *(char *) a - *(char *) b; } static inline int BKDRHash(char *s, size_t size) @@ -78,50 +28,41 @@ static inline int BKDRHash(char *s, size_t size) ** The sizes of the arrays are returned as *columnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -static char*** groupAnagrams(char** strs, int strsSize, int** columnSizes, int* returnSize) { +static char*** groupAnagrams(char** strs, int strsSize, int** columnSizes, int* returnSize) +{ int i, j, count = 0; - struct word_node *wn; - int hash_size = strsSize; - struct word_hash *ht = malloc(hash_size * sizeof(*ht)); - for (i = 0; i < hash_size; i++) { - INIT_HLIST_HEAD(&ht[i].head); - ht[i].num = 0; - } + struct word_hash *ht = calloc(hash_size, sizeof(*ht)); char **words = malloc(strsSize * sizeof(char *)); for (i = 0; i < strsSize; i++) { int len = strlen(strs[i]); words[i] = malloc(len + 1); strcpy(words[i], strs[i]); - insert_sort(words[i], len); + qsort(words[i], len, sizeof(char), compare); int hash = BKDRHash(words[i], hash_size); /* find available hash bucket */ for (j = hash; ht[j].num > 0 && strcmp(ht[j].word, words[i]); j = ++j % hash_size) {} - wn = malloc(sizeof(*wn)); - wn->index = i; if (ht[j].num == 0) { ht[j].word = words[i]; count++; } - hlist_add_head(&wn->node, &ht[j].head); - ht[j].num++; + ht[j].indexes[ht[j].num++] = i; } - j = 0; + int k = 0; struct hlist_node *p; char ***lists = malloc(count * sizeof(char **)); *columnSizes = malloc(count * sizeof(int)); for (i = 0; i < hash_size; i++) { if (ht[i].num > 0) { - (*columnSizes)[j] = ht[i].num; - lists[j] = malloc(ht[i].num * sizeof(char *)); - int k = 0; - hlist_for_each(p, &ht[i].head) { - wn = list_entry(p, struct word_node, node); - lists[j][k++] = strs[wn->index]; + (*columnSizes)[k] = ht[i].num; + lists[k] = malloc(ht[i].num * sizeof(char *)); + for (j = 0; j < ht[i].num; j++) { + int index = ht[i].indexes[j]; + lists[k][j] = strs[index]; } - j++; + k++; } } diff --git a/050_pow/pow.c b/050_pow/pow.c index 68c9fa9..515454e 100644 --- a/050_pow/pow.c +++ b/050_pow/pow.c @@ -1,42 +1,17 @@ #include #include -#include -/* - * n == 2(10) -- 2 -- res = 1 * 2^2 - * n == 3(11) -- 2 + 1 -- res = 1 * 2^1 * 2^2 - * n == 4(100) -- 4 -- res = 1 * 2^4 - * n == 5(101) -- 4 + 1 -- res = 1 * 2^1 * 2^4 - * n == 6(110) -- 4 + 2 + 1 -- res = 1 * 2^1 * 2^2 * 2^4 - */ -static double my_pow(double x, int n) +static double fast_pow(double x, int n) { - int orig = x; - int sign = 0; - int one_more = 0; - if (n < 0) { - if (n == INT_MIN) { - n = INT_MAX; - one_more = 1; - } else { - n = -n; - } - sign = 1; - } - - double res = 1; - while (n > 0) { - if (n & 0x1) { - res *= x; - } - x *= x; - n >>= 1; - } - if (one_more) { - res *= orig; - } + if (n == 0) { return 1.0; } + if (n == 1) { return x; } + double t = fast_pow(x, n / 2); + return n & 1 ? t * t * x : t * t; +} - return sign ? 1 / res : res; +static double my_pow(double x, int n) +{ + return n < 0 ? 1 / fast_pow(x, -n) : fast_pow(x, n); } int main(int argc, char **argv) From 934b7b7639682217dde2051ece6ee6f525f39e35 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 3 Jan 2018 16:54:26 +0800 Subject: [PATCH 027/211] Improve Signed-off-by: begeekmyfriend --- 053_maximum_subarray/max_subarray.c | 8 +- 054_spiral_matrix/spiral_matrix.c | 4 +- 055_jump_game/jump_game.c | 26 +++---- .../permutation_sequence.c | 55 ++++--------- 062_unique_path/unique_path.c | 31 +------- 064_minumum_path_sum/minimum_path_sum.c | 13 ++-- 065_valid_number/valid_number.c | 77 +++++++------------ 071_simplify_path/simplify_path.c | 3 +- 072_edit_distance/edit_distance.c | 45 ++--------- 073_set_matrix_zeroes/set_zero.c | 3 +- 075_sort_colors/sort_colors.c | 5 +- 077_combinations/combinations.c | 8 +- 078_subsets/subsets.c | 15 ++-- 079_word_search/word_search.c | 13 ++-- .../rm_dups.c | 31 +++++--- .../search_rotated_array.c | 16 ++-- .../rect_in_histogram.c | 2 + 085_maximal_rectangle/maximal_rectangle.c | 68 ++++++++++------ 086_partition_list/partition_list.c | 1 + 090_subsets_ii/subsets.c | 66 ++++++---------- 091_decode_ways/decode_ways.c | 68 +++++----------- 093_restore_ip_addresses/ip_addr.c | 9 ++- .../bst_inorder_traversal.c | 9 ++- .../unique_bst.c | 8 +- 096_unique_binary_search_trees/unique_bst.c | 2 +- 097_interleaving_string/interleaving_string.c | 5 ++ 098_validate_binary_search_tree/valid_bst.c | 35 +++------ 099_recover_binary_search_tree/recover_bst.c | 50 ++++++------ 100_same_tree/same_tree.c | 8 +- 29 files changed, 277 insertions(+), 407 deletions(-) diff --git a/053_maximum_subarray/max_subarray.c b/053_maximum_subarray/max_subarray.c index fe4b3ba..6a0bbb4 100644 --- a/053_maximum_subarray/max_subarray.c +++ b/053_maximum_subarray/max_subarray.c @@ -2,15 +2,15 @@ #include #include -static int recursive(int *nums, int lo, int hi) +static int partition(int *nums, int lo, int hi) { if (lo == hi) { return nums[lo]; } int ce = (hi - lo) / 2; - int left_max = recursive(nums, lo, lo + ce); - int right_max = recursive(nums, hi - ce, hi); + int left_max = partition(nums, lo, lo + ce); + int right_max = partition(nums, hi - ce, hi); int i; int left_border = 0, left_border_max = INT_MIN; @@ -48,7 +48,7 @@ static int maxSubArray(int* nums, int numsSize) } return max; #else - return recursive(nums, 0, numsSize - 1); + return partition(nums, 0, numsSize - 1); #endif } diff --git a/054_spiral_matrix/spiral_matrix.c b/054_spiral_matrix/spiral_matrix.c index 65e8ed1..54114ea 100644 --- a/054_spiral_matrix/spiral_matrix.c +++ b/054_spiral_matrix/spiral_matrix.c @@ -60,9 +60,9 @@ int main(int argc, char **argv) mat[i] = malloc(col * sizeof(int)); for (j = 0; j < col; j++) { mat[i][j] = ++count; -printf("%d ", mat[i][j]); + printf("%d ", mat[i][j]); } -printf("\n"); + printf("\n"); } int *nums = spiralOrder(mat, row, col); for (i = 0; i < row * col; i++) { diff --git a/055_jump_game/jump_game.c b/055_jump_game/jump_game.c index 8d4e5b0..a768dc4 100644 --- a/055_jump_game/jump_game.c +++ b/055_jump_game/jump_game.c @@ -2,24 +2,22 @@ #include #include -static bool canJump(int* nums, int numsSize) { - if (numsSize == 0) return false; +static inline int max(int a, int b) +{ + return a > b ? a : b; +} - int i = numsSize - 1, j; - while (i > 0) { - if (nums[--i] == 0) { - for (j = i - 1; j >= 0; j--) { - if (nums[j] > i - j) { - break; - } - } - if (j == -1) { - return false; - } +static bool canJump(int* nums, int numsSize) +{ + int i, pos = 0; + for (i = 0; i < numsSize - 1; i++) { + if (pos < i || pos >= numsSize - 1) { + break; } + pos = max(i + nums[i], pos); } - return true; + return pos >= numsSize - 1; } int main(int argc, char **argv) diff --git a/060_permutation_sequence/permutation_sequence.c b/060_permutation_sequence/permutation_sequence.c index 983b1a7..9e63960 100644 --- a/060_permutation_sequence/permutation_sequence.c +++ b/060_permutation_sequence/permutation_sequence.c @@ -2,59 +2,34 @@ #include #include -static void reverse(int *a, int size) +static int factorial(int n) { - int left = 0; - int right = size - 1; - while (left < right) { - int tmp = a[left]; - a[left] = a[right]; - a[right] = tmp; - left++; - right--; + if (n == 0) { + return 0; + } else if (n == 1) { + return 1; + } else { + return n * factorial(n - 1); } } -void nextPermutation(int* nums, int numsSize) { - if (numsSize <= 1) { - return; - } - - int *p = nums + numsSize - 1; - int *q = nums + numsSize - 1; - - while (p != nums && *(p - 1) >= *p) { - p--; - } - - if (p != nums) { - int n = *(p - 1); - while (*q <= n) { - q--; - } - - int tmp = *q; - *q = *(p - 1); - *(p - 1) = tmp; - } - reverse(p, numsSize - (p - nums)); -} - -static char* getPermutation(int n, int k) { +static char* getPermutation(int n, int k) +{ int i; int *permutation = malloc(n * sizeof(int)); for (i = 0; i < n; i++) { permutation[i] = i + 1; } - while (--k > 0) { - nextPermutation(permutation, n); - } + char *result = malloc(n + 1); for (i = 0; i < n; i++) { - result[i] = permutation[i] + '0'; + int fac = factorial(n - i - 1); + int j = k > 1 ? (k - 1) / fac : 0; + result[i] = permutation[j] + '0'; + k -= j * fac; + memmove(permutation + j, permutation + j + 1, (n - j) * sizeof(int)); } result[n] = '\0'; - free(permutation); return result; } diff --git a/062_unique_path/unique_path.c b/062_unique_path/unique_path.c index b7dd848..2a1a184 100644 --- a/062_unique_path/unique_path.c +++ b/062_unique_path/unique_path.c @@ -1,33 +1,8 @@ #include #include -static void valid_path_recursive(int col, int m, int row, int n, int *count) +static int uniquePaths(int m, int n) { - if (col == m - 1 && row == n - 1) { - (*count)++; - } else { - if (m > n) { - if (col < m - 1) { - valid_path(col + 1, m, row, n, count); - } - if (row < n - 1) { - valid_path(col, m, row + 1, n, count); - } - } else { - if (col < m - 1) { - valid_path(col + 1, m, row, n, count); - } - if (row < n - 1) { - valid_path(col, m, row + 1, n, count); - } - } - } -} - -static int uniquePaths(int m, int n) { - //int count = 0; - //valid_path(0, m, 0, n, &count); - //return count; int row, col; int *grids = malloc(m * n * sizeof(int)); for (col = 0; col < m; col++) { @@ -41,9 +16,7 @@ static int uniquePaths(int m, int n) { grids[row * m + col] = grids[row * m + col - 1] + grids[(row - 1) * m + col]; } } - int result = grids[m * n - 1]; - free(grids); - return result; + return grids[m * n - 1]; } int main(int argc, char **argv) diff --git a/064_minumum_path_sum/minimum_path_sum.c b/064_minumum_path_sum/minimum_path_sum.c index 33777ae..ad807c5 100644 --- a/064_minumum_path_sum/minimum_path_sum.c +++ b/064_minumum_path_sum/minimum_path_sum.c @@ -1,9 +1,14 @@ #include #include #include -#include -int minPathSum(int** grid, int gridRowSize, int gridColSize) { +static inline int min(int a, int b) +{ + return a < b ? a : b; +} + +int minPathSum(int** grid, int gridRowSize, int gridColSize) +{ int i, j; int **dp = malloc(gridRowSize * sizeof(int *)); for (i = 0; i < gridRowSize; i++) { @@ -23,11 +28,9 @@ int minPathSum(int** grid, int gridRowSize, int gridColSize) { dp[0][i] = sum; } - int min = INT_MAX; for (i = 1; i < gridRowSize; i++) { for (j = 1; j < gridColSize; j++) { - int n = dp[i - 1][j] < dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1]; - dp[i][j] = n + grid[i][j]; + dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]); } } diff --git a/065_valid_number/valid_number.c b/065_valid_number/valid_number.c index 36a0c5e..76af82a 100644 --- a/065_valid_number/valid_number.c +++ b/065_valid_number/valid_number.c @@ -1,57 +1,38 @@ #include #include #include +#include -static bool isNumber(const char *s) { - bool point = false; - bool hasE = false; - - //trim the space - while(isspace(*s)) s++; - //check empty - if (*s == '\0' ) return false; - //check sign - if (*s=='+' || *s=='-') s++; - - const char *head = s; - for(; *s!='\0'; s++){ - // if meet point - if ( *s == '.' ){ - if ( hasE == true || point == true){ - return false; - } - if ( s == head && !isdigit(*(s+1)) ){ - return false; - } - point = true; - continue; - } - //if meet "e" - if ( *s == 'e' ){ - if ( hasE == true || s == head) { - return false; - } - s++; - if ( *s=='+' || *s=='-' ) s++; - if ( !isdigit(*s) ) return false; - - hasE = true; - continue; - } - //if meet space, check the rest chars are space or not - if (isspace(*s)){ - for (; *s != '\0'; s++){ - if (!isspace(*s)) return false; - } - return true; - } - if ( !isdigit(*s) ) { - return false; +static bool isNumber(const char *s) +{ + while (*s == ' ') + ++s; + bool if_find_num = false; + if (*s == '-' || *s == '+') + ++s; + while (isdigit(*s)) { + if_find_num = true; + ++s; + } + if (*s == '.') + ++s; + while (isdigit(*s)) { + if_find_num = true; + ++s; + } + if (if_find_num == true && *s == 'e') { + ++s; + if (*s == '+' || *s == '-') + ++s; + if_find_num = false; + while (isdigit(*s)) { + if_find_num = true; + ++s; } - } - - return true; + while (*s == ' ') + ++s; + return *s == '\0' && if_find_num == true; } int main(int argc, char** argv) diff --git a/071_simplify_path/simplify_path.c b/071_simplify_path/simplify_path.c index b56a907..a6ac084 100644 --- a/071_simplify_path/simplify_path.c +++ b/071_simplify_path/simplify_path.c @@ -2,7 +2,8 @@ #include #include -static char* simplifyPath(char* path) { +static char* simplifyPath(char* path) +{ int len = strlen(path); if (len == 0) { return path; diff --git a/072_edit_distance/edit_distance.c b/072_edit_distance/edit_distance.c index c854187..b035609 100644 --- a/072_edit_distance/edit_distance.c +++ b/072_edit_distance/edit_distance.c @@ -4,41 +4,6 @@ #include /* - * Dynamic Programming - * - * Definitaion - * - * m[i][j] is minimal distance from word1[0..i] to word2[0..j] - * - * So, - * - * 1) if word1[i] == word2[j], then m[i][j] == m[i-1][j-1]. - * - * 2) if word1[i] != word2[j], then we need to find which one below is minimal: - * - * min( m[i-1][j-1], m[i-1][j], m[i][j-1] ) - * - * and +1 - current char need be changed. - * - * Let's take a look m[1][2] : "a" => "ab" - * - * +---+ +---+ - * ''=> a | 1 | | 2 | '' => ab - * +---+ +---+ - * - * +---+ +---+ - * a => a | 0 | | 1 | a => ab - * +---+ +---+ - * - * To know the minimal distance `a => ab`, we can get it from one of the following cases: - * - * 1) delete the last char in word1, minDistance( '' => ab ) + 1 - * 2) delete the last char in word2, minDistance( a => a ) + 1 - * 3) change the last char, minDistance( '' => a ) + 1 - * - * - * For Example: - * * word1="abb", word2="abccb" * * 1) Initialize the DP matrix as below: @@ -56,9 +21,13 @@ * a 1 0 1 2 3 4 * b 2 1 0 1 2 3 * b 3 2 1 1 2 2 - * */ +static inline int min(int a, int b) +{ + return a < b ? a : b; +} + static int minDistance(char* word1, char* word2) { int i, j; @@ -82,9 +51,7 @@ static int minDistance(char* word1, char* word2) if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; } else { - int min = dp[i - 1][j] > dp[i][j - 1] ? dp[i][j - 1] : dp[i - 1][j]; - dp[i][j] = min > dp[i - 1][j - 1] ? dp[i - 1][j - 1] : min; - dp[i][j] += 1; + dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])); } } } diff --git a/073_set_matrix_zeroes/set_zero.c b/073_set_matrix_zeroes/set_zero.c index 71e54a7..7be6a54 100644 --- a/073_set_matrix_zeroes/set_zero.c +++ b/073_set_matrix_zeroes/set_zero.c @@ -1,7 +1,8 @@ #include #include -static void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) { +static void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) +{ int row, col, bRow = 0, bCol = 0; for (row = 0; row < matrixRowSize; row++) { for (col = 0; col < matrixColSize; col++) { diff --git a/075_sort_colors/sort_colors.c b/075_sort_colors/sort_colors.c index adfb1a9..d7017ad 100644 --- a/075_sort_colors/sort_colors.c +++ b/075_sort_colors/sort_colors.c @@ -2,7 +2,7 @@ #include #include -static void swap(int *a, int *b) +static inline void swap(int *a, int *b) { int tmp = *a; *a = *b; @@ -14,7 +14,8 @@ static void swap(int *a, int *b) * WHITE = 1 * BLUE = 2 */ -static void sortColors(int* nums, int numsSize) { +static void sortColors(int* nums, int numsSize) +{ int i = 0, j = numsSize - 1; while (i < j) { while (nums[i] == 0 && i < j) { diff --git a/077_combinations/combinations.c b/077_combinations/combinations.c index 47a6b71..cbe320c 100644 --- a/077_combinations/combinations.c +++ b/077_combinations/combinations.c @@ -3,8 +3,8 @@ #include #include -static void recursive(int n, int k, int start, int *stack, int len, bool *used, - int *col_sizes, int **results, int *count) +static void dfs(int n, int k, int start, int *stack, int len, + bool *used, int *col_sizes, int **results, int *count) { int i; if (len == k) { @@ -17,7 +17,7 @@ static void recursive(int n, int k, int start, int *stack, int len, bool *used, if (!used[i]) { stack[len] = i; used[i] = true; - recursive(n, k, i + 1, stack, len + 1, used, col_sizes, results, count); + dfs(n, k, i + 1, stack, len + 1, used, col_sizes, results, count); used[i] = false; } } @@ -37,7 +37,7 @@ int** combine(int n, int k, int** columnSizes, int* returnSize) { bool *used = malloc((n + 1) * sizeof(bool)); memset(used, false, n + 1); *columnSizes = malloc(capacity * sizeof(int)); - recursive(n, k, 1, stack, 0, used, *columnSizes, results, &count); + dfs(n, k, 1, stack, 0, used, *columnSizes, results, &count); *returnSize = count; return results; } diff --git a/078_subsets/subsets.c b/078_subsets/subsets.c index dcdf3ec..6a4d18b 100644 --- a/078_subsets/subsets.c +++ b/078_subsets/subsets.c @@ -2,9 +2,8 @@ #include #include -static void subset_recursive(int *nums, int size, int start, - int *buf, int len, - int **sets, int *sizes, int *count) +static void dfs(int *nums, int size, int start, int *buf, + int len, int **sets, int *sizes, int *count) { int i; sets[*count] = malloc(len * sizeof(int)); @@ -12,9 +11,8 @@ static void subset_recursive(int *nums, int size, int start, sizes[*count] = len; (*count)++; for (i = start; i < size; i++) { - buf[len++] = nums[i]; - subset_recursive(nums, size, i + 1, buf, len, sets, sizes, count); - len--; + buf[len] = nums[i]; + dfs(nums, size, i + 1, buf, len + 1, sets, sizes, count); } } @@ -23,13 +21,14 @@ static void subset_recursive(int *nums, int size, int start, ** The sizes of the arrays are returned as *columnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) { +int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) +{ int capacity = 5000; int **sets = malloc(capacity * sizeof(int *)); int *buf = malloc(numsSize * sizeof(int)); *columnSizes = malloc(capacity * sizeof(int)); *returnSize = 0; - subset_recursive(nums, numsSize, 0, buf, 0, sets, *columnSizes, returnSize); + dfs(nums, numsSize, 0, buf, 0, sets, *columnSizes, returnSize); return sets; } diff --git a/079_word_search/word_search.c b/079_word_search/word_search.c index 54cae5d..c4bf7bd 100644 --- a/079_word_search/word_search.c +++ b/079_word_search/word_search.c @@ -3,7 +3,8 @@ #include #include -static bool recursive(char *word, char **board, bool *used, int row, int col, int row_size, int col_size) +static bool dfs(char *word, char **board, bool *used, + int row, int col, int row_size, int col_size) { if (board[row][col] != *word) { return false; @@ -17,19 +18,19 @@ static bool recursive(char *word, char **board, bool *used, int row, int col, in bool result = false; if (row > 0 && !used[(row - 1) * col_size + col]) { - result = recursive(word + 1, board, used, row - 1, col, row_size, col_size); + result = dfs(word + 1, board, used, row - 1, col, row_size, col_size); } if (!result && row < row_size - 1 && !used[(row + 1) * col_size + col]) { - result = recursive(word + 1, board, used, row + 1, col, row_size, col_size); + result = dfs(word + 1, board, used, row + 1, col, row_size, col_size); } if (!result && col > 0 && !used[row * col_size + col - 1]) { - result = recursive(word + 1, board, used, row, col - 1, row_size, col_size); + result = dfs(word + 1, board, used, row, col - 1, row_size, col_size); } if (!result && col < col_size - 1 && !used[row * col_size + col + 1]) { - result = recursive(word + 1, board, used, row, col + 1, row_size, col_size); + result = dfs(word + 1, board, used, row, col + 1, row_size, col_size); } used[row * col_size + col] = false; @@ -46,7 +47,7 @@ static bool exist(char** board, int boardRowSize, int boardColSize, char* word) for (i = 0; i < boardRowSize; i++) { for (j = 0; j < boardColSize; j++) { memset(used, false, boardRowSize * boardColSize); - if (recursive(word, board, used, i, j, boardRowSize, boardColSize)) { + if (dfs(word, board, used, i, j, boardRowSize, boardColSize)) { return true; } } diff --git a/080_remove_duplicates_from_sorted_array_ii/rm_dups.c b/080_remove_duplicates_from_sorted_array_ii/rm_dups.c index 6156057..bc529ce 100644 --- a/080_remove_duplicates_from_sorted_array_ii/rm_dups.c +++ b/080_remove_duplicates_from_sorted_array_ii/rm_dups.c @@ -1,21 +1,28 @@ #include #include -int removeDuplicates(int* nums, int numsSize) { - int i = 0, j, x, y, count = 0; - while (i < numsSize) { - for (j = i + 1; j < numsSize && nums[i] == nums[j]; j++) {} - int diff = j - i; - if (diff > 2) { - for (x = i + 2, y = j; y < numsSize; x++, y++) { - nums[x] = nums[y]; +static int removeDuplicates(int* nums, int numsSize) +{ + if (numsSize == 0) { + return 0; + } + + int i; + int len = 0; + int count = 0; + for (i = 1; i < numsSize; i++) { + if (nums[len] == nums[i]) { + if (count < 2) { + count++; + nums[++len] = nums[i]; } - numsSize -= diff - 2; + } else { + count = 1; + nums[++len] = nums[i]; } - count += diff > 2 ? 2 : diff; - i += diff > 2 ? 2 : diff; } - return count; + + return len + 1; } int main(int argc, char **argv) diff --git a/081_search_in_rotated_sorted_array_ii/search_rotated_array.c b/081_search_in_rotated_sorted_array_ii/search_rotated_array.c index b5ba3b5..a271eff 100644 --- a/081_search_in_rotated_sorted_array_ii/search_rotated_array.c +++ b/081_search_in_rotated_sorted_array_ii/search_rotated_array.c @@ -1,5 +1,6 @@ #include #include +#include static int binary_search(int *nums, int size, int target) { @@ -20,12 +21,14 @@ static int binary_search(int *nums, int size, int target) } } -static int search(int* nums, int numsSize, int target) { +static bool search(int* nums, int numsSize, int target) +{ if (numsSize <= 0) { - return -1; + return false; } + if (numsSize == 1) { - return target == nums[0] ? 0 : -1; + return target == nums[0]; } int i; @@ -36,12 +39,11 @@ static int search(int* nums, int numsSize, int target) { } if (i == 0) { - return binary_search(nums, numsSize, target); + return binary_search(nums, numsSize, target) >= 0; } else if (target >= nums[0]) { - return binary_search(nums, i, target); + return binary_search(nums, i, target) >= 0; } else if (target <= nums[numsSize - 1]) { - int index = binary_search(nums + i, numsSize - i, target); - return index >= 0 ? index + i : -1; + return binary_search(nums + i, numsSize - i, target) >= 0; } else { return -1; } diff --git a/084_largest_rectangle_in_histogram/rect_in_histogram.c b/084_largest_rectangle_in_histogram/rect_in_histogram.c index de31162..49116ff 100644 --- a/084_largest_rectangle_in_histogram/rect_in_histogram.c +++ b/084_largest_rectangle_in_histogram/rect_in_histogram.c @@ -9,6 +9,7 @@ static int largestRectangleArea(int* heights, int heightsSize) int i, pos = 0; for (i = 0; i < heightsSize; i++) { + /* monotonous increasing stack */ while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { pos--; } @@ -18,6 +19,7 @@ static int largestRectangleArea(int* heights, int heightsSize) pos = 0; for (i = heightsSize - 1; i >= 0; i--) { + /* monotonous increasing stack */ while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { pos--; } diff --git a/085_maximal_rectangle/maximal_rectangle.c b/085_maximal_rectangle/maximal_rectangle.c index cdca77a..3edadbd 100644 --- a/085_maximal_rectangle/maximal_rectangle.c +++ b/085_maximal_rectangle/maximal_rectangle.c @@ -3,32 +3,56 @@ #include #include -int maximalRectangle(char** matrix, int matrixRowSize, int matrixColSize) { +static inline int max(int a, int b) +{ + return a > b ? a : b; +} + +static int area_calc(int *heights, int size) +{ + int *indexes = malloc(size * sizeof(int)); + int *left = malloc(size * sizeof(int)); + int *right = malloc(size * sizeof(int)); + + int i, pos = 0; + for (i = 0; i < size; i++) { + /* monotonous increasing stack */ + while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { + pos--; + } + left[i] = pos == 0 ? -1 : indexes[pos - 1]; + indexes[pos++] = i; + } + + pos = 0; + for (i = size - 1; i >= 0; i--) { + /* monotonous increasing stack */ + while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { + pos--; + } + right[i] = pos == 0 ? size : indexes[pos - 1]; + indexes[pos++] = i; + } + + int max_area = 0; + for (i = 0; i < size; i++) { + int area = heights[i] * (right[i] - left[i] - 1); + max_area = max(area, max_area); + } + + return max_area; +} + +static int maximalRectangle(char** matrix, int matrixRowSize, 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++) { - if (matrix[i][j] == '1') { - int area = 0, x, y; - int row = i; - int min_col = matrixColSize; - while (row < matrixRowSize) { - for (x = j; x < matrixColSize && matrix[row][x] == '1'; x++) {} - min_col = x < min_col ? x : min_col; - area = (row - i + 1) * (min_col - j); - max_area = area > max_area ? area : max_area; - row++; - } - int col = j; - int min_row = matrixRowSize; - while (col < matrixColSize) { - for (y = i; y < matrixRowSize && matrix[y][col] == '1'; y++) {} - min_row = y < min_row ? y : min_row; - area = (min_row - i) * (col - j + 1); - max_area = area > max_area ? area : max_area; - col++; - } - } + heights[j] = matrix[i][j] == '1' ? heights[j] + 1 : 0; } + max_area = max(max_area, area_calc(heights, matrixColSize)); } return max_area; } diff --git a/086_partition_list/partition_list.c b/086_partition_list/partition_list.c index 8f262a9..1dcc37c 100644 --- a/086_partition_list/partition_list.c +++ b/086_partition_list/partition_list.c @@ -12,6 +12,7 @@ struct ListNode* partition(struct ListNode* head, int x) { dummy.next = head; for (pivot = head; pivot != NULL; pivot = pivot->next) { if (pivot->val >= x) { + /* start->next == pivot */ break; } start = pivot; diff --git a/090_subsets_ii/subsets.c b/090_subsets_ii/subsets.c index c33fe19..09a38f3 100644 --- a/090_subsets_ii/subsets.c +++ b/090_subsets_ii/subsets.c @@ -1,53 +1,29 @@ #include #include +#include #include -int *cache1, *cache2; - -static void insert_sort(int *nums, int size) +static inline int compare(const void *a, const void *b) { - int i, j; - for (i = 1; i < size; i++) { - int tmp = nums[i]; - for (j = i - 1; j >= 0 && tmp < nums[j]; j--) { - nums[j + 1] = nums[j]; - } - nums[j + 1] = tmp; - } + return *(int *) a - *(int *) b; } -static int exist(int **results, int count, int *sizes, int *buf, int len) -{ - int i, j; - for (i = 0; i < count; i++) { - if (len == sizes[i]) { - memcpy(cache1, results[i], len * sizeof(int)); - memcpy(cache2, buf, len * sizeof(int)); - insert_sort(cache1, len); - insert_sort(cache2, len); - if (!memcmp(cache1, cache2, len * sizeof(int))) { - return 1; - } - } - } - return 0; -} - -static void subset_recursive(int *nums, int size, int start, - int *buf, int len, - int **sets, int *sizes, int *count) +static void dfs(int *nums, int size, int start, int *buf, int level, + bool *used, int **sets, int *sizes, int *count) { int i; - if (!exist(sets, *count, sizes, buf, len)) { - sets[*count] = malloc(len * sizeof(int)); - memcpy(sets[*count], buf, len * sizeof(int)); - sizes[*count] = len; - (*count)++; - } + sets[*count] = malloc(level * sizeof(int)); + memcpy(sets[*count], buf, level * sizeof(int)); + sizes[*count] = level; + (*count)++; for (i = start; i < size; i++) { - buf[len++] = nums[i]; - subset_recursive(nums, size, i + 1, buf, len, sets, sizes, count); - len--; + if (!used[i]) { + if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) continue; + used[i] = true; + buf[level] = nums[i]; + dfs(nums, size, i + 1, buf, level + 1, used, sets, sizes, count); + used[i] = false; + } } } @@ -56,15 +32,17 @@ static void subset_recursive(int *nums, int size, int start, ** The sizes of the arrays are returned as *columnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) { +static int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) +{ + qsort(nums, numsSize, sizeof(int), compare); int capacity = 5000; int **sets = malloc(capacity * sizeof(int *)); int *buf = malloc(numsSize * sizeof(int)); + bool *used = malloc(numsSize); + memset(used, false, numsSize); *columnSizes = malloc(capacity * sizeof(int)); *returnSize = 0; - cache1 = malloc(numsSize * sizeof(int)); - cache2 = malloc(numsSize * sizeof(int)); - subset_recursive(nums, numsSize, 0, buf, 0, sets, *columnSizes, returnSize); + dfs(nums, numsSize, 0, buf, 0, used, sets, *columnSizes, returnSize); return sets; } diff --git a/091_decode_ways/decode_ways.c b/091_decode_ways/decode_ways.c index 4f374fb..a096361 100644 --- a/091_decode_ways/decode_ways.c +++ b/091_decode_ways/decode_ways.c @@ -2,61 +2,29 @@ #include #include -//static void recursive(char *s, char *stack, int len, char **results, int *count) -//{ -// if (*s == '\0') { -// printf("%s\n", stack); -// results[*count] = malloc(len + 1); -// strcpy(results[*count], stack); -// (*count)++; -// } else { -// //while (*s != '\0') { -// stack[len++] = *s - '0' - 1 + 'A'; -// recursive(s + 1, stack, len, results, count); -// stack[--len] = '\0'; -// if (*(s + 1) != '\0') { -// int value = (*s - '0') * 10 + (*(s + 1) - '0'); -// char c = (value - 1) + 'A'; -// if (c >= 'A' && c <= 'Z') { -// stack[len++] = c; -// recursive(s + 2, stack, len, results, count); -// stack[--len] = '\0'; -// //s++; -// } -// } -// //s++; -// //} -// } -//} +static int numDecodings(char* s) { + int len = strlen(s); + if (len == 0) { + return 0; + } -static void recursive(char *s, int *count) -{ - int value; - char c; - if (*s == '\0') { - (*count)++; - } else { - value = *s - '0'; - c = (value - 1) + 'A'; - if (c >= 'A' && c <= 'Z') { - recursive(s + 1, count); + int dp[len + 1]; + memset(dp, 0, (len + 1) * sizeof(int)); + + dp[0] = 1; + dp[1] = s[0] == '0' ? 0 : 1; + for (int i = 2; i <= len; i++) { + if (s[i - 1] != '0') { + dp[i] = dp[i - 1]; } - if (*(s + 1) != '\0' && *s != '0') { - value = (*s - '0') * 10 + (*(s + 1) - '0'); - c = (value - 1) + 'A'; - if (c >= 'A' && c <= 'Z') { - recursive(s + 2, count); - } + + int num = (s[i - 2] - '0') * 10 + (s[i - 1] - '0'); + if (num >= 10 && num <= 26) { + dp[i] += dp[i - 2]; } } -} -static int numDecodings(char* s) { - int count = 0; - if (*s != '\0' && *s != '0') { - recursive(s, &count); - } - return count; + return dp[len]; } int main(int argc, char **argv) diff --git a/093_restore_ip_addresses/ip_addr.c b/093_restore_ip_addresses/ip_addr.c index 38855ad..8f461a5 100644 --- a/093_restore_ip_addresses/ip_addr.c +++ b/093_restore_ip_addresses/ip_addr.c @@ -19,7 +19,7 @@ static bool valid(char *ip, int len) #define WIDTH 4 -static void recursive(char *s, int start, char *stack, int num, char **results, int *count) +static void dfs(char *s, int start, char *stack, int num, char **results, int *count) { int i, j; if (num == 4) { @@ -45,7 +45,7 @@ static void recursive(char *s, int start, char *stack, int num, char **results, if (!valid(p, q - p)) { return; } - recursive(s, i + 1, stack, num + 1, results, count); + dfs(s, i + 1, stack, num + 1, results, count); if (num + 1 < 4) { memset(stack + (num + 1) * WIDTH, 0, WIDTH); } @@ -57,11 +57,12 @@ static void recursive(char *s, int start, char *stack, int num, char **results, ** Return an array of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ -static char** restoreIpAddresses(char* s, int* returnSize) { +static char** restoreIpAddresses(char* s, int* returnSize) +{ int count = 0; char **results = malloc(100 * sizeof(char *)); char addr[16] = { '\0' }; - recursive(s, 0, addr, 0, results, &count); + dfs(s, 0, addr, 0, results, &count); *returnSize = count; return results; } diff --git a/094_binary_tree_inorder_traversal/bst_inorder_traversal.c b/094_binary_tree_inorder_traversal/bst_inorder_traversal.c index 8730457..ad7253f 100644 --- a/094_binary_tree_inorder_traversal/bst_inorder_traversal.c +++ b/094_binary_tree_inorder_traversal/bst_inorder_traversal.c @@ -22,10 +22,11 @@ static void traverse(struct TreeNode *node, int *result, int *count) } /** - * * Return an array of size *returnSize. - * * Note: The returned array must be malloced, assume caller calls free(). - * */ -int* inorderTraversal(struct TreeNode* root, int* returnSize) { + ** Return an array of size *returnSize. + ** Note: The returned array must be malloced, assume caller calls free(). + **/ +static int* inorderTraversal(struct TreeNode* root, int* returnSize) +{ if (root == NULL) { *returnSize = 0; return NULL; diff --git a/095_unique_binary_search_trees_ii/unique_bst.c b/095_unique_binary_search_trees_ii/unique_bst.c index 0cbf3d1..41f1478 100644 --- a/095_unique_binary_search_trees_ii/unique_bst.c +++ b/095_unique_binary_search_trees_ii/unique_bst.c @@ -52,7 +52,7 @@ struct TreeNode { struct TreeNode *right; }; -static struct TreeNode *sub_tree_generate(int low, int high, int *count) +static struct TreeNode *dfs(int low, int high, int *count) { int i, j, k; if (low > high) { @@ -72,8 +72,8 @@ static struct TreeNode *sub_tree_generate(int low, int high, int *count) for (i = low; i <= high; i++) { /* Possibilities of roots with different values */ int left_cnt, right_cnt; - struct TreeNode *left_subs = sub_tree_generate(low, i - 1, &left_cnt); - struct TreeNode *right_subs = sub_tree_generate(i + 1, high, &right_cnt); + struct TreeNode *left_subs = dfs(low, i - 1, &left_cnt); + struct TreeNode *right_subs = dfs(i + 1, high, &right_cnt); /* Total number = left sub possibilities * right sub possibilities */ if (left_cnt == 0) left_cnt = 1; if (right_cnt == 0) right_cnt = 1; @@ -103,7 +103,7 @@ static struct TreeNode *sub_tree_generate(int low, int high, int *count) static struct TreeNode** generateTrees(int n, int* returnSize) { int i, count = 0; - struct TreeNode *roots = sub_tree_generate(1, n, &count); + struct TreeNode *roots = dfs(1, n, &count); struct TreeNode **results = malloc(count * sizeof(struct TreeNode *)); for (i = 0; i < count; i++) { results[i] = &roots[i]; diff --git a/096_unique_binary_search_trees/unique_bst.c b/096_unique_binary_search_trees/unique_bst.c index 507a64b..913e90a 100644 --- a/096_unique_binary_search_trees/unique_bst.c +++ b/096_unique_binary_search_trees/unique_bst.c @@ -21,7 +21,7 @@ static int numTrees(int n) { int main(int argc, char **argv) { if (argc != 2) { - fprintf(stderr, "Usage: ./test n"); + fprintf(stderr, "Usage: ./test n\n"); exit(-1); } printf("%d\n", numTrees(atoi(argv[1]))); diff --git a/097_interleaving_string/interleaving_string.c b/097_interleaving_string/interleaving_string.c index e274c6a..70e9d96 100644 --- a/097_interleaving_string/interleaving_string.c +++ b/097_interleaving_string/interleaving_string.c @@ -20,6 +20,11 @@ static bool isInterleave(char* s1, char* s2, char* s3) int i, j; int len1 = strlen(s1); int len2 = strlen(s2); + int len3 = strlen(s3); + if (len1 + len2 != len3) { + return false; + } + bool *table = malloc((len1 + 1) * (len2 + 1) * sizeof(bool)); bool **dp = malloc((len1 + 1) * sizeof(bool *)); for (i = 0; i < len1 + 1; i++) { diff --git a/098_validate_binary_search_tree/valid_bst.c b/098_validate_binary_search_tree/valid_bst.c index 3b90ad7..06e972e 100644 --- a/098_validate_binary_search_tree/valid_bst.c +++ b/098_validate_binary_search_tree/valid_bst.c @@ -9,33 +9,18 @@ struct TreeNode { struct TreeNode *right; }; -static bool traverse(struct TreeNode* node, int *last_val) +static bool dfs(struct TreeNode* node, int min, int max) { - bool ret = true; - - if (ret && node->left != NULL) { - ret = traverse(node->left, last_val); - } - - if (node->val <= *last_val) { - return false; - } - *last_val = node->val; - - if (ret && node->right != NULL) { - ret = traverse(node->right, last_val); - } - return ret; + if (node == NULL) return true; + if (node->val < min || node->val > max) return false; + if (node->left != NULL && node->val == INT_MIN) return false; + if (node->right != NULL && node->val == INT_MAX) return false; + return dfs(node->left, min, node->val - 1) && dfs(node->right, node->val + 1, max); } static bool isValidBST(struct TreeNode* root) { - if (root == NULL) { - return true; - } else { - int last_val = -1; - return traverse(root, &last_val); - } + return dfs(root, INT_MIN, INT_MAX); } int main(int argc, char **argv) @@ -43,13 +28,13 @@ int main(int argc, char **argv) struct TreeNode root; struct TreeNode left; struct TreeNode right; - root.val = 2; + root.val = 1; root.left = &left; - root.right = &right; + root.right = NULL; left.val = 1; left.left = NULL; left.right = NULL; - right.val = 3; + right.val = 1; right.left = NULL; right.right = NULL; printf("%s\n", isValidBST(&root) ? "true" : "false"); diff --git a/099_recover_binary_search_tree/recover_bst.c b/099_recover_binary_search_tree/recover_bst.c index ecae963..8636472 100644 --- a/099_recover_binary_search_tree/recover_bst.c +++ b/099_recover_binary_search_tree/recover_bst.c @@ -8,45 +8,41 @@ struct TreeNode { struct TreeNode *right; }; -static struct TreeNode *last = NULL; -static struct TreeNode *m1 = NULL; -static struct TreeNode *m2 = NULL; -static int wrong = 0; - -static void traverse(struct TreeNode* node) +static void traverse(struct TreeNode *node, struct TreeNode **prev, + struct TreeNode **p1, struct TreeNode **p2, int *wrong) { if (node->left != NULL) { - traverse(node->left); + traverse(node->left, prev, p1, p2, wrong); } - if (last != NULL && node->val < last->val) { - if (++wrong == 2) { - int tmp = node->val; - node->val = m1->val; - m1->val = tmp; + if (*prev != NULL && node->val < (*prev)->val) { + (*wrong)++; + if (*wrong == 1) { + *p1 = *prev; + *p2 = node; + } else if (*wrong == 2) { + *p2 = node; + return; } - m1 = last; - m2 = node; } - last = node; + *prev = node; if (node->right != NULL) { - traverse(node->right); + traverse(node->right, prev, p1, p2, wrong); } } -static void recoverTree(struct TreeNode* root) { +static void recoverTree(struct TreeNode* root) +{ if (root != NULL) { - last = NULL; - m1 = NULL; - m2 = NULL; - wrong = 0; - traverse(root); - if (wrong == 1) { - int tmp = m1->val; - m1->val = m2->val; - m2->val = tmp; - } + struct TreeNode *prev = NULL; + struct TreeNode *p1 = NULL; + struct TreeNode *p2 = NULL; + int wrong = 0; + traverse(root, &prev, &p1, &p2, &wrong); + int tmp = p1->val; + p1->val = p2->val; + p2->val = tmp; } } diff --git a/100_same_tree/same_tree.c b/100_same_tree/same_tree.c index 14e15ee..36bc7bb 100644 --- a/100_same_tree/same_tree.c +++ b/100_same_tree/same_tree.c @@ -8,10 +8,8 @@ struct TreeNode { struct TreeNode *right; }; -bool isSameTree(struct TreeNode* p, struct TreeNode* q) { - if ((p == NULL && q != NULL) || (p != NULL && q == NULL)) { - return false; - } +static bool isSameTree(struct TreeNode* p, struct TreeNode* q) +{ if (p != NULL && q != NULL) { if (p->val != q->val) { return false; @@ -22,6 +20,8 @@ bool isSameTree(struct TreeNode* p, struct TreeNode* q) { if (!isSameTree(p->right, q->right)) { return false; } + } else { + return p == q; } return true; From d5070608d33718c9db556921d10fa111eafe3436 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 4 Jan 2018 18:35:59 +0800 Subject: [PATCH 028/211] Improve Signed-off-by: begeekmyfriend --- .../longest_palindromic_substring.c | 71 ++++++++++++----- 070_climbing_stairs/climb_stairs.c | 8 +- 087_scramble_string/scramble_string.c | 7 +- .../binary_tree_build.c | 76 ++++--------------- .../binary_tree_build.c | 76 ++++--------------- .../bst_convert.c | 23 ++---- .../bst_convert.c | 8 +- 113_path_sum_ii/path_sum.c | 8 +- .../flatten.c | 8 +- 115_distinct_subsequences/distinct_subseq.c | 1 + .../connect.c | 4 + 120_triangle/triangle.c | 10 +-- .../bst_max_path.c | 11 ++- 126_word_ladder_ii/word_ladder.c | 34 +++------ 127_word_ladder/word_ladder.c | 68 +++++++---------- 128_longest_consecutive_sequence/consec_seq.c | 38 +++++----- 129_sum_root_to_leaf_numbers/sum_tree.c | 26 +++---- 130_surrounded_regions/surrounded_regions.c | 21 ++--- .../palindrome_partition.c | 14 ++-- 133_clone_graph/clone_graph.c | 34 ++++----- 135_candy/candy.c | 1 + 139_word_break/word_break.c | 63 +++++++-------- 140_word_break_ii/word_break.c | 63 +++++++-------- 143_reorder_list/reorder_list.c | 4 + .../bst_preorder.c | 2 + .../bst_postorder.c | 34 +++++---- 146_lru_cache/lru_cache.c | 51 +++++-------- 148_sort_list/sort_list.c | 8 +- 164_maximum_gap/max_gap.c | 20 +++-- 179_largest_number/largest_number.c | 37 +++------ 200_number_of_islands/islands.c | 12 +-- 214_shortest_palindrome/shortest_palindrome.c | 5 ++ 32 files changed, 366 insertions(+), 480 deletions(-) diff --git a/005_longest_palindromic_substring/longest_palindromic_substring.c b/005_longest_palindromic_substring/longest_palindromic_substring.c index 540a9cb..b8c2e91 100644 --- a/005_longest_palindromic_substring/longest_palindromic_substring.c +++ b/005_longest_palindromic_substring/longest_palindromic_substring.c @@ -2,21 +2,61 @@ #include #include -static void find(char *s, int len, int low, int high, int *max_size, char *palindrome) { - while (low >= 0 && high < len && s[low] == s[high]) { - low--; - high++; - } - low++; - high--; +static inline int min(int a, int b) +{ + return a < b ? a : b; +} + +static int manacher(char *s, char output[]) +{ + int i, j; + char s2[1000] = { '\0' }; - if (high - low + 1 > *max_size) { - *max_size = high - low + 1; - memcpy(palindrome, s + low, *max_size); + s2[0] = '$'; + for (i = 0; s[i] != '\0'; i++) { + s2[(i<<1)+1] = '#'; + s2[(i<<1)+2] = s[i]; } + s2[(i<<1)+1] = '#'; + int len = (i<<1)+2; + s2[len] = '\0'; + + int p[1000] = { 0 }; // 以s2中某一点为中心的回文半径 + int id = 0; // 回文的中心点 + int limit = 0; // 最长回文的右边界点 + int maxLen = 0; // 最大回文长度 + int maxId = 0; // 最长回文的中心点 + for (i = 1; i < len; i++) { + if (i < limit) { + p[i] = min(p[2*id-i], limit-i); + } else { + p[i] = 1; + } + + while (s2[i+p[i]] == s2[i-p[i]]) { + p[i]++; + } + + if (i+p[i] > limit) { + limit = i+p[i]; + id = i; + } + if (maxLen < p[i]-1) { + maxLen = p[i]-1; + maxId = i; + } + } + + for (j = 0, i = maxId - maxLen; i <= maxId+maxLen; i++) { + if (s2[i] != '#') { + output[j++] = s2[i]; + } + } + return maxLen; } -static char *longestPalindrom(char *s) { +static char *longestPalindrom(char *s) +{ int i; if (s == NULL) { return NULL; @@ -30,13 +70,8 @@ static char *longestPalindrom(char *s) { char *palindrome = malloc(1000); memset(palindrome, 0, sizeof(palindrome)); - int max_size = 0; - for (i = 0; i < len; i++) { - /* start from the middle and scan both two sides */ - find(s, len, i, i, &max_size, palindrome); - find(s, len, i, i + 1, &max_size, palindrome); - } - + int size = manacher(s, palindrome); + palindrome[size] = '\0'; return palindrome; } diff --git a/070_climbing_stairs/climb_stairs.c b/070_climbing_stairs/climb_stairs.c index 2b0b31a..54645c6 100644 --- a/070_climbing_stairs/climb_stairs.c +++ b/070_climbing_stairs/climb_stairs.c @@ -2,7 +2,7 @@ #include #include -static int recursive(int n, int *count) +static int dfs(int n, int *count) { if (n == 0) { return 0; @@ -10,10 +10,10 @@ static int recursive(int n, int *count) return count[n]; } else { if (n >= 1) { - count[n] += recursive(n - 1, count); + count[n] += dfs(n - 1, count); } if (n >= 2) { - count[n] += recursive(n - 2, count); + count[n] += dfs(n - 2, count); } return count[n]; } @@ -25,7 +25,7 @@ static int climbStairs(int n) memset(count, 0, (n + 1) * sizeof(int)); count[1] = 1; count[2] = 2; - return recursive(n, count); + return dfs(n, count); } int main(int argc, char **argv) diff --git a/087_scramble_string/scramble_string.c b/087_scramble_string/scramble_string.c index 1eb5c8a..7e379bd 100644 --- a/087_scramble_string/scramble_string.c +++ b/087_scramble_string/scramble_string.c @@ -49,10 +49,9 @@ static bool scramble(char *s1, int low1, int high1, char *s2, int low2, int high } } -static bool isScramble(char* s1, char* s2) { - int len1 = strlen(s1); - int len2 = strlen(s2); - return scramble(s1, 0, len1 - 1, s2, 0, len2 - 1); +static bool isScramble(char* s1, char* s2) +{ + return scramble(s1, 0, strlen(s1) - 1, s2, 0, strlen(s2) - 1); } int main(int argc, char **argv) diff --git a/105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c b/105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c index 4319273..87bd48c 100644 --- a/105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c +++ b/105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c @@ -1,6 +1,15 @@ #include #include +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + struct hlist_node; struct hlist_head { @@ -15,11 +24,6 @@ static inline void INIT_HLIST_HEAD(struct hlist_head *h) { h->first = NULL; } -static inline void INIT_HLIST_NODE(struct hlist_node *n) { - n->next = NULL; - n->pprev = NULL; -} - static inline int hlist_empty(struct hlist_head *h) { return !h->first; } @@ -44,15 +48,6 @@ static inline void hlist_del(struct hlist_node *n) } } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - struct TreeNode { int val; struct TreeNode *left; @@ -87,9 +82,8 @@ static struct TreeNode *node_new(int val) return tn; } -static struct TreeNode *recursive(int *preorder, int pre_low, int pre_high, - int *inorder, int in_low, int in_high, - struct hlist_head *in_heads, int size) +static struct TreeNode *dfs(int *preorder, int pre_low, int pre_high, int *inorder, + int in_low, int in_high, struct hlist_head *in_heads, int size) { if (in_low > in_high || pre_low > pre_high) { return NULL; @@ -97,8 +91,8 @@ static struct TreeNode *recursive(int *preorder, int pre_low, int pre_high, struct TreeNode *tn = malloc(sizeof(*tn)); tn->val = preorder[pre_low]; int index = find(preorder[pre_low], size, in_heads); - tn->left = recursive(preorder, pre_low + 1, pre_low + (index - in_low), inorder, in_low, index - 1, in_heads, size); - tn->right = recursive(preorder, pre_high - (in_high - index - 1), pre_high, inorder, index + 1, in_high, in_heads, size); + tn->left = dfs(preorder, pre_low + 1, pre_low + (index - in_low), inorder, in_low, index - 1, in_heads, size); + tn->right = dfs(preorder, pre_high - (in_high - index - 1), pre_high, inorder, index + 1, in_high, in_heads, size); return tn; } @@ -122,49 +116,7 @@ static struct TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, node_add(inorder[i], i, inorderSize, in_heads); } -#if 0 - struct hlist_head *pre_heads = malloc(preorderSize * sizeof(*pre_heads)); - for (i = 0; i < preorderSize; i++) { - INIT_HLIST_HEAD(&pre_heads[i]); - } - for (i = 0; i < inorderSize; i++) { - node_add(preorder[i], i, preorderSize, pre_heads); - } - - int last_index, level = 0; - struct TreeNode **stack = malloc(preorderSize * sizeof(*stack)); - struct TreeNode *tn, *root = NULL; - for (i = 0; i < preorderSize; i++) { - if (i == 0) { - tn = root = node_new(preorder[0]); - last_index = find(preorder[0], inorderSize, in_heads); - stack[level++] = root; - } else { - int index = find(preorder[i], inorderSize, in_heads); - if (index < last_index) { - tn->left = node_new(preorder[i]); - tn = tn->left; - } else { - for (j = index - 1; j >= 0; j--) { - if (find(inorder[j], preorderSize, pre_heads) < i) { - break; - } - } - /* find the parent of the right child */ - while (stack[--level]->val != inorder[j]) {} - tn = stack[level++]; - tn->right = node_new(preorder[i]); - tn = tn->right; - } - stack[level++] = tn; - last_index = index; - } - } - - return root; -#else - return recursive(preorder, 0, preorderSize - 1, inorder, 0, inorderSize - 1, in_heads, inorderSize); -#endif + return dfs(preorder, 0, preorderSize - 1, inorder, 0, inorderSize - 1, in_heads, inorderSize); } static void dump(struct TreeNode *node) diff --git a/106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c b/106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c index a02c17b..60c9b62 100644 --- a/106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c +++ b/106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c @@ -1,6 +1,15 @@ #include #include +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + struct hlist_node; struct hlist_head { @@ -15,11 +24,6 @@ static inline void INIT_HLIST_HEAD(struct hlist_head *h) { h->first = NULL; } -static inline void INIT_HLIST_NODE(struct hlist_node *n) { - n->next = NULL; - n->prev = NULL; -} - static inline int hlist_empty(struct hlist_head *h) { return !h->first; } @@ -44,15 +48,6 @@ static inline void hlist_del(struct hlist_node *n) } } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - struct TreeNode { int val; struct TreeNode *left; @@ -96,9 +91,8 @@ static void node_add(int val, int index, int size, struct hlist_head *heads) hlist_add_head(&on->node, &heads[hash]); } -static struct TreeNode *recursive(int *inorder, int in_low, int in_high, - int *postorder, int post_low, int post_high, - struct hlist_head *in_heads, int size) +static struct TreeNode *dfs(int *inorder, int in_low, int in_high, int *postorder, + int post_low, int post_high, struct hlist_head *in_heads, int size) { if (in_low > in_high || post_low > post_high) { return NULL; @@ -106,15 +100,14 @@ static struct TreeNode *recursive(int *inorder, int in_low, int in_high, struct TreeNode *tn = malloc(sizeof(*tn)); tn->val = postorder[post_high]; int index = find(postorder[post_high], size, in_heads); - tn->left = recursive(inorder, in_low, index - 1, postorder, post_low, post_low + (index - 1 - in_low), in_heads, size); - tn->right = recursive(inorder, index + 1, in_high, postorder, post_high - (in_high - index), post_high - 1, in_heads, size); + tn->left = dfs(inorder, in_low, index - 1, postorder, post_low, post_low + (index - 1 - in_low), in_heads, size); + tn->right = dfs(inorder, index + 1, in_high, postorder, post_high - (in_high - index), post_high - 1, in_heads, size); return tn; } static struct TreeNode *buildTree(int *inorder, int inorderSize, int *postorder, int postorderSize) { int i, j; - struct hlist_head *in_heads = malloc(inorderSize * sizeof(*in_heads)); for (i = 0; i < inorderSize; i++) { INIT_HLIST_HEAD(&in_heads[i]); @@ -123,48 +116,7 @@ static struct TreeNode *buildTree(int *inorder, int inorderSize, int *postorder, node_add(inorder[i], i, inorderSize, in_heads); } -#if 0 - struct hlist_head *post_heads = malloc(postorderSize * sizeof(*post_heads)); - for (i = 0; i < postorderSize; i++) { - INIT_HLIST_HEAD(&post_heads[i]); - } - for (i = 0; i < inorderSize; i++) { - node_add(postorder[i], i, postorderSize, post_heads); - } - int last_index, level = 0; - struct TreeNode **stack = malloc(postorderSize * sizeof(*stack)); - struct TreeNode *tn, *root = NULL; - for (i = postorderSize - 1; i >= 0; i--) { - if (i == postorderSize - 1) { - tn = root = node_new(postorder[i]); - last_index = find(postorder[i], inorderSize, in_heads); - stack[level++] = root; - } else { - int index = find(postorder[i], inorderSize, in_heads); - if (index > last_index) { - tn->right = node_new(postorder[i]); - tn = tn->right; - } else { - for (j = index + 1; j < inorderSize; j++) { - if (find(inorder[j], postorderSize, post_heads) > i) { - break; - } - } - /* find the parent of the left child */ - while (stack[--level]->val != inorder[j]) {} - tn = stack[level++]; - tn->left = node_new(postorder[i]); - tn = tn->left; - } - stack[level++] = tn; - last_index = index; - } - } - - return root; -#else - return recursive(inorder, 0, inorderSize - 1, postorder, 0, postorderSize - 1, in_heads, inorderSize); -#endif + return dfs(inorder, 0, inorderSize - 1, postorder, 0, postorderSize - 1, in_heads, inorderSize); } static void dump(struct TreeNode *node) diff --git a/108_convert_sorted_array_to_binary_search_tree/bst_convert.c b/108_convert_sorted_array_to_binary_search_tree/bst_convert.c index 3f249c2..b38e13b 100644 --- a/108_convert_sorted_array_to_binary_search_tree/bst_convert.c +++ b/108_convert_sorted_array_to_binary_search_tree/bst_convert.c @@ -8,19 +8,14 @@ struct TreeNode { struct TreeNode *right; }; -static void recursive(struct TreeNode **node, int *nums, int size, int i, struct TreeNode **root) +static struct TreeNode *partition(int *nums, int lo, int hi) { - if () { - *node = malloc(sizeof(**node)); - (*node)->val = nums[ - } else { - recursive(node, nums, size, i, root); - *node = malloc(sizeof(**root)); - if (i == size / 2) { - *root = *node; - } - recursive(node, nums, size, i, root); - } + int mid = lo + (hi - lo) / 2; + struct TreeNode *node = malloc(sizeof(*node)); + node->val = nums[mid]; + node->left = mid > lo ? partition(nums, lo, mid - 1) : NULL; + node->right = mid < hi ? partition(nums, mid + 1, hi) : NULL; + return node; } static struct TreeNode* sortedArrayToBST(int* nums, int numsSize) @@ -28,9 +23,7 @@ static struct TreeNode* sortedArrayToBST(int* nums, int numsSize) if (numsSize == 0) { return NULL; } - struct TreeNode *node, *root; - recursive(nums, numsSize, 0, &root); - return root; + return partition(nums, 0, numsSize - 1); } int main(int argc, char **argv) diff --git a/109_convert_sorted_list_to_binary_search_tree/bst_convert.c b/109_convert_sorted_list_to_binary_search_tree/bst_convert.c index d5f5fa4..c79f239 100644 --- a/109_convert_sorted_list_to_binary_search_tree/bst_convert.c +++ b/109_convert_sorted_list_to_binary_search_tree/bst_convert.c @@ -12,13 +12,13 @@ struct TreeNode { struct TreeNode *right; }; -static struct TreeNode *recursive(int *nums, int lo, int hi) +static struct TreeNode *traverse(int *nums, int lo, int hi) { int mid = lo + (hi - lo) / 2; struct TreeNode *node = malloc(sizeof(*node)); node->val = nums[mid]; - node->left = mid > lo ? recursive(nums, lo, mid - 1) : NULL; - node->right = mid < hi ? recursive(nums, mid + 1, hi) : NULL; + node->left = mid > lo ? traverse(nums, lo, mid - 1) : NULL; + node->right = mid < hi ? traverse(nums, mid + 1, hi) : NULL; return node; } @@ -31,7 +31,7 @@ static struct TreeNode *sortedListToBST(struct ListNode *head) if (i == 0) { return NULL; } - return recursive(nums, 0, i - 1); + return traverse(nums, 0, i - 1); } int main(int argc, char **argv) diff --git a/113_path_sum_ii/path_sum.c b/113_path_sum_ii/path_sum.c index 9f07251..5ab7343 100644 --- a/113_path_sum_ii/path_sum.c +++ b/113_path_sum_ii/path_sum.c @@ -8,7 +8,7 @@ struct TreeNode { struct TreeNode *right; }; -static void recursive(struct TreeNode *node, int sum, int *stack, int len, int **results, int *sizes, int *count) +static void dfs(struct TreeNode *node, int sum, int *stack, int len, int **results, int *sizes, int *count) { if (node == NULL) { return; @@ -24,8 +24,8 @@ static void recursive(struct TreeNode *node, int sum, int *stack, int len, int * return; } stack[len] = node->val; - recursive(node->left, sum, stack, len + 1, results, sizes, count); - recursive(node->right, sum, stack, len + 1, results, sizes, count); + dfs(node->left, sum, stack, len + 1, results, sizes, count); + dfs(node->right, sum, stack, len + 1, results, sizes, count); } static int **pathSum(struct TreeNode *root, int sum, int **columnSizes, int *returnSize) @@ -39,7 +39,7 @@ static int **pathSum(struct TreeNode *root, int sum, int **columnSizes, int *ret int *stack = malloc(level * sizeof(int)); int **results = malloc(cap * sizeof(int *)); *columnSizes = malloc(cap * sizeof(int)); - recursive(root, sum, stack, 0, results, *columnSizes, returnSize); + dfs(root, sum, stack, 0, results, *columnSizes, returnSize); return results; } diff --git a/114_flatten_binary_tree_to_linked_list/flatten.c b/114_flatten_binary_tree_to_linked_list/flatten.c index 58072f6..ddad243 100644 --- a/114_flatten_binary_tree_to_linked_list/flatten.c +++ b/114_flatten_binary_tree_to_linked_list/flatten.c @@ -8,7 +8,7 @@ struct TreeNode { struct TreeNode *right; }; -static struct TreeNode *recursive(struct TreeNode *node) +static struct TreeNode *partition(struct TreeNode *node) { if (node == NULL) { return NULL; @@ -18,8 +18,8 @@ static struct TreeNode *recursive(struct TreeNode *node) return node; } - struct TreeNode *right_last = recursive(node->right); - struct TreeNode *left_last = recursive(node->left); + struct TreeNode *right_last = partition(node->right); + struct TreeNode *left_last = partition(node->left); if (left_last != NULL) { left_last->right = node->right; @@ -32,7 +32,7 @@ static struct TreeNode *recursive(struct TreeNode *node) static void flatten(struct TreeNode *root) { - recursive(root); + partition(root); } int main(void) diff --git a/115_distinct_subsequences/distinct_subseq.c b/115_distinct_subsequences/distinct_subseq.c index 9ab6849..a367df4 100644 --- a/115_distinct_subsequences/distinct_subseq.c +++ b/115_distinct_subsequences/distinct_subseq.c @@ -30,6 +30,7 @@ static int numDistinct(char* s, char* t) dp[0][i] = 0; } + /* I guess it, just dump the dp table and you will find the rule... */ for (i = 1; i < s_len - start; i++) { dp[i][0] = dp[i - 1][0]; if (s[start + i] == t[0]) { diff --git a/116_populating_next_right_pointers_in_each_node/connect.c b/116_populating_next_right_pointers_in_each_node/connect.c index 9ff181f..728a0be 100644 --- a/116_populating_next_right_pointers_in_each_node/connect.c +++ b/116_populating_next_right_pointers_in_each_node/connect.c @@ -10,6 +10,10 @@ struct TreeLinkNode { static void connect(struct TreeLinkNode *root) { + if (root == NULL) { + return; + } + struct TreeLinkNode *head = root; while (head->left != NULL) { struct TreeLinkNode *p; diff --git a/120_triangle/triangle.c b/120_triangle/triangle.c index 430c425..2221137 100644 --- a/120_triangle/triangle.c +++ b/120_triangle/triangle.c @@ -3,16 +3,16 @@ #include #include -static int recursive(int** triangle, int row_size, int *col_sizes, - int row, int col, int **sums, bool **passes) +static int dfs(int** triangle, int row_size, int *col_sizes, + int row, int col, int **sums, bool **passes) { if (row == row_size - 1) { return triangle[row][col]; } else if (passes[row][col]) { return sums[row][col]; } else { - int s1 = recursive(triangle, row_size, col_sizes, row + 1, col, sums, passes); - int s2 = recursive(triangle, row_size, col_sizes, row + 1, col + 1, sums, passes); + int s1 = dfs(triangle, row_size, col_sizes, row + 1, col, sums, passes); + int s2 = dfs(triangle, row_size, col_sizes, row + 1, col + 1, sums, passes); sums[row][col] = triangle[row][col] + (s1 < s2 ? s1 : s2); passes[row][col] = true; return sums[row][col]; @@ -31,7 +31,7 @@ static int minimumTotal(int** triangle, int triangleRowSize, int *triangleColSiz for (i = 0; i < triangleRowSize; i++) { sums[i] = malloc(triangleColSizes[i] * sizeof(int)); } - return recursive(triangle, triangleRowSize, triangleColSizes, 0, 0, sums, passes); + return dfs(triangle, triangleRowSize, triangleColSizes, 0, 0, sums, passes); } int main(void) diff --git a/124_binary_tree_maximum_path_sum/bst_max_path.c b/124_binary_tree_maximum_path_sum/bst_max_path.c index 31f9ac0..bf9df29 100644 --- a/124_binary_tree_maximum_path_sum/bst_max_path.c +++ b/124_binary_tree_maximum_path_sum/bst_max_path.c @@ -8,17 +8,17 @@ struct TreeNode { struct TreeNode *right; }; -static int recursive(struct TreeNode *node, int *max) +static int partition(struct TreeNode *node, int *max) { int left_max = 0; int right_max = 0; if (node->left != NULL) { - left_max = recursive(node->left, max); + left_max = partition(node->left, max); } if (node->right != NULL) { - right_max = recursive(node->right, max); + right_max = partition(node->right, max); } int sum = node->val + left_max + right_max; @@ -26,8 +26,7 @@ static int recursive(struct TreeNode *node, int *max) *max = sum; } - int path_sum = node->val + (right_max > left_max ? right_max : left_max); - return path_sum > 0 ? path_sum : 0; + return node->val + (right_max > left_max ? right_max : left_max); } static int maxPathSum(struct TreeNode* root) @@ -37,7 +36,7 @@ static int maxPathSum(struct TreeNode* root) } int max = INT_MIN; - recursive(root, &max); + partition(root, &max); return max; } diff --git a/126_word_ladder_ii/word_ladder.c b/126_word_ladder_ii/word_ladder.c index a3aaa8d..7305ddc 100644 --- a/126_word_ladder_ii/word_ladder.c +++ b/126_word_ladder_ii/word_ladder.c @@ -37,11 +37,6 @@ static inline void INIT_HLIST_HEAD(struct hlist_head *h) { h->first = NULL; } -static inline void INIT_HLIST_NODE(struct hlist_node *n) { - n->next = NULL; - n->pprev = NULL; -} - static inline int hlist_empty(struct hlist_head *h) { return !h->first; } @@ -60,20 +55,17 @@ struct list_head { struct list_head *next, *prev; }; -static inline void -INIT_LIST_HEAD(struct list_head *list) +static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; } -static inline int -list_empty(const struct list_head *head) +static inline int list_empty(const struct list_head *head) { return (head->next == head); } -static inline void -__list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; @@ -81,27 +73,23 @@ __list_add(struct list_head *new, struct list_head *prev, struct list_head *next prev->next = new; } -static inline void -list_add(struct list_head *_new, struct list_head *head) +static inline void list_add(struct list_head *_new, struct list_head *head) { __list_add(_new, head, head->next); } -static inline void -list_add_tail(struct list_head *_new, struct list_head *head) +static inline void list_add_tail(struct list_head *_new, struct list_head *head) { __list_add(_new, head->prev, head); } -static inline void -__list_del(struct list_head *entry) +static inline void __list_del(struct list_head *entry) { entry->next->prev = entry->prev; entry->prev->next = entry->next; } -static inline void -list_del(struct list_head *entry) +static inline void list_del(struct list_head *entry) { __list_del(entry); entry->next = entry->prev = NULL; @@ -161,10 +149,10 @@ static void parent_add(struct word_tree *parent, struct word_tree *child) } /** - * * Return an array of arrays of size *returnSize. - * * The sizes of the arrays are returned as *columnSizes array. - * * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). - * */ + ** Return an array of arrays of size *returnSize. + ** The sizes of the arrays are returned as *columnSizes array. + ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + **/ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordListSize, int** columnSizes, int* returnSize) { int i, j, k; diff --git a/127_word_ladder/word_ladder.c b/127_word_ladder/word_ladder.c index 3059ae9..0ae1d43 100644 --- a/127_word_ladder/word_ladder.c +++ b/127_word_ladder/word_ladder.c @@ -2,6 +2,27 @@ #include #include +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) +#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) + +#define list_for_each(p, head) \ + for (p = (head)->next; p != (head); p = p->next) + +#define list_for_each_safe(p, n, head) \ + for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + +#define hlist_for_each_safe(pos, n, head) \ + for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) + struct hlist_node; struct hlist_head { @@ -16,11 +37,6 @@ static inline void INIT_HLIST_HEAD(struct hlist_head *h) { h->first = NULL; } -static inline void INIT_HLIST_NODE(struct hlist_node *n) { - n->next = NULL; - n->pprev = NULL; -} - static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) { if (h->first != NULL) { @@ -35,20 +51,17 @@ struct list_head { struct list_head *next, *prev; }; -static inline void -INIT_LIST_HEAD(struct list_head *list) +static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; } -static inline int -list_empty(const struct list_head *head) +static inline int list_empty(const struct list_head *head) { return (head->next == head); } -static inline void -__list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; @@ -56,53 +69,28 @@ __list_add(struct list_head *new, struct list_head *prev, struct list_head *next prev->next = new; } -static inline void -list_add(struct list_head *_new, struct list_head *head) +static inline void list_add(struct list_head *_new, struct list_head *head) { __list_add(_new, head, head->next); } -static inline void -list_add_tail(struct list_head *_new, struct list_head *head) +static inline void list_add_tail(struct list_head *_new, struct list_head *head) { __list_add(_new, head->prev, head); } -static inline void -__list_del(struct list_head *entry) +static inline void __list_del(struct list_head *entry) { entry->next->prev = entry->prev; entry->prev->next = entry->next; } -static inline void -list_del(struct list_head *entry) +static inline void list_del(struct list_head *entry) { __list_del(entry); entry->next = entry->prev = NULL; } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) - -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - struct word_node { int step; char *word; diff --git a/128_longest_consecutive_sequence/consec_seq.c b/128_longest_consecutive_sequence/consec_seq.c index a290d5c..075844e 100644 --- a/128_longest_consecutive_sequence/consec_seq.c +++ b/128_longest_consecutive_sequence/consec_seq.c @@ -1,6 +1,18 @@ #include #include +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + +#define hlist_for_each_safe(pos, n, head) \ + for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) + struct hlist_node; struct hlist_head { @@ -11,16 +23,13 @@ struct hlist_node { struct hlist_node *next, **pprev; }; -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { +static inline void INIT_HLIST_HEAD(struct hlist_head *h) +{ h->first = NULL; } -static inline void INIT_HLIST_NODE(struct hlist_node *n) { - n->next = NULL; - n->pprev = NULL; -} - -static inline int hlist_empty(struct hlist_head *h) { +static inline int hlist_empty(struct hlist_head *h) +{ return !h->first; } @@ -44,18 +53,6 @@ static inline void hlist_del(struct hlist_node *n) } } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - struct seq_node { int num; struct hlist_node node; @@ -74,7 +71,8 @@ static struct seq_node *find(int num, int size, struct hlist_head *heads) return NULL; } -static int longestConsecutive(int* nums, int numsSize) { +static int longestConsecutive(int* nums, int numsSize) +{ int i, hash, length = 0; struct seq_node *node; struct hlist_head *heads = malloc(numsSize * sizeof(*heads)); diff --git a/129_sum_root_to_leaf_numbers/sum_tree.c b/129_sum_root_to_leaf_numbers/sum_tree.c index c06d7ca..686b3d8 100644 --- a/129_sum_root_to_leaf_numbers/sum_tree.c +++ b/129_sum_root_to_leaf_numbers/sum_tree.c @@ -7,20 +7,21 @@ struct TreeNode { struct TreeNode *right; }; -static void recursive(struct TreeNode* node, int sum, int *total) +static int dfs(struct TreeNode* node, int sum) { + int total = 0; sum = sum * 10 + node->val; if (node->left == NULL && node->right == NULL) { - *total += sum; - } - - if (node->left != NULL) { - recursive(node->left, sum, total); - } - - if (node->right != NULL) { - recursive(node->right, sum, total); + return sum; + } else { + if (node->left != NULL) { + total += dfs(node->left, sum); + } + if (node->right != NULL) { + total += dfs(node->right, sum); + } + return total; } } @@ -29,10 +30,7 @@ static int sumNumbers(struct TreeNode* root) if (root == NULL) { return 0; } - - int total = 0; - recursive(root, 0, &total); - return total; + return dfs(root, 0); } int main(void) diff --git a/130_surrounded_regions/surrounded_regions.c b/130_surrounded_regions/surrounded_regions.c index 96f2ca4..304b4c7 100644 --- a/130_surrounded_regions/surrounded_regions.c +++ b/130_surrounded_regions/surrounded_regions.c @@ -21,20 +21,17 @@ struct list_head { struct list_head *next, *prev; }; -static inline void -INIT_LIST_HEAD(struct list_head *list) +static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; } -static inline int -list_empty(const struct list_head *head) +static inline int list_empty(const struct list_head *head) { return (head->next == head); } -static inline void -__list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; @@ -42,27 +39,23 @@ __list_add(struct list_head *new, struct list_head *prev, struct list_head *next prev->next = new; } -static inline void -list_add(struct list_head *_new, struct list_head *head) +static inline void list_add(struct list_head *_new, struct list_head *head) { __list_add(_new, head, head->next); } -static inline void -list_add_tail(struct list_head *_new, struct list_head *head) +static inline void list_add_tail(struct list_head *_new, struct list_head *head) { __list_add(_new, head->prev, head); } -static inline void -__list_del(struct list_head *entry) +static inline void __list_del(struct list_head *entry) { entry->next->prev = entry->prev; entry->prev->next = entry->next; } -static inline void -list_del(struct list_head *entry) +static inline void list_del(struct list_head *entry) { __list_del(entry); entry->next = entry->prev = NULL; diff --git a/131_palindrome_patitioning/palindrome_partition.c b/131_palindrome_patitioning/palindrome_partition.c index 25f2e88..2691e0f 100644 --- a/131_palindrome_patitioning/palindrome_partition.c +++ b/131_palindrome_patitioning/palindrome_partition.c @@ -19,9 +19,9 @@ static void collect(char *s, int len, int low, int high, struct palindrome *resu } } -static void recursive(struct palindrome *pal_set, int num, int start, - char *s, int len, struct palindrome **stack, int size, - char ***results, int *col_sizes, int *count) +static void dfs(struct palindrome *pal_set, int num, int start, + char *s, int len, struct palindrome **stack, int size, + char ***results, int *col_sizes, int *count) { int i; if (size > 0 && stack[size - 1]->high == len - 1) { @@ -40,7 +40,7 @@ static void recursive(struct palindrome *pal_set, int num, int start, if ((size == 0 && pal_set[i].low == 0) || (size > 0 && stack[size - 1]->high + 1 == pal_set[i].low)) { stack[size] = &pal_set[i]; - recursive(pal_set, num, i + 1, s, len, stack, size + 1, results, col_sizes, count); + dfs(pal_set, num, i + 1, s, len, stack, size + 1, results, col_sizes, count); } } } @@ -51,7 +51,8 @@ static void recursive(struct palindrome *pal_set, int num, int start, ** The sizes of the arrays are returned as *columnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -char ***partition(char* s, int** columnSizes, int* returnSize) { +static char ***partition(char* s, int** columnSizes, int* returnSize) +{ int len = strlen(s); if (len == 0) { *returnSize = 0; @@ -68,8 +69,7 @@ char ***partition(char* s, int** columnSizes, int* returnSize) { char ***results = malloc(cap * sizeof(char **)); struct palindrome **stack = malloc(count * sizeof(*stack)); *columnSizes = malloc(cap * sizeof(int)); - recursive(pal_set, count, 0, s, len, stack, 0, results, *columnSizes, returnSize); - + dfs(pal_set, count, 0, s, len, stack, 0, results, *columnSizes, returnSize); return results; } diff --git a/133_clone_graph/clone_graph.c b/133_clone_graph/clone_graph.c index cea7f4d..30ad891 100644 --- a/133_clone_graph/clone_graph.c +++ b/133_clone_graph/clone_graph.c @@ -1,6 +1,20 @@ #include #include +#define NEIGHBORS_MAX_SIZE 100 + +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + +#define hlist_for_each_safe(pos, n, head) \ + for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) + struct hlist_node; struct hlist_head { @@ -44,20 +58,6 @@ static inline void hlist_del(struct hlist_node *n) } } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - -#define NEIGHBORS_MAX_SIZE 100 - struct UndirectedGraphNode { int label; struct UndirectedGraphNode *neighbors[NEIGHBORS_MAX_SIZE]; @@ -82,7 +82,7 @@ static struct UndirectedGraphNode *find(int label, int size, struct hlist_head * return NULL; } -static struct UndirectedGraphNode *recursive_clone(struct UndirectedGraphNode *graph, struct hlist_head *heads, int size) +static struct UndirectedGraphNode *dfs(struct UndirectedGraphNode *graph, struct hlist_head *heads, int size) { if (graph == NULL) { return NULL; @@ -103,7 +103,7 @@ static struct UndirectedGraphNode *recursive_clone(struct UndirectedGraphNode *g int i; for (i = 0; i < node->neighborsCount; i++) { - node->neighbors[i] = recursive_clone(graph->neighbors[i], heads, size); + node->neighbors[i] = dfs(graph->neighbors[i], heads, size); } return node; @@ -117,7 +117,7 @@ static struct UndirectedGraphNode *cloneGraph(struct UndirectedGraphNode *graph) INIT_HLIST_HEAD(&heads[i]); } - return recursive_clone(graph, heads, cap); + return dfs(graph, heads, cap); } int main(void) diff --git a/135_candy/candy.c b/135_candy/candy.c index 25bee29..20721bd 100644 --- a/135_candy/candy.c +++ b/135_candy/candy.c @@ -13,6 +13,7 @@ static int candy(int* ratings, int ratingsSize) if (ratings[i] > ratings[i - 1]) { candies[i] = candies[i - 1] + 1; } else { + /* Set as least so that it will be reset from the opposite side */ candies[i] = 1; } } diff --git a/139_word_break/word_break.c b/139_word_break/word_break.c index 9938b02..40992fa 100644 --- a/139_word_break/word_break.c +++ b/139_word_break/word_break.c @@ -3,24 +3,33 @@ #include #include +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define list_for_each(p, head) \ + for (p = (head)->next; p != (head); p = p->next) + +#define list_for_each_safe(p, n, head) \ + for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) + struct list_head { struct list_head *next, *prev; }; -static inline void -INIT_LIST_HEAD(struct list_head *list) +static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; } -static inline int -list_empty(const struct list_head *head) +static inline int list_empty(const struct list_head *head) { return (head->next == head); } -static inline void -__list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; @@ -28,59 +37,43 @@ __list_add(struct list_head *new, struct list_head *prev, struct list_head *next prev->next = new; } -static inline void -list_add(struct list_head *_new, struct list_head *head) +static inline void list_add(struct list_head *_new, struct list_head *head) { __list_add(_new, head, head->next); } -static inline void -list_add_tail(struct list_head *_new, struct list_head *head) +static inline void list_add_tail(struct list_head *_new, struct list_head *head) { __list_add(_new, head->prev, head); } -static inline void -__list_del(struct list_head *entry) +static inline void __list_del(struct list_head *entry) { entry->next->prev = entry->prev; entry->prev->next = entry->next; } -static inline void -list_del(struct list_head *entry) +static inline void list_del(struct list_head *entry) { __list_del(entry); entry->next = entry->prev = NULL; } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct word_node { char *word; struct list_head link; }; -struct recur_cache { +struct dfs_cache { int num; int cap; struct list_head **heads; }; -static struct recur_cache *resize(struct recur_cache **caches, int index) +static struct dfs_cache *resize(struct dfs_cache **caches, int index) { int i; - struct recur_cache *cache = caches[index]; + struct dfs_cache *cache = caches[index]; if (cache->num + 1 > cache->cap) { cache->cap *= 2; struct list_head **heads = malloc(cache->cap * sizeof(*heads)); @@ -99,12 +92,12 @@ static struct recur_cache *resize(struct recur_cache **caches, int index) return cache; } -static struct recur_cache *recursive(char *s, char **words, int *sizes, int num, - struct recur_cache **caches, int len, int index) +static struct dfs_cache *dfs(char *s, char **words, int *sizes, int num, + struct dfs_cache **caches, int index) { int i, j; struct word_node *wn; - struct recur_cache *result; + struct dfs_cache *result; if (*s == '\0') { return NULL; @@ -120,7 +113,7 @@ static struct recur_cache *recursive(char *s, char **words, int *sizes, int num, caches[index] = result; for (i = 0; i < num; i++) { if (!memcmp(s, words[i], sizes[i])) { - struct recur_cache *next = recursive(s + sizes[i], words, sizes, num, caches, len, index + sizes[i]); + struct dfs_cache *next = dfs(s + sizes[i], words, sizes, num, caches, index + sizes[i]); if (next != NULL) { int k = result->num; for (j = k; j < k + next->num; j++) { @@ -163,9 +156,9 @@ static bool wordBreak(char* s, char** wordDict, int wordDictSize) total += sizes[i]; } - struct recur_cache **caches = malloc(len * sizeof(*caches)); + struct dfs_cache **caches = malloc(len * sizeof(*caches)); memset(caches, 0, len * sizeof(*caches)); - return recursive(s, wordDict, sizes, wordDictSize, caches, len, 0) == NULL; + return dfs(s, wordDict, sizes, wordDictSize, caches, 0) == NULL; } int main(int argc, char **argv) diff --git a/140_word_break_ii/word_break.c b/140_word_break_ii/word_break.c index 97e4bac..2813c4f 100644 --- a/140_word_break_ii/word_break.c +++ b/140_word_break_ii/word_break.c @@ -2,24 +2,33 @@ #include #include +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define list_for_each(p, head) \ + for (p = (head)->next; p != (head); p = p->next) + +#define list_for_each_safe(p, n, head) \ + for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) + struct list_head { struct list_head *next, *prev; }; -static inline void -INIT_LIST_HEAD(struct list_head *list) +static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; } -static inline int -list_empty(const struct list_head *head) +static inline int list_empty(const struct list_head *head) { return (head->next == head); } -static inline void -__list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; @@ -27,59 +36,43 @@ __list_add(struct list_head *new, struct list_head *prev, struct list_head *next prev->next = new; } -static inline void -list_add(struct list_head *_new, struct list_head *head) +static inline void list_add(struct list_head *_new, struct list_head *head) { __list_add(_new, head, head->next); } -static inline void -list_add_tail(struct list_head *_new, struct list_head *head) +static inline void list_add_tail(struct list_head *_new, struct list_head *head) { __list_add(_new, head->prev, head); } -static inline void -__list_del(struct list_head *entry) +static inline void __list_del(struct list_head *entry) { entry->next->prev = entry->prev; entry->prev->next = entry->next; } -static inline void -list_del(struct list_head *entry) +static inline void list_del(struct list_head *entry) { __list_del(entry); entry->next = entry->prev = NULL; } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct word_node { char *word; struct list_head link; }; -struct recur_cache { +struct dfs_cache { int num; int cap; struct list_head **heads; }; -static struct recur_cache *resize(struct recur_cache **caches, int index) +static struct dfs_cache *resize(struct dfs_cache **caches, int index) { int i; - struct recur_cache *cache = caches[index]; + struct dfs_cache *cache = caches[index]; if (cache->num + 1 > cache->cap) { cache->cap *= 2; struct list_head **heads = malloc(cache->cap * sizeof(*heads)); @@ -98,12 +91,12 @@ static struct recur_cache *resize(struct recur_cache **caches, int index) return cache; } -static struct recur_cache *recursive(char *s, char **words, int *sizes, int num, - struct recur_cache **caches, int len, int index) +static struct dfs_cache *dfs(char *s, char **words, int *sizes, int num, + struct dfs_cache **caches, int index) { int i, j; struct word_node *wn; - struct recur_cache *result; + struct dfs_cache *result; if (*s == '\0') { return NULL; @@ -119,7 +112,7 @@ static struct recur_cache *recursive(char *s, char **words, int *sizes, int num, caches[index] = result; for (i = 0; i < num; i++) { if (!memcmp(s, words[i], sizes[i])) { - struct recur_cache *next = recursive(s + sizes[i], words, sizes, num, caches, len, index + sizes[i]); + struct dfs_cache *next = dfs(s + sizes[i], words, sizes, num, caches, index + sizes[i]); if (next != NULL) { int k = result->num; for (j = k; j < k + next->num; j++) { @@ -170,9 +163,9 @@ static char **wordBreak(char* s, char** wordDict, int wordDictSize, int *returnS total += sizes[i]; } - struct recur_cache **caches = malloc(len * sizeof(*caches)); + struct dfs_cache **caches = malloc(len * sizeof(*caches)); memset(caches, 0, len * sizeof(*caches)); - struct recur_cache *cache = recursive(s, wordDict, sizes, wordDictSize, caches, len, 0); + struct dfs_cache *cache = dfs(s, wordDict, sizes, wordDictSize, caches, 0); char **results = malloc(cache->num * sizeof(char *)); for (i = 0; i < cache->num; i++) { diff --git a/143_reorder_list/reorder_list.c b/143_reorder_list/reorder_list.c index a8d220a..4e98eec 100644 --- a/143_reorder_list/reorder_list.c +++ b/143_reorder_list/reorder_list.c @@ -29,14 +29,18 @@ static void reorderList(struct ListNode *head) int count = 0; struct ListNode *p = head; struct ListNode *q = p; + + /* locate half length */ for (; p != NULL; p = p->next) { if ((++count & 0x1) == 0) { q = q->next; } } + /* reverse latter half list */ reverse(q); + /* insert each element */ struct ListNode *r; for (p = head, r = q->next; r != NULL; p = r->next, r = q->next) { q->next = r->next; diff --git a/144_binary_tree_preorder_traversal/bst_preorder.c b/144_binary_tree_preorder_traversal/bst_preorder.c index 14e3f56..1a5e9a8 100644 --- a/144_binary_tree_preorder_traversal/bst_preorder.c +++ b/144_binary_tree_preorder_traversal/bst_preorder.c @@ -28,9 +28,11 @@ static int* preorderTraversal(struct TreeNode* root, int* returnSize) { } results[count++] = node->val; + if (node->right != NULL) { *top++ = node->right; } + node = node->left; } diff --git a/145_binary_tree_postorder_traversal/bst_postorder.c b/145_binary_tree_postorder_traversal/bst_postorder.c index f917af9..e54d3a8 100644 --- a/145_binary_tree_postorder_traversal/bst_postorder.c +++ b/145_binary_tree_postorder_traversal/bst_postorder.c @@ -12,6 +12,14 @@ struct node_backlog { struct TreeNode *right; }; +static int counting(struct TreeNode* node) +{ + if (node == NULL) { + return 0; + } + return 1 + counting(node->left) + counting(node->right); +} + /** ** Return an array of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). @@ -22,34 +30,32 @@ static int* postorderTraversal(struct TreeNode* root, int* returnSize) return NULL; } - int cap = 10000, count = 0; - int *results = malloc(cap * sizeof(int)); - struct node_backlog *stack = malloc(cap / 16 * sizeof(*stack)); + *returnSize = counting(root); + + int count = 0; + int *results = malloc(*returnSize * sizeof(int)); + struct node_backlog *stack = malloc(*returnSize * sizeof(*stack)); struct node_backlog *top = stack; struct TreeNode *node = root; - struct node_backlog nbl; while (node != NULL || top != stack) { if (node == NULL) { - nbl = *--top; - if (nbl.right != NULL) { - node = nbl.right; - nbl.right = NULL; - *top++ = nbl; + if ((top - 1)->right != NULL) { + node = (top - 1)->right; + (top - 1)->right = NULL; } else { - node = nbl.parent; + node = (--top)->parent; results[count++] = node->val; node = NULL; continue; } } - nbl.parent = node; - nbl.right = node->right; - *top++ = nbl; + top->parent = node; + top->right = node->right; + top++; node = node->left; } - *returnSize = count; return results; } diff --git a/146_lru_cache/lru_cache.c b/146_lru_cache/lru_cache.c index a11558f..9d45326 100644 --- a/146_lru_cache/lru_cache.c +++ b/146_lru_cache/lru_cache.c @@ -1,6 +1,27 @@ #include #include +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + +#define hlist_for_each_safe(pos, n, head) \ + for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) + +#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) +#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) + +#define list_for_each(p, head) \ + for (p = (head)->next; p != (head); p = p->next) + +#define list_for_each_safe(p, n, head) \ + for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) + struct hlist_node; struct hlist_head { @@ -15,11 +36,6 @@ static inline void INIT_HLIST_HEAD(struct hlist_head *h) { h->first = NULL; } -static inline void INIT_HLIST_NODE(struct hlist_node *n) { - n->next = NULL; - n->pprev = NULL; -} - static inline int hlist_empty(struct hlist_head *h) { return !h->first; } @@ -44,27 +60,6 @@ static inline void hlist_del(struct hlist_node *n) } } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - -#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) - -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct list_head { struct list_head *next, *prev; }; @@ -205,11 +200,7 @@ void lRUCachePut(LRUCache *obj, int key, int value) hlist_add_head(&cache->node, &obj->hhead[hash]); } else { cache = malloc(sizeof(LRUNode)); - INIT_HLIST_NODE(&cache->node); - INIT_LIST_HEAD(&cache->link); - /* Add into hash list */ hlist_add_head(&cache->node, &obj->hhead[hash]); - /* Add into double list */ list_add(&cache->link, &obj->dhead); obj->count++; } diff --git a/148_sort_list/sort_list.c b/148_sort_list/sort_list.c index 90d34f4..9673199 100644 --- a/148_sort_list/sort_list.c +++ b/148_sort_list/sort_list.c @@ -6,7 +6,7 @@ struct ListNode { struct ListNode *next; }; -static void recursive(struct ListNode *dummy, struct ListNode *end) +static void traverse(struct ListNode *dummy, struct ListNode *end) { if (dummy == NULL || dummy->next == end) { return; @@ -32,15 +32,15 @@ static void recursive(struct ListNode *dummy, struct ListNode *end) } } - recursive(dummy, pivot); - recursive(first, end); + traverse(dummy, pivot); + traverse(first, end); } static struct ListNode *sortList(struct ListNode *head) { struct ListNode dummy; dummy.next = head; - recursive(&dummy, NULL); + traverse(&dummy, NULL); return dummy.next; } diff --git a/164_maximum_gap/max_gap.c b/164_maximum_gap/max_gap.c index 00e9237..4303a31 100644 --- a/164_maximum_gap/max_gap.c +++ b/164_maximum_gap/max_gap.c @@ -2,6 +2,16 @@ #include #include +static inline int gt(int a, int b) +{ + return a > b ? a : b; +} + +static inline int lt(int a, int b) +{ + return a < b ? a : b; +} + static int maximumGap(int* nums, int numsSize) { if (numsSize < 2) { @@ -12,8 +22,8 @@ static int maximumGap(int* nums, int numsSize) int min = INT_MAX; int max = INT_MIN; for (i = 0; i < numsSize; i++) { - min = nums[i] < min ? nums[i] : min; - max = nums[i] > max ? nums[i] : max; + min = lt(nums[i], min); + max = gt(nums[i], max); } /* the max gap size must be larger than or equal to the average */ @@ -33,8 +43,8 @@ static int maximumGap(int* nums, int numsSize) for (i = 0; i < numsSize; i++) { int id = (nums[i] - min) / buck_size; - max_buck[id] = nums[i] > max_buck[id] ? nums[i] : max_buck[id]; - min_buck[id] = nums[i] < min_buck[id] ? nums[i] : min_buck[id]; + max_buck[id] = gt(nums[i], max_buck[id]); + min_buck[id] = lt(nums[i], min_buck[id]); } int max_gap = 0; @@ -47,7 +57,7 @@ static int maximumGap(int* nums, int numsSize) * bucket since the max gap must be larger or equal than the average * while the differences of elements in one bucket must less than * the average */ - max_gap = min_buck[i] - last_max > max_gap ? min_buck[i] - last_max : max_gap; + max_gap = gt(min_buck[i] - last_max, max_gap); last_max = max_buck[i]; } } diff --git a/179_largest_number/largest_number.c b/179_largest_number/largest_number.c index cdf5bb8..6eb31f3 100644 --- a/179_largest_number/largest_number.c +++ b/179_largest_number/largest_number.c @@ -4,57 +4,38 @@ struct object { char buf[16]; - int index; }; -static int compare(const char *c1, const char *c2) +static int compare(const void *o1, const void *o2) { char p1[32]; char p2[32]; p1[0] = '\0'; - p2[1] = '\0'; - strcat(p1, c1); - strcat(p1, c2); - strcat(p2, c2); - strcat(p2, c1); + p2[0] = '\0'; + strcat(p1, ((struct object *) o1)->buf); + strcat(p1, ((struct object *) o2)->buf); + strcat(p2, ((struct object *) o2)->buf); + strcat(p2, ((struct object *) o1)->buf); return strcmp(p1, p2); } -static void bubble_sort(struct object *objs, int size) -{ - int i, flag = size; - while (flag) { - int len = flag; - flag = 0; - for (i = 1; i < len; i++) { - if (compare(objs[i].buf, objs[i - 1].buf) > 0) { - struct object tmp = objs[i]; - objs[i] = objs[i - 1]; - objs[i - 1] = tmp; - flag = i; - } - } - } -} - static char* largestNumber(int* nums, int numsSize) { int i; struct object *objs = malloc(numsSize * sizeof(*objs)); memset(objs, 0, sizeof(*objs)); for (i = 0; i < numsSize; i++) { - objs[i].index = i; sprintf(objs[i].buf, "%d", nums[i]); } - bubble_sort(objs, numsSize); - if (objs[0].buf[0] == '0') { + qsort(objs, numsSize, sizeof(*objs), compare); + if (objs[numsSize - 1].buf[0] == '0') { return "0"; } char *result = malloc(numsSize * 16); result[0] = '\0'; - for (i = 0; i < numsSize; i++) { + for (i = numsSize - 1; i >= 0; i--) { strcat(result, objs[i].buf); } diff --git a/200_number_of_islands/islands.c b/200_number_of_islands/islands.c index 5dbb67d..7ab40ad 100644 --- a/200_number_of_islands/islands.c +++ b/200_number_of_islands/islands.c @@ -2,24 +2,24 @@ #include #include -static void recursive(char** grid, int row_size, int col_size, int row, int col) +static void dfs(char** grid, int row_size, int col_size, int row, int col) { grid[row][col] = '0'; if (row > 0 && grid[row - 1][col] == '1') { - recursive(grid, row_size, col_size, row - 1, col); + dfs(grid, row_size, col_size, row - 1, col); } if (row < row_size - 1 && grid[row + 1][col] == '1') { - recursive(grid, row_size, col_size, row + 1, col); + dfs(grid, row_size, col_size, row + 1, col); } if (col > 0 && grid[row][col - 1] == '1') { - recursive(grid, row_size, col_size, row, col - 1); + dfs(grid, row_size, col_size, row, col - 1); } if (col < col_size - 1 && grid[row][col + 1] == '1') { - recursive(grid, row_size, col_size, row, col + 1); + dfs(grid, row_size, col_size, row, col + 1); } } @@ -29,7 +29,7 @@ static int numIslands(char** grid, int gridRowSize, int gridColSize) for (i = 0; i < gridRowSize; i++) { for (j = 0; j < gridColSize; j++) { if (grid[i][j] == '1') { - recursive(grid, gridRowSize, gridColSize, i, j); + dfs(grid, gridRowSize, gridColSize, i, j); count++; } } diff --git a/214_shortest_palindrome/shortest_palindrome.c b/214_shortest_palindrome/shortest_palindrome.c index e754b96..3440488 100644 --- a/214_shortest_palindrome/shortest_palindrome.c +++ b/214_shortest_palindrome/shortest_palindrome.c @@ -32,6 +32,11 @@ static char *shortestPalindrome(char *s) next[i] = j; } + for (i = 0; i < res_len; i++) { + printf("%d ", next[i]); + } + printf("\n"); + memmove(result, result + len + 1, len + 1); int start = len - next[res_len - 1]; strcpy(result + start, s); From ce1341340725c92ca2b4bd471322379f313ef8fe Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 5 Jan 2018 17:45:57 +0800 Subject: [PATCH 029/211] Improve Signed-off-by: begeekmyfriend --- {052_n_queens => 052_n_queens_ii}/Makefile | 0 {052_n_queens => 052_n_queens_ii}/n_queens.c | 0 133_clone_graph/clone_graph.c | 5 - 149_max_points_on_a_line/points_on_line.c | 29 +++--- 207_course_schedule/Makefile | 2 + 207_course_schedule/course_schedule.c | 90 ++++++++++++++++++ 210_course_schedule_ii/Makefile | 2 + 210_course_schedule_ii/course_schedule.c | 97 ++++++++++++++++++++ 8 files changed, 203 insertions(+), 22 deletions(-) rename {052_n_queens => 052_n_queens_ii}/Makefile (100%) rename {052_n_queens => 052_n_queens_ii}/n_queens.c (100%) create mode 100644 207_course_schedule/Makefile create mode 100644 207_course_schedule/course_schedule.c create mode 100644 210_course_schedule_ii/Makefile create mode 100644 210_course_schedule_ii/course_schedule.c diff --git a/052_n_queens/Makefile b/052_n_queens_ii/Makefile similarity index 100% rename from 052_n_queens/Makefile rename to 052_n_queens_ii/Makefile diff --git a/052_n_queens/n_queens.c b/052_n_queens_ii/n_queens.c similarity index 100% rename from 052_n_queens/n_queens.c rename to 052_n_queens_ii/n_queens.c diff --git a/133_clone_graph/clone_graph.c b/133_clone_graph/clone_graph.c index 30ad891..e6ef47c 100644 --- a/133_clone_graph/clone_graph.c +++ b/133_clone_graph/clone_graph.c @@ -29,11 +29,6 @@ static inline void INIT_HLIST_HEAD(struct hlist_head *h) { h->first = NULL; } -static inline void INIT_HLIST_NODE(struct hlist_node *n) { - n->next = NULL; - n->pprev = NULL; -} - static inline int hlist_empty(struct hlist_head *h) { return !h->first; } diff --git a/149_max_points_on_a_line/points_on_line.c b/149_max_points_on_a_line/points_on_line.c index 25388f6..96c0122 100644 --- a/149_max_points_on_a_line/points_on_line.c +++ b/149_max_points_on_a_line/points_on_line.c @@ -3,6 +3,18 @@ #include #include +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos; pos = pos->next) + +#define hlist_for_each_safe(pos, n, head) \ + for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) + struct hlist_node; struct hlist_head { @@ -17,11 +29,6 @@ static inline void INIT_HLIST_HEAD(struct hlist_head *h) { h->first = NULL; } -static inline void INIT_HLIST_NODE(struct hlist_node *n) { - n->next = NULL; - n->pprev = NULL; -} - static inline int hlist_empty(struct hlist_head *h) { return !h->first; } @@ -46,18 +53,6 @@ static inline void hlist_del(struct hlist_node *n) } } -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - struct Point { int x, y; }; diff --git a/207_course_schedule/Makefile b/207_course_schedule/Makefile new file mode 100644 index 0000000..0657996 --- /dev/null +++ b/207_course_schedule/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test course_schedule.c diff --git a/207_course_schedule/course_schedule.c b/207_course_schedule/course_schedule.c new file mode 100644 index 0000000..9c70d71 --- /dev/null +++ b/207_course_schedule/course_schedule.c @@ -0,0 +1,90 @@ +#include +#include +#include +#include + +enum { + RET_FAILURE = -1, + RET_OK, + RET_IGNORE, +}; + +struct graph_node { + int req_num; + int reqs[15]; +}; + +#define N 2000 +static struct graph_node courses[N]; +static bool takens[N]; +static bool touched[N]; + +static int dfs(struct graph_node *courses, int id, bool *takens, bool *touched) +{ + int i; + if (touched[id]) { + return RET_IGNORE; + } else if (takens[id]) { + return RET_FAILURE; + } else { + takens[id] = true; + for (i = 0; i < courses[id].req_num; i++) { + int ret = dfs(courses, courses[id].reqs[i], takens, touched); + if (ret == RET_FAILURE) { + return ret; + } + } + /* marked as available and no need to traverse next time */ + touched[id] = true; + takens[id] = false; + return RET_OK; + } +} + +static bool canFinish(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize) +{ + int i; + memset(courses, 0, numCourses * sizeof(*courses)); + memset(takens, false, numCourses * sizeof(bool)); + memset(touched, false, numCourses * sizeof(bool)); + + for (i = 0; i < prerequisitesRowSize; i++) { + int id = prerequisites[i][0]; + int req = prerequisites[i][1]; + courses[id].reqs[courses[id].req_num++] = req; + } + + for (i = 0; i < numCourses; i++) { + if (dfs(courses, i, takens, touched) < 0) { + return false; + } + } + + return true; +} + +int main(void) +{ + int i, course_num = 6, pair_num = 6; + int **pairs = malloc(pair_num * sizeof(int *)); + pairs[0] = malloc(2 * sizeof(int)); + pairs[0][0] = 1; + pairs[0][1] = 0; + pairs[1] = malloc(2 * sizeof(int)); + pairs[1][0] = 2; + pairs[1][1] = 1; + pairs[2] = malloc(2 * sizeof(int)); + pairs[2][0] = 3; + pairs[2][1] = 2; + pairs[3] = malloc(2 * sizeof(int)); + pairs[3][0] = 1; + pairs[3][1] = 3; + pairs[4] = malloc(2 * sizeof(int)); + pairs[4][0] = 4; + pairs[4][1] = 0; + pairs[5] = malloc(2 * sizeof(int)); + pairs[5][0] = 0; + pairs[5][1] = 5; + printf("%s\n", canFinish(course_num, pairs, pair_num, 2) ? "true" : "false"); + return 0; +} diff --git a/210_course_schedule_ii/Makefile b/210_course_schedule_ii/Makefile new file mode 100644 index 0000000..0657996 --- /dev/null +++ b/210_course_schedule_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test course_schedule.c diff --git a/210_course_schedule_ii/course_schedule.c b/210_course_schedule_ii/course_schedule.c new file mode 100644 index 0000000..5d964cf --- /dev/null +++ b/210_course_schedule_ii/course_schedule.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include + +enum { + RET_FAILURE = -1, + RET_OK, + RET_IGNORE, +}; + +struct graph_node { + int req_num; + int reqs[15]; +}; + +static int dfs(struct graph_node *courses, int id, bool *takens, bool *touched, int *order, int *count) +{ + int i; + if (touched[id]) { + return RET_IGNORE; + } else if (takens[id]) { + return RET_FAILURE; + } else { + takens[id] = true; + for (i = 0; i < courses[id].req_num; i++) { + int ret = dfs(courses, courses[id].reqs[i], takens, touched, order, count); + if (ret == RET_FAILURE) { + return ret; + } + } + /* marked as available and no need to traverse next time */ + order[(*count)++] = id; + touched[id] = true; + takens[id] = false; + return RET_OK; + } +} + +#define N 2000 +static int order[N]; +static struct graph_node courses[N]; +static bool takens[N]; +static bool touched[N]; + +static int *findOrder(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize, int *returnSize) +{ + int i; + memset(courses, 0, numCourses * sizeof(*courses)); + memset(takens, false, numCourses * sizeof(bool)); + memset(touched, false, numCourses * sizeof(bool)); + + for (i = 0; i < prerequisitesRowSize; i++) { + int id = prerequisites[i][0]; + int req = prerequisites[i][1]; + courses[id].reqs[courses[id].req_num++] = req; + } + + *returnSize = 0; + for (i = 0; i < numCourses; i++) { + if (dfs(courses, i, takens, touched, order, returnSize) < 0) { + *returnSize = 0; + return order; + } + } + + return order; +} + +int main(void) +{ + int i, course_num = 3, pair_num = 1; + int **pairs = malloc(pair_num * sizeof(int *)); + pairs[0] = malloc(2 * sizeof(int)); + pairs[0][0] = 1; + pairs[0][1] = 0; + //pairs[1] = malloc(2 * sizeof(int)); + //pairs[1][0] = 2; + //pairs[1][1] = 1; + //pairs[2] = malloc(2 * sizeof(int)); + //pairs[2][0] = 3; + //pairs[2][1] = 2; + //pairs[3] = malloc(2 * sizeof(int)); + //pairs[3][0] = 4; + //pairs[3][1] = 0; + //pairs[4] = malloc(2 * sizeof(int)); + //pairs[4][0] = 0; + //pairs[4][1] = 5; + + int count = 0; + int *ids = findOrder(course_num, pairs, pair_num, 2, &count); + for (i = 0; i < count; i++) { + printf("%d ", ids[i]); + } + printf("\n"); + return 0; +} From da962db4bb3396cc1e09f5e8d8c507d479439900 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 7 Jan 2018 01:08:20 +0800 Subject: [PATCH 030/211] Improve Signed-off-by: Leo Ma --- 202_happy_number/Makefile | 2 + 202_happy_number/happy_number.c | 37 ++++++++++++++ 203_remove_linked_list_element/Makefile | 2 + 203_remove_linked_list_element/rm_elem.c | 53 +++++++++++++++++++++ 204_count_primes/Makefile | 2 + 204_count_primes/count_primes.c | 37 ++++++++++++++ 205_isomorphic_strings/1 | 0 205_isomorphic_strings/Makefile | 2 + 205_isomorphic_strings/isomorphic_strings.c | 32 +++++++++++++ 206_reverse_linked_list/Makefile | 2 + 206_reverse_linked_list/reverse_list.c | 52 ++++++++++++++++++++ 207_course_schedule/course_schedule.c | 31 +++++------- 210_course_schedule_ii/course_schedule.c | 25 +++++----- 13 files changed, 244 insertions(+), 33 deletions(-) create mode 100644 202_happy_number/Makefile create mode 100644 202_happy_number/happy_number.c create mode 100644 203_remove_linked_list_element/Makefile create mode 100644 203_remove_linked_list_element/rm_elem.c create mode 100644 204_count_primes/Makefile create mode 100644 204_count_primes/count_primes.c create mode 100644 205_isomorphic_strings/1 create mode 100644 205_isomorphic_strings/Makefile create mode 100644 205_isomorphic_strings/isomorphic_strings.c create mode 100644 206_reverse_linked_list/Makefile create mode 100644 206_reverse_linked_list/reverse_list.c diff --git a/202_happy_number/Makefile b/202_happy_number/Makefile new file mode 100644 index 0000000..7b43a8a --- /dev/null +++ b/202_happy_number/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test happy_number.c diff --git a/202_happy_number/happy_number.c b/202_happy_number/happy_number.c new file mode 100644 index 0000000..9e4d9e8 --- /dev/null +++ b/202_happy_number/happy_number.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +static bool recursive(int n, bool *used, const int *sq) +{ + if (n == 1) return true; + if (n < 10000) { + if (used[n]) return false; + used[n] = true; + } + int sum = 0; + while (n > 0) { + sum += sq[n % 10]; + n /= 10; + } + return recursive(sum, used, sq); +} + +static bool isHappy(int n) +{ + bool used[10000] = { false }; + const static int sq[10] = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 }; + return recursive(n, used, sq); +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test n\n"); + exit(-1); + } + + printf("%s\n", isHappy(atoi(argv[1])) ? "true" : "false"); + return 0; +} diff --git a/203_remove_linked_list_element/Makefile b/203_remove_linked_list_element/Makefile new file mode 100644 index 0000000..210f162 --- /dev/null +++ b/203_remove_linked_list_element/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test rm_elem.c diff --git a/203_remove_linked_list_element/rm_elem.c b/203_remove_linked_list_element/rm_elem.c new file mode 100644 index 0000000..0834a82 --- /dev/null +++ b/203_remove_linked_list_element/rm_elem.c @@ -0,0 +1,53 @@ +#include +#include + +struct ListNode { + int val; + struct ListNode *next; +}; + +static struct ListNode *removeElement(struct ListNode *head, int val) +{ + struct ListNode dummy; + dummy.next = head; + struct ListNode *prev = &dummy; + struct ListNode *p = head; + while (p != NULL) { + if (p->val == val) { + prev->next = p->next; + } else { + prev = p; + } + p = p->next; + } + return dummy.next; +} + +int main(int argc, char **argv) +{ + if (argc < 3) { + fprintf(stderr, "Usage: ./test value n1 n2 n3...\n"); + exit(-1); + } + + int value = atoi(argv[1]); + int i, count = argc - 2; + struct ListNode *head = NULL, *p, *prev; + for (i = 0; i < count; i++) { + p = malloc(sizeof(*p)); + p->val = atoi(argv[i + 2]); + p->next = NULL; + if (head == NULL) { + head = p; + } else { + prev->next = p; + } + prev = p; + } + + for (p = removeElement(head, value); p != NULL; p = p->next) { + printf("%d ", p->val); + } + printf("\n"); + return 0; +} diff --git a/204_count_primes/Makefile b/204_count_primes/Makefile new file mode 100644 index 0000000..0937319 --- /dev/null +++ b/204_count_primes/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test count_primes.c diff --git a/204_count_primes/count_primes.c b/204_count_primes/count_primes.c new file mode 100644 index 0000000..f64c6e6 --- /dev/null +++ b/204_count_primes/count_primes.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +static int countPrimes(int n) +{ + if (n < 3) return 0; + + int i, j; + bool *marked = malloc(n); + memset(marked, false, n); + int count = n >> 1; + + for (i = 3; i * i <= n; i += 2) { + if (!marked[i]) { + for (j = i * i; j < n; j += (i << 1)) { + if (!marked[j]) { + marked[j] = true; + --count; + } + } + } + } + return count; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test n\n"); + exit(-1); + } + + printf("%d\n", countPrimes(atoi(argv[1]))); + return 0; +} diff --git a/205_isomorphic_strings/1 b/205_isomorphic_strings/1 new file mode 100644 index 0000000..e69de29 diff --git a/205_isomorphic_strings/Makefile b/205_isomorphic_strings/Makefile new file mode 100644 index 0000000..ef9f896 --- /dev/null +++ b/205_isomorphic_strings/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test isomorphic_strings.c diff --git a/205_isomorphic_strings/isomorphic_strings.c b/205_isomorphic_strings/isomorphic_strings.c new file mode 100644 index 0000000..692713a --- /dev/null +++ b/205_isomorphic_strings/isomorphic_strings.c @@ -0,0 +1,32 @@ +#include +#include +#include + +static bool isIsomorphic(char *s, char *t) +{ + int i; + char smap[128] = { '\0' }; + char tmap[128] = { '\0' }; + while (*s != '\0' && *t != '\0') { + if ((smap[*s] != '\0' && smap[*s] != *t) || + (tmap[*t] != '\0' && tmap[*t] != *s)) { + return false; + } + smap[*s] = *t; + tmap[*t] = *s; + s++; + t++; + } + return *s == *t; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test s1 s2\n"); + exit(-1); + } + + printf("%s\n", isIsomorphic(argv[1], argv[2]) ? "true" : "false"); + return 0; +} diff --git a/206_reverse_linked_list/Makefile b/206_reverse_linked_list/Makefile new file mode 100644 index 0000000..d480ecf --- /dev/null +++ b/206_reverse_linked_list/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test reverse_list.c diff --git a/206_reverse_linked_list/reverse_list.c b/206_reverse_linked_list/reverse_list.c new file mode 100644 index 0000000..ed76673 --- /dev/null +++ b/206_reverse_linked_list/reverse_list.c @@ -0,0 +1,52 @@ +#include +#include + +struct ListNode { + int val; + struct ListNode *next; +}; + +static void recursive(struct ListNode *dummy, struct ListNode *prev, struct ListNode *p) +{ + if (p != NULL) { + prev->next = p->next; + p->next = dummy->next; + dummy->next = p; + recursive(dummy, prev, prev->next); + } +} + +static struct ListNode *reverseList(struct ListNode *head) +{ + if (head == NULL) { + return NULL; + } + + struct ListNode dummy; + dummy.next = head; + recursive(&dummy, head, head->next); + return dummy.next; +} + +int main(int argc, char **argv) +{ + int i, count = argc - 1; + struct ListNode *head = NULL, *p, *prev; + for (i = 0; i < count; i++) { + p = malloc(sizeof(*p)); + p->val = atoi(argv[i + 1]); + p->next = NULL; + if (head == NULL) { + head = p; + } else { + prev->next = p; + } + prev = p; + } + + for (p = reverseList(head); p != NULL; p = p->next) { + printf("%d ", p->val); + } + printf("\n"); + return 0; +} diff --git a/207_course_schedule/course_schedule.c b/207_course_schedule/course_schedule.c index 9c70d71..b37bc23 100644 --- a/207_course_schedule/course_schedule.c +++ b/207_course_schedule/course_schedule.c @@ -3,44 +3,37 @@ #include #include -enum { - RET_FAILURE = -1, - RET_OK, - RET_IGNORE, -}; - struct graph_node { int req_num; int reqs[15]; }; -#define N 2000 -static struct graph_node courses[N]; -static bool takens[N]; -static bool touched[N]; - -static int dfs(struct graph_node *courses, int id, bool *takens, bool *touched) +static bool dfs(struct graph_node *courses, int id, bool *takens, bool *touched) { int i; if (touched[id]) { - return RET_IGNORE; + return true; } else if (takens[id]) { - return RET_FAILURE; + return false; } else { takens[id] = true; for (i = 0; i < courses[id].req_num; i++) { - int ret = dfs(courses, courses[id].reqs[i], takens, touched); - if (ret == RET_FAILURE) { - return ret; + if (!dfs(courses, courses[id].reqs[i], takens, touched)) { + return false; } } /* marked as available and no need to traverse next time */ touched[id] = true; takens[id] = false; - return RET_OK; + return true; } } +#define N 2000 +static struct graph_node courses[N]; +static bool takens[N]; +static bool touched[N]; + static bool canFinish(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize) { int i; @@ -55,7 +48,7 @@ static bool canFinish(int numCourses, int** prerequisites, int prerequisitesRowS } for (i = 0; i < numCourses; i++) { - if (dfs(courses, i, takens, touched) < 0) { + if (!dfs(courses, i, takens, touched)) { return false; } } diff --git a/210_course_schedule_ii/course_schedule.c b/210_course_schedule_ii/course_schedule.c index 5d964cf..fdc4159 100644 --- a/210_course_schedule_ii/course_schedule.c +++ b/210_course_schedule_ii/course_schedule.c @@ -3,37 +3,30 @@ #include #include -enum { - RET_FAILURE = -1, - RET_OK, - RET_IGNORE, -}; - struct graph_node { int req_num; int reqs[15]; }; -static int dfs(struct graph_node *courses, int id, bool *takens, bool *touched, int *order, int *count) +static bool dfs(struct graph_node *courses, int id, bool *takens, bool *touched, int *order, int *count) { int i; if (touched[id]) { - return RET_IGNORE; + return true; } else if (takens[id]) { - return RET_FAILURE; + return false; } else { takens[id] = true; for (i = 0; i < courses[id].req_num; i++) { - int ret = dfs(courses, courses[id].reqs[i], takens, touched, order, count); - if (ret == RET_FAILURE) { - return ret; + if (!dfs(courses, courses[id].reqs[i], takens, touched, order, count)) { + return false; } } /* marked as available and no need to traverse next time */ order[(*count)++] = id; touched[id] = true; takens[id] = false; - return RET_OK; + return true; } } @@ -43,6 +36,10 @@ static struct graph_node courses[N]; static bool takens[N]; static bool touched[N]; +/** + * Return an array of size *returnSize. + * Note: The returned array must be malloced, assume caller calls free(). + */ static int *findOrder(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize, int *returnSize) { int i; @@ -58,7 +55,7 @@ static int *findOrder(int numCourses, int** prerequisites, int prerequisitesRowS *returnSize = 0; for (i = 0; i < numCourses; i++) { - if (dfs(courses, i, takens, touched, order, returnSize) < 0) { + if (!dfs(courses, i, takens, touched, order, returnSize)) { *returnSize = 0; return order; } From 895c3706f1831e336a8b1dd0069e2f86a2a7ccaf Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 7 Jan 2018 01:29:01 +0800 Subject: [PATCH 031/211] Combination sum Signed-off-by: Leo Ma --- 039_combination_sum/combination_sum.c | 4 +- 040_combination_sum_ii/combination_sum.c | 5 ++ 216_combination_sum_iii/Makefile | 2 + 216_combination_sum_iii/combination_sum.c | 65 +++++++++++++++++++++++ 4 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 216_combination_sum_iii/Makefile create mode 100644 216_combination_sum_iii/combination_sum.c diff --git a/039_combination_sum/combination_sum.c b/039_combination_sum/combination_sum.c index d47dcb6..8ec6845 100644 --- a/039_combination_sum/combination_sum.c +++ b/039_combination_sum/combination_sum.c @@ -40,8 +40,8 @@ static int** combinationSum(int* candidates, int candidatesSize, int target, int int main(int argc, char **argv) { - if (argc <= 2) { - fprintf(stderr, "Usage: ./test target array...\n"); + if (argc < 3) { + fprintf(stderr, "Usage: ./test target n1 n2...\n"); exit(-1); } diff --git a/040_combination_sum_ii/combination_sum.c b/040_combination_sum_ii/combination_sum.c index bf62cae..5ffa641 100644 --- a/040_combination_sum_ii/combination_sum.c +++ b/040_combination_sum_ii/combination_sum.c @@ -51,6 +51,11 @@ static int** combinationSum(int* candidates, int candidatesSize, int target, int int main(int argc, char **argv) { + if (argc < 3) { + fprintf(stderr, "Usage: ./test target n1 n2...\n"); + exit(-1); + } + int i, j, count = 0; int target = atoi(argv[1]); int *nums = malloc((argc - 2) * sizeof(int)); diff --git a/216_combination_sum_iii/Makefile b/216_combination_sum_iii/Makefile new file mode 100644 index 0000000..e5462fa --- /dev/null +++ b/216_combination_sum_iii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test combination_sum.c diff --git a/216_combination_sum_iii/combination_sum.c b/216_combination_sum_iii/combination_sum.c new file mode 100644 index 0000000..52b124e --- /dev/null +++ b/216_combination_sum_iii/combination_sum.c @@ -0,0 +1,65 @@ +#include +#include +#include +#include + +static void dfs(int *nums, int size, int start, int target, int num, + int *solution, int len, int **results, int *column_sizes, int *count) +{ + int i; + if (len == num) { + if (target == 0) { + results[*count] = malloc(len * sizeof(int)); + memcpy(results[*count], solution, len * sizeof(int)); + column_sizes[*count] = len; + (*count)++; + } + } else if (target > 0) { + for (i = start; i < size; i++) { + solution[len] = nums[i]; + dfs(nums, size, i + 1, target - nums[i], num, solution, len + 1, results, column_sizes, count); + } + } +} + +/** + ** Return an array of arrays of size *returnSize. + ** The sizes of the arrays are returned as *columnSizes array. + ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + **/ +static int** combinationSum3(int k, int n, int** columnSizes, int* returnSize) +{ + int i, count = 9; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = i + 1; + } + + int *solution = malloc(k * sizeof(int)); + int **results = malloc(100 * sizeof(int *)); + *columnSizes = malloc(100 * sizeof(int)); + *returnSize = 0; + dfs(nums, count, 0, n, k, solution, 0, results, *columnSizes, returnSize); + return results; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test k n\n"); + exit(-1); + } + + int i, j; + int k = atoi(argv[1]); + int n = atoi(argv[2]); + int *sizes, count = 0; + int **lists = combinationSum3(k, n, &sizes, &count); + for (i = 0; i < count; i++) { + for (j = 0; j < sizes[i]; j++) { + printf("%d ", lists[i][j]); + } + printf("\n"); + } + return 0; +} From ec051ec36339b2c0b8a7adabb9c6e7bfb1280947 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 7 Jan 2018 13:34:55 +0800 Subject: [PATCH 032/211] Word Search Signed-off-by: Leo Ma --- 079_word_search/word_search.c | 3 +- 212_word_search_ii/Makefile | 2 + 212_word_search_ii/word_search.c | 196 +++++++++++++++++++++++++++++++ 3 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 212_word_search_ii/Makefile create mode 100644 212_word_search_ii/word_search.c diff --git a/079_word_search/word_search.c b/079_word_search/word_search.c index c4bf7bd..6394a19 100644 --- a/079_word_search/word_search.c +++ b/079_word_search/word_search.c @@ -37,7 +37,8 @@ static bool dfs(char *word, char **board, bool *used, return result; } -static bool exist(char** board, int boardRowSize, int boardColSize, char* word) { +static bool exist(char** board, int boardRowSize, int boardColSize, char* word) +{ int i, j; int len = strlen(word); if (len > boardRowSize * boardColSize) { diff --git a/212_word_search_ii/Makefile b/212_word_search_ii/Makefile new file mode 100644 index 0000000..99bef24 --- /dev/null +++ b/212_word_search_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test word_search.c diff --git a/212_word_search_ii/word_search.c b/212_word_search_ii/word_search.c new file mode 100644 index 0000000..54d78a1 --- /dev/null +++ b/212_word_search_ii/word_search.c @@ -0,0 +1,196 @@ +#include +#include +#include +#include + +struct trie { + struct trie *subs[27]; + char letters[27]; + int num; +}; + +static struct trie* trie_create() +{ + struct trie *obj = malloc(sizeof(*obj)); + memset(obj->letters, 0xff, sizeof(obj->letters)); + memset(&obj->subs[0], 0, sizeof(obj->subs)); + obj->num = 0; + return obj; +} + +static void trie_insert(struct trie* obj, char* word) +{ + while (*word != '\0') { + int pos = *word - 'a' + 1; + obj->letters[pos] = *word++; + obj->num++; + if (obj->subs[pos] == NULL) { + obj->subs[pos] = trie_create(); + } + obj = obj->subs[pos]; + } + obj->letters[0] = '\0'; +} + +static void trie_remove(struct trie* obj, char* word) +{ + while (obj != NULL && *word != '\0') { + int pos = *word++ - 'a' + 1; + if (--obj->num == 0) { + obj->letters[pos] = 0xff; + } + obj = obj->subs[pos]; + } + if (obj != NULL) { + obj->letters[0] = 0xff; + } +} + +static void dfs(char **board, int row_size, int col_size, int row, int col, struct trie *node, + char *word, int len, bool *used, char **results, int *count, struct trie *root, int *wordsSize) +{ + char c = board[row][col]; + int index = c - 'a' + 1; + + if (node == NULL || node->letters[index] == -1) { + return; + } + + printf("%d %d\n", row, col); + word[len] = c; + + struct trie *sub = node->subs[index]; + if (sub != NULL && sub->letters[0] == '\0') { + word[len + 1] = '\0'; + results[*count] = malloc(len + 2); + strcpy(results[*count], word); + (*count)++; + trie_remove(root, word); + (*wordsSize)--; + printf("%s\n", word); + } + + used[row * col_size + col] = true; + + if (row > 0 && !used[(row - 1) * col_size + col]) { + dfs(board, row_size, col_size, row - 1, col, node->subs[index], word, len + 1, used, results, count, root, wordsSize); + } + + if (row < row_size - 1 && !used[(row + 1) * col_size + col]) { + dfs(board, row_size, col_size, row + 1, col, node->subs[index], word, len + 1, used, results, count, root, wordsSize); + } + + if (col > 0 && !used[row * col_size + col - 1]) { + dfs(board, row_size, col_size, row, col - 1, node->subs[index], word, len + 1, used, results, count, root, wordsSize); + } + + if (col < col_size - 1 && !used[row * col_size + col + 1]) { + dfs(board, row_size, col_size, row, col + 1, node->subs[index], word, len + 1, used, results, count, root, wordsSize); + } + + used[row * col_size + col] = false; +} + +/** + * Return an array of size *returnSize. + * Note: The returned array must be malloced, assume caller calls free(). + */ +static char **findWords(char** board, int boardRowSize, int boardColSize, char** words, int wordsSize, int* returnSize) +{ + int i, j, cap = 5000; + struct trie *root = trie_create(); + for (i = 0; i < wordsSize; i++) { + trie_insert(root, words[i]); + } + + *returnSize = 0; + char *word = malloc(boardRowSize * boardColSize + 1); + memset(word, 0, boardRowSize * boardColSize + 1); + char **results = malloc(cap * sizeof(char *)); + bool *used = malloc(boardRowSize * boardColSize); + memset(used, false, boardRowSize * boardColSize); + for (i = 0; i < boardRowSize; i++) { + for (j = 0; j < boardColSize; j++) { + if (wordsSize == 0) { + return results; + } + dfs(board, boardRowSize, boardColSize, i, j, root, word, 0, used, results, returnSize, root, &wordsSize); + } + } + return results; +} + +int main(void) +{ + int i; +#if 0 + int row = 4; + int col = 4; + char **board = malloc(row * sizeof(char *)); + board[0] = malloc(col); + board[0][0] = 'o'; + board[0][1] = 'a'; + board[0][2] = 'a'; + board[0][3] = 'n'; + board[1] = malloc(col); + board[1][0] = 'e'; + board[1][1] = 't'; + board[1][2] = 'a'; + board[1][3] = 'e'; + board[2] = malloc(col); + board[2][0] = 'i'; + board[2][1] = 'h'; + board[2][2] = 'k'; + board[2][3] = 'r'; + board[3] = malloc(col); + board[3][0] = 'i'; + board[3][1] = 'f'; + board[3][2] = 'l'; + board[3][3] = 'v'; + + int size = 4; + char **words = malloc(size * sizeof(char *)); + words[0] = malloc(5); + strcpy(words[0], "oath"); + words[1] = malloc(5); + strcpy(words[1], "pea"); + words[2] = malloc(5); + strcpy(words[2], "eat"); + words[3] = malloc(5); + strcpy(words[3], "rain"); +#else + int row = 2; + int col = 2; + char **board = malloc(row * sizeof(char *)); + board[0] = malloc(col); + board[0][0] = 'a'; + board[0][1] = 'b'; + board[1] = malloc(col); + board[1][0] = 'a'; + board[1][1] = 'a'; + + int size = 7; + char **words = malloc(size * sizeof(char *)); + words[0] = malloc(5); + words[1] = malloc(5); + words[2] = malloc(5); + words[3] = malloc(5); + words[4] = malloc(5); + words[5] = malloc(5); + words[6] = malloc(5); + strcpy(words[0], "aba"); + strcpy(words[1], "baa"); + strcpy(words[2], "bab"); + strcpy(words[3], "aaab"); + strcpy(words[4], "aaa"); + strcpy(words[5], "aaaa"); + strcpy(words[6], "aaba"); +#endif + + int count = 0; + char **lists = findWords(board, row, col, words, size, &count); + for (i = 0; i < count; i++) { + printf("%s\n", lists[i]); + } + return 0; +} From fc02ac6a917422232aaddc387c2525fb043419c7 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 7 Jan 2018 13:35:27 +0800 Subject: [PATCH 033/211] Improve Signed-off-by: Leo Ma --- 205_isomorphic_strings/1 | 0 207_course_schedule/course_schedule.c | 9 ++-- 210_course_schedule_ii/course_schedule.c | 11 ++--- 239_sliding_window_maximum/Makefile | 2 + 239_sliding_window_maximum/slide_window.c | 56 +++++++++++++++++++++++ 5 files changed, 67 insertions(+), 11 deletions(-) delete mode 100644 205_isomorphic_strings/1 create mode 100644 239_sliding_window_maximum/Makefile create mode 100644 239_sliding_window_maximum/slide_window.c diff --git a/205_isomorphic_strings/1 b/205_isomorphic_strings/1 deleted file mode 100644 index e69de29..0000000 diff --git a/207_course_schedule/course_schedule.c b/207_course_schedule/course_schedule.c index b37bc23..7a7c325 100644 --- a/207_course_schedule/course_schedule.c +++ b/207_course_schedule/course_schedule.c @@ -29,14 +29,13 @@ static bool dfs(struct graph_node *courses, int id, bool *takens, bool *touched) } } -#define N 2000 -static struct graph_node courses[N]; -static bool takens[N]; -static bool touched[N]; - static bool canFinish(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize) { int i; + bool *takens = malloc(numCourses); + bool *touched = malloc(numCourses); + struct graph_node *courses = malloc(numCourses * sizeof(*courses)); + memset(courses, 0, numCourses * sizeof(*courses)); memset(takens, false, numCourses * sizeof(bool)); memset(touched, false, numCourses * sizeof(bool)); diff --git a/210_course_schedule_ii/course_schedule.c b/210_course_schedule_ii/course_schedule.c index fdc4159..5ecd140 100644 --- a/210_course_schedule_ii/course_schedule.c +++ b/210_course_schedule_ii/course_schedule.c @@ -30,12 +30,6 @@ static bool dfs(struct graph_node *courses, int id, bool *takens, bool *touched, } } -#define N 2000 -static int order[N]; -static struct graph_node courses[N]; -static bool takens[N]; -static bool touched[N]; - /** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). @@ -43,6 +37,11 @@ static bool touched[N]; static int *findOrder(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize, int *returnSize) { int i; + int *order = malloc(numCourses * sizeof(int)); + bool *takens = malloc(numCourses); + bool *touched = malloc(numCourses); + struct graph_node *courses = malloc(numCourses * sizeof(*courses)); + memset(courses, 0, numCourses * sizeof(*courses)); memset(takens, false, numCourses * sizeof(bool)); memset(touched, false, numCourses * sizeof(bool)); diff --git a/239_sliding_window_maximum/Makefile b/239_sliding_window_maximum/Makefile new file mode 100644 index 0000000..3ef9a2f --- /dev/null +++ b/239_sliding_window_maximum/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test slide_window.c diff --git a/239_sliding_window_maximum/slide_window.c b/239_sliding_window_maximum/slide_window.c new file mode 100644 index 0000000..4e7ded9 --- /dev/null +++ b/239_sliding_window_maximum/slide_window.c @@ -0,0 +1,56 @@ +#include +#include + +/** + * Return an array of size *returnSize. + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) +{ + int i, head = 0, tail = 0; + int count = 0; + int *indexes = malloc(numsSize * sizeof(int)); + int *results = malloc((numsSize - k + 1) * sizeof(int)); + + for (i = 0; i < numsSize; i++) { + /* monotonous decreasing */ + while (tail > head && nums[i] >= nums[indexes[tail - 1]]) { + tail--; + } + indexes[tail++] = i; + + if (indexes[head] <= i - k) { + head++; + } + + if (i >= k - 1) { + results[count++] = nums[indexes[head]]; + } + } + + *returnSize = count; + return results; +} + +int main(int argc, char **argv) +{ + if (argc < 2) { + fprintf(stderr, "Usage: ./test k n1 n2...\n"); + exit(-1); + } + + int i, size = argc - 2; + int k = atoi(argv[1]); + int *nums = malloc(size * sizeof(int)); + for (i = 0; i < size; i++) { + nums[i] = atoi(argv[i + 2]); + } + + int count = 0; + int *lists = maxSlidingWindow(nums, size, k, &count); + for (i = 0; i < count; i++) { + printf("%d ", lists[i]); + } + printf("\n"); + return 0; +} From 383370dc62f61cae4a14791e13869a9d0ca8f149 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 7 Jan 2018 15:15:36 +0800 Subject: [PATCH 034/211] Majority elements Signed-off-by: Leo Ma --- 229_majority_element_ii/Makefile | 2 + 229_majority_element_ii/majority.c | 67 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 229_majority_element_ii/Makefile create mode 100644 229_majority_element_ii/majority.c diff --git a/229_majority_element_ii/Makefile b/229_majority_element_ii/Makefile new file mode 100644 index 0000000..9741c71 --- /dev/null +++ b/229_majority_element_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test majority.c diff --git a/229_majority_element_ii/majority.c b/229_majority_element_ii/majority.c new file mode 100644 index 0000000..780fca4 --- /dev/null +++ b/229_majority_element_ii/majority.c @@ -0,0 +1,67 @@ +#include +#include + +static int *majorityElement(int* nums, int numsSize, int *returnSize) +{ + int i, m = -1, n = -1, cm = 0, cn = 0; + for (i = 0; i < numsSize; i++) { + if (m == nums[i]) { + cm++; + } else if (n == nums[i]) { + cn++; + } else if (cm == 0) { + m = nums[i]; + cm++; + } else if (cn == 0) { + n = nums[i]; + cn++; + } else { + cm--; + cn--; + } + } + + cm = 0; + cn = 0; + for (i = 0; i < numsSize; i++) { + if (nums[i] == m) { + cm++; + } else if (nums[i] == n) { + cn++; + } + } + + int count = 0; + int *results = malloc(2 * sizeof(int)); + if (cm > numsSize / 3) { + results[count++] = m; + } + if (cn > numsSize / 3) { + results[count++] = n; + } + + *returnSize = count; + return results; +} + +int main(int argc, char **argv) +{ + if (argc < 2) { + fprintf(stderr, "Usage: ./test target n1 n2...\n"); + exit(-1); + } + + int i, size = argc - 1; + int *nums = malloc(size * sizeof(int)); + for (i = 0; i < size; i++) { + nums[i] = atoi(argv[i + 1]); + } + + int count = 0; + int *results = majorityElement(nums, size, &count); + for (i = 0; i < count; i++) { + printf("%d ", results[i]); + } + printf("\n"); + return 0; +} From b55babca0618719ee9146c0ac389e00bbb0fb353 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 8 Jan 2018 14:38:59 +0800 Subject: [PATCH 035/211] Kth bst Signed-off-by: begeekmyfriend --- 230_kth_smallest_element_in_a_bst/Makefile | 2 + 230_kth_smallest_element_in_a_bst/kth_bst.c | 83 +++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 230_kth_smallest_element_in_a_bst/Makefile create mode 100644 230_kth_smallest_element_in_a_bst/kth_bst.c diff --git a/230_kth_smallest_element_in_a_bst/Makefile b/230_kth_smallest_element_in_a_bst/Makefile new file mode 100644 index 0000000..755b6b9 --- /dev/null +++ b/230_kth_smallest_element_in_a_bst/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test kth_bst.c diff --git a/230_kth_smallest_element_in_a_bst/kth_bst.c b/230_kth_smallest_element_in_a_bst/kth_bst.c new file mode 100644 index 0000000..337f1a3 --- /dev/null +++ b/230_kth_smallest_element_in_a_bst/kth_bst.c @@ -0,0 +1,83 @@ +#include +#include +#include + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +static bool traverse(struct TreeNode *node, int *k, int *val) +{ + if (node == NULL) { + return false; + } + if (traverse(node->left, k, val)) { + return true; + } + if (--*k == 0) { + *val = node->val; + return true; + } + if (traverse(node->right, k, val)) { + return true; + } + return false; +} + +static int kthSmallest(struct TreeNode* root, int k) +{ + int value = 0; + traverse(root, &k, &value); + return value; +} + +int main(void) +{ +#if 1 + struct TreeNode root, n10, n11, n20, n21, n22, n23; + root.val = 1; + n10.val = 2; + n11.val = 2; + n20.val = 3; + n21.val = 4; + n22.val = 4; + n23.val = 3; + root.left = &n10; + root.right = &n11; + n10.left = &n20; + n10.right = &n21; + n11.left = &n22; + n11.right = &n23; + n20.left = NULL; + n20.right = NULL; + n21.left = NULL; + n21.right = NULL; + n22.left = NULL; + n22.right = NULL; + n23.left = NULL; + n23.right = NULL; +#else + struct TreeNode root, n10, n11, n21, n22; + root.val = 1; + n10.val = 2; + n11.val = 2; + n21.val = 3; + n22.val = 4; + root.left = &n10; + root.right = &n11; + n10.left = NULL; + n10.right = &n21; + n11.left = &n22; + n11.right = NULL; + n21.left = NULL; + n21.right = NULL; + n22.left = NULL; + n22.right = NULL; +#endif + + int k = 1; + printf("%d\n", kthSmallest(&root, k)); + return 0; +} From a000d9465e149249cc9443b2f1cbd1a1c165a7f9 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 9 Jan 2018 09:54:46 +0800 Subject: [PATCH 036/211] Basic calculator Signed-off-by: begeekmyfriend --- 224_basic_calculator/Makefile | 2 + 224_basic_calculator/calculator.c | 68 +++++++++++++++++++++++++ 227_basic_calculator_ii/Makefile | 2 + 227_basic_calculator_ii/calculator.c | 75 ++++++++++++++++++++++++++++ 4 files changed, 147 insertions(+) create mode 100644 224_basic_calculator/Makefile create mode 100644 224_basic_calculator/calculator.c create mode 100644 227_basic_calculator_ii/Makefile create mode 100644 227_basic_calculator_ii/calculator.c diff --git a/224_basic_calculator/Makefile b/224_basic_calculator/Makefile new file mode 100644 index 0000000..2446711 --- /dev/null +++ b/224_basic_calculator/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test calculator.c diff --git a/224_basic_calculator/calculator.c b/224_basic_calculator/calculator.c new file mode 100644 index 0000000..e4cfac5 --- /dev/null +++ b/224_basic_calculator/calculator.c @@ -0,0 +1,68 @@ +#include +#include + +static int calculator(char *s) +{ + int n; + int pos1 = 0; + int pos2 = 0; + int *nums = malloc(1000 * sizeof(int)); + char *signs = malloc(1000 * sizeof(char)); + + 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--; + + if (pos1 >= 2 && signs[pos2 - 1] != '(' && signs[pos2 - 1] != '(') { + int a = nums[--pos1]; + if (signs[--pos2] == '+') { + n = a + n; + } else { + n = a - n; + } + } + nums[pos1++] = n; + break; + } + s++; + } + + return n; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test string\n"); + exit(-1); + } + printf("%d\n", calculator(argv[1])); + return 0; +} diff --git a/227_basic_calculator_ii/Makefile b/227_basic_calculator_ii/Makefile new file mode 100644 index 0000000..2446711 --- /dev/null +++ b/227_basic_calculator_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test calculator.c diff --git a/227_basic_calculator_ii/calculator.c b/227_basic_calculator_ii/calculator.c new file mode 100644 index 0000000..6465b9b --- /dev/null +++ b/227_basic_calculator_ii/calculator.c @@ -0,0 +1,75 @@ +#include +#include + +static int calculator(char *s) +{ + int n; + int pos1 = 0; + int pos2 = 0; + int *nums = malloc(100 * sizeof(int)); + char *signs = malloc(100 * sizeof(char)); + + nums[pos1++] = 0; + while (*s != '\0') { + switch (*s) { + case '+': + case '-': + if (pos1 >= 3) { + int b = nums[pos1 - 1]; + int a = nums[pos1 - 2]; + if (signs[--pos2] == '+') { + nums[pos1 - 2] = a + b; + } else { + nums[pos1 - 2] = a - b; + } + pos1--; + } + case '*': + case '/': + signs[pos2++] = *s; + break; + case ' ': + break; + default: + n = 0; + while(*s >= '0' && *s <= '9') { + n = n * 10 + (*s - '0'); + s++; + } + s--; + + if (pos1 >= 2 && signs[pos2 - 1] != '+' && signs[pos2 - 1] != '-') { + int a = nums[--pos1]; + if (signs[--pos2] == '*') { + n = a * n; + } else { + n = a / n; + } + } + nums[pos1++] = n; + break; + } + s++; + } + + while (pos2 > 0) { + n = nums[--pos1]; + int a = nums[--pos1]; + if (signs[--pos2] == '+') { + n = a + n; + } else { + n = a - n; + } + } + return n; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test string\n"); + exit(-1); + } + printf("%d\n", calculator(argv[1])); + return 0; +} From d895c2b2f3aa5a2a511e3d10f95c9e0f01d7f09c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 11 Jan 2018 09:36:08 +0800 Subject: [PATCH 037/211] Maximal Square Signed-off-by: begeekmyfriend --- 221_maximal_square/Makefile | 2 + 221_maximal_square/maximal_square.c | 63 +++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 221_maximal_square/Makefile create mode 100644 221_maximal_square/maximal_square.c diff --git a/221_maximal_square/Makefile b/221_maximal_square/Makefile new file mode 100644 index 0000000..635083b --- /dev/null +++ b/221_maximal_square/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test maximal_square.c diff --git a/221_maximal_square/maximal_square.c b/221_maximal_square/maximal_square.c new file mode 100644 index 0000000..c014308 --- /dev/null +++ b/221_maximal_square/maximal_square.c @@ -0,0 +1,63 @@ +#include +#include +#include + +static inline int min(int a, int b) +{ + return a < b ? a : b; +} + +static inline int max(int a, int b) +{ + return a > b ? a : b; +} + +static int maximalSquare(char** matrix, int matrixRowSize, int matrixColSize) +{ + int i, j, max_len = 0; + int **lens = malloc(matrixRowSize * sizeof(int *)); + for (i = 0; i < matrixRowSize; i++) { + lens[i] = malloc(matrixColSize * sizeof(int)); + } + + for (i = 0; i < matrixColSize; i++) { + lens[0][i] = matrix[0][i] == '1' ? 1 : 0; + max_len = matrix[0][i] == '1' ? 1 : max_len; + } + + for (i = 0; i < matrixRowSize; i++) { + lens[i][0] = matrix[i][0] == '1' ? 1 : 0; + max_len = matrix[i][0] == '1' ? 1 : max_len; + } + + for (i = 1; i < matrixRowSize; i++) { + for (j = 1; j < matrixColSize; j++) { + if (matrix[i][j] == '1') { + lens[i][j] = 1; + lens[i][j] += min(lens[i - 1][j - 1], min(lens[i - 1][j], lens[i][j - 1])); + } else { + lens[i][j] = 0; + } + max_len = max(max_len, lens[i][j]); + } + } + return max_len * max_len; +} + +/* ./test 11111111 11111110 11111110 11111000 01111000 */ +int main(int argc, char **argv) +{ + if (argc < 2) { + fprintf(stderr, "Usage: ./test row1 row2...\n"); + exit(-1); + } + + int i, j; + int row_size = argc - 1; + int col_size = strlen(argv[1]); + for (i = 0; i < row_size; i++) { + printf("%s\n", argv[i + 1]); + } + printf("%d\n", maximalSquare(argv + 1, argc - 1, strlen(argv[1]))); + return 0; +} From 95d861c4f9c7fd9e726ac475efb593c6be9dc327 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 11 Jan 2018 09:36:24 +0800 Subject: [PATCH 038/211] Invert binary tree Signed-off-by: begeekmyfriend --- 226_invert_binary_tree/Makefile | 2 + 226_invert_binary_tree/invert_binary_tree.c | 69 +++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 226_invert_binary_tree/Makefile create mode 100644 226_invert_binary_tree/invert_binary_tree.c diff --git a/226_invert_binary_tree/Makefile b/226_invert_binary_tree/Makefile new file mode 100644 index 0000000..1a8a9fe --- /dev/null +++ b/226_invert_binary_tree/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test invert_binary_tree.c diff --git a/226_invert_binary_tree/invert_binary_tree.c b/226_invert_binary_tree/invert_binary_tree.c new file mode 100644 index 0000000..36b0cad --- /dev/null +++ b/226_invert_binary_tree/invert_binary_tree.c @@ -0,0 +1,69 @@ +#include +#include +#include + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +static struct TreeNode *invertTree(struct TreeNode* root) +{ + if (root != NULL) { + struct TreeNode *node = root->left; + root->left = root->right; + root->right = node; + invertTree(root->left); + invertTree(root->right); + } + return root; +} + +int main(void) +{ +#if 1 + struct TreeNode root, n10, n11, n20, n21, n22, n23; + root.val = 1; + n10.val = 2; + n11.val = 2; + n20.val = 3; + n21.val = 4; + n22.val = 4; + n23.val = 3; + root.left = &n10; + root.right = &n11; + n10.left = &n20; + n10.right = &n21; + n11.left = &n22; + n11.right = &n23; + n20.left = NULL; + n20.right = NULL; + n21.left = NULL; + n21.right = NULL; + n22.left = NULL; + n22.right = NULL; + n23.left = NULL; + n23.right = NULL; +#else + struct TreeNode root, n10, n11, n21, n22; + root.val = 1; + n10.val = 2; + n11.val = 2; + n21.val = 3; + n22.val = 4; + root.left = &n10; + root.right = &n11; + n10.left = NULL; + n10.right = &n21; + n11.left = &n22; + n11.right = NULL; + n21.left = NULL; + n21.right = NULL; + n22.left = NULL; + n22.right = NULL; +#endif + + invertTree(&root); + return 0; +} From 89d8e289eb61ba3c23e439bcb2be06566ff78a3b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 11 Jan 2018 09:36:52 +0800 Subject: [PATCH 039/211] Lowest common ancestor of a binary tree Signed-off-by: begeekmyfriend --- .../Makefile | 2 + .../bst_lca.c | 58 ++++++++++++++++ .../Makefile | 2 + .../bst_lca.c | 68 +++++++++++++++++++ 4 files changed, 130 insertions(+) create mode 100644 235_lowest_common_ancestor_of_a_binary_search_tree/Makefile create mode 100644 235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c create mode 100644 236_lowest_common_ancestor_of_a_binary_tree/Makefile create mode 100644 236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c diff --git a/235_lowest_common_ancestor_of_a_binary_search_tree/Makefile b/235_lowest_common_ancestor_of_a_binary_search_tree/Makefile new file mode 100644 index 0000000..32b0df5 --- /dev/null +++ b/235_lowest_common_ancestor_of_a_binary_search_tree/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test bst_lca.c diff --git a/235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c b/235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c new file mode 100644 index 0000000..502863a --- /dev/null +++ b/235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c @@ -0,0 +1,58 @@ +#include +#include +#include + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +static struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) +{ + if (root == NULL || root->val == p->val || root->val == q->val) { + return root; + } else if (p->val > root->val && q->val > root->val) { + return lowestCommonAncestor(root->right, p, q); + } else if (p->val < root->val && q->val < root->val) { + return lowestCommonAncestor(root->left, p, q); + } else { + return root; + } +} + +int main(int argc, char **argv) +{ + struct TreeNode root, node1, node2, node11, node12, node21, node22, node121, node122; + root.val = 3; + node1.val = 2; + node2.val = 8; + node11.val = 0; + node12.val = 4; + node21.val = 7; + node22.val = 9; + node121.val = 3; + node122.val = 5; + root.left = &node1; + root.right = &node2; + node1.left = &node11; + node1.right = &node12; + node2.left = &node21; + node2.right = &node22; + node11.left = NULL; + node11.right = NULL; + node12.left = &node121; + node12.right = &node122; + node21.left = NULL; + node21.right = NULL; + node22.left = NULL; + node22.right = NULL; + node121.left = NULL; + node121.right = NULL; + node122.left = NULL; + node122.right = NULL; + + struct TreeNode *ancestor = lowestCommonAncestor(&root, &node11, &node22); + printf("%d\n", ancestor->val); + return 0; +} diff --git a/236_lowest_common_ancestor_of_a_binary_tree/Makefile b/236_lowest_common_ancestor_of_a_binary_tree/Makefile new file mode 100644 index 0000000..32b0df5 --- /dev/null +++ b/236_lowest_common_ancestor_of_a_binary_tree/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test bst_lca.c diff --git a/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c b/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c new file mode 100644 index 0000000..28c9ab7 --- /dev/null +++ b/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c @@ -0,0 +1,68 @@ +#include +#include +#include + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +static struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) +{ + if (root == NULL || root == p || root == q) { + return root; + } + + struct TreeNode *l = lowestCommonAncestor(root->left, p, q); + if (l != NULL && l != p && l != q) { + return l; + } + + struct TreeNode *r = lowestCommonAncestor(root->right, p, q); + if (r != NULL && r != p && r != q) { + return r; + } + + if (l != NULL && r != NULL) { + return root; + } else { + return l != NULL ? l : r; + } +} + +int main(int argc, char **argv) +{ + struct TreeNode root, node1, node2, node11, node12, node21, node22, node121, node122; + root.val = 3; + node1.val = 5; + node2.val = 1; + node11.val = 0; + node12.val = 4; + node21.val = 7; + node22.val = 9; + node121.val = 3; + node122.val = 5; + root.left = &node1; + root.right = &node2; + node1.left = &node11; + node1.right = &node12; + node2.left = &node21; + node2.right = &node22; + node11.left = NULL; + node11.right = NULL; + node12.left = &node121; + node12.right = &node122; + node21.left = NULL; + node21.right = NULL; + node22.left = NULL; + node22.right = NULL; + node121.left = NULL; + node121.right = NULL; + node122.left = NULL; + node122.right = NULL; + + struct TreeNode *ancestor = lowestCommonAncestor(&root, &node11, &node22); + printf("%d\n", ancestor->val); + return 0; +} From a147a5756860e023968364e3374dfd78892f5340 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 12 Feb 2018 17:54:50 +0800 Subject: [PATCH 040/211] Improvement Signed-off-by: begeekmyfriend --- .../longest_palindromic_substring.c | 6 +- 006_zigzag_conversion/zigzag_conversion.c | 3 +- 008_atoi/Makefile | 2 + 008_atoi/atoi.c | 80 +++++++++---------- 009_palindrome_number/palindrome_number.c | 3 +- .../regular_expression.c | 3 +- 012_roman_numeral/roman_numeral.c | 6 +- 013_roman_to_integer/roman_to_integer.c | 4 +- 014_longest_common_prefix/common_prefix.c | 2 +- .../letter_combinations.c | 3 +- 029_divide_two_integers/divide.c | 3 +- 034_search_for_a_range/range_search.c | 3 +- 035_search_insert_position/insert_position.c | 3 +- 036_valid_sudoku/valid_sudoku.c | 3 +- 041_first_missing_positive/missing_positive.c | 2 +- 042_trapping_rain_water/trap_water.c | 3 +- 048_rotate_image/rotate.c | 7 +- 17 files changed, 77 insertions(+), 59 deletions(-) create mode 100644 008_atoi/Makefile diff --git a/005_longest_palindromic_substring/longest_palindromic_substring.c b/005_longest_palindromic_substring/longest_palindromic_substring.c index b8c2e91..9a9b2a7 100644 --- a/005_longest_palindromic_substring/longest_palindromic_substring.c +++ b/005_longest_palindromic_substring/longest_palindromic_substring.c @@ -10,7 +10,7 @@ static inline int min(int a, int b) static int manacher(char *s, char output[]) { int i, j; - char s2[1000] = { '\0' }; + char s2[3000] = { '\0' }; s2[0] = '$'; for (i = 0; s[i] != '\0'; i++) { @@ -21,7 +21,7 @@ static int manacher(char *s, char output[]) int len = (i<<1)+2; s2[len] = '\0'; - int p[1000] = { 0 }; // 以s2中某一点为中心的回文半径 + int p[3000] = { 0 }; // 以s2中某一点为中心的回文半径 int id = 0; // 回文的中心点 int limit = 0; // 最长回文的右边界点 int maxLen = 0; // 最大回文长度 @@ -67,7 +67,7 @@ static char *longestPalindrom(char *s) return s; } - char *palindrome = malloc(1000); + char *palindrome = malloc(2000); memset(palindrome, 0, sizeof(palindrome)); int size = manacher(s, palindrome); diff --git a/006_zigzag_conversion/zigzag_conversion.c b/006_zigzag_conversion/zigzag_conversion.c index 8f00e28..f324d63 100644 --- a/006_zigzag_conversion/zigzag_conversion.c +++ b/006_zigzag_conversion/zigzag_conversion.c @@ -2,7 +2,8 @@ #include #include -static char* convert(char* s, int numRows) { +static char* convert(char* s, int numRows) +{ if (numRows <= 1) return s; int len = strlen(s); diff --git a/008_atoi/Makefile b/008_atoi/Makefile new file mode 100644 index 0000000..5910ca2 --- /dev/null +++ b/008_atoi/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test atoi.c diff --git a/008_atoi/atoi.c b/008_atoi/atoi.c index 481c24d..ef8cda4 100644 --- a/008_atoi/atoi.c +++ b/008_atoi/atoi.c @@ -1,52 +1,52 @@ -/* - * Copyright (C) 2015, Leo Ma - */ - #include #include #include -int main(int argc, char **argv) +static int myAtoi(char* str) { - char *alpha, *s; - int n = 0, sign = 0; - - if (argc != 2) { - printf("Usage: ./atoi 123\n"); - exit(-1); - } + char *s; + int n = 0, sign = 0; - alpha = argv[1]; - while (*alpha == ' ' || *alpha == '\t') { - alpha++; - } + while (*str == ' ' || *str == '\t') { + str++; + } - for (s = alpha; *s != '\0'; s++) { - if (isdigit(*s)) { - int d = *s - '0'; - if (sign) { - if (-n < (INT_MIN + d) / 10) { - n = INT_MIN; - break; - } - } else { - if (n > (INT_MAX - d) / 10) { - n = INT_MAX; - break; - } - } - n = n * 10 + d; - } else if (*s == '-' && isdigit(*(s + 1))) { - sign = 1; - } else if (*s == '+' && isdigit(*(s + 1))) { - sign = 0; - } else { - break; + for (s = str; *s != '\0'; s++) { + if (isdigit(*s)) { + int d = *s - '0'; + if (sign) { + if (-n < (INT_MIN + d) / 10) { + n = INT_MIN; + break; + } + } else { + if (n > (INT_MAX - d) / 10) { + n = INT_MAX; + break; } + } + n = n * 10 + d; + } else if (*s == '-' && isdigit(*(s + 1))) { + sign = 1; + } else if (*s == '+' && isdigit(*(s + 1))) { + sign = 0; + } else { + break; } + } + + return sign ? -n : n; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + printf("Usage: ./atoi 123\n"); + exit(-1); + } - n = sign ? -n : n; - printf("n = %d %x\n", n, n); + int n = myAtoi(argv[1]); + printf("n = %d %x\n", n, n); - return 0; + return 0; } diff --git a/009_palindrome_number/palindrome_number.c b/009_palindrome_number/palindrome_number.c index 4b8d801..0c59619 100644 --- a/009_palindrome_number/palindrome_number.c +++ b/009_palindrome_number/palindrome_number.c @@ -12,7 +12,8 @@ static int reverse(int x) return y; } -static bool isPalindrome(int x) { +static bool isPalindrome(int x) +{ if (x == 0) { return true; } diff --git a/010_regular_expression_matching/regular_expression.c b/010_regular_expression_matching/regular_expression.c index 37c62cd..ccc78e5 100644 --- a/010_regular_expression_matching/regular_expression.c +++ b/010_regular_expression_matching/regular_expression.c @@ -3,7 +3,8 @@ #include #include -bool isMatch(char* s, char* p) { +static bool isMatch(char* s, char* p) +{ if (*p == '\0') { return *s == '\0'; } diff --git a/012_roman_numeral/roman_numeral.c b/012_roman_numeral/roman_numeral.c index 8a632e8..f3ad517 100644 --- a/012_roman_numeral/roman_numeral.c +++ b/012_roman_numeral/roman_numeral.c @@ -2,7 +2,8 @@ #include #include -static void num2char(char **num, int bit, int n) { +static void num2char(char **num, int bit, int n) +{ int i; char low, mid, high; char *p = *num; @@ -61,7 +62,8 @@ static void num2char(char **num, int bit, int n) { static char roman_numeral[64]; -static char *intToRoman(int num) { +static char *intToRoman(int num) +{ char *p = &roman_numeral[0]; int thousand_bit = num / 1000; int hundred_bit = (num % 1000) / 100; diff --git a/013_roman_to_integer/roman_to_integer.c b/013_roman_to_integer/roman_to_integer.c index d7899c3..4469ae8 100644 --- a/013_roman_to_integer/roman_to_integer.c +++ b/013_roman_to_integer/roman_to_integer.c @@ -23,7 +23,8 @@ static int roman_to_integer(char c) } } -int romanToInt (char *s) { +int romanToInt (char *s) +{ int i, result = roman_to_integer(s[0]); for (i = 1; s[i] != '\0'; i++) { @@ -39,6 +40,7 @@ int romanToInt (char *s) { return result; } + int main(int argc, char **argv) { if (argc < 2) { diff --git a/014_longest_common_prefix/common_prefix.c b/014_longest_common_prefix/common_prefix.c index 595effd..e764526 100644 --- a/014_longest_common_prefix/common_prefix.c +++ b/014_longest_common_prefix/common_prefix.c @@ -5,7 +5,7 @@ static char* longestCommonPrefix(char** strs, int strsSize) { int i, count = 0; - char *result = malloc(100); + char *result = malloc(1000); while (strsSize > 0) { char c = strs[0][count]; for (i = 1; i < strsSize; i++) { diff --git a/017_letter_combinations_of_a_phone_number/letter_combinations.c b/017_letter_combinations_of_a_phone_number/letter_combinations.c index 359c33a..7a1382b 100644 --- a/017_letter_combinations_of_a_phone_number/letter_combinations.c +++ b/017_letter_combinations_of_a_phone_number/letter_combinations.c @@ -6,7 +6,8 @@ ** Return an array of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ -char** letterCombinations(char* digits, int* returnSize) { +static char** letterCombinations(char* digits, int* returnSize) +{ char *letter_matrix[10]; letter_matrix[0] = ""; letter_matrix[1] = " "; diff --git a/029_divide_two_integers/divide.c b/029_divide_two_integers/divide.c index f587cd4..9c0250d 100644 --- a/029_divide_two_integers/divide.c +++ b/029_divide_two_integers/divide.c @@ -2,7 +2,8 @@ #include #include -int divide(int dividend, int divisor) { +int divide(int dividend, int divisor) +{ int sign = (float) dividend / divisor > 0 ? 1 : -1; unsigned int dvd = dividend > 0 ? dividend : -dividend; unsigned int dvs = divisor > 0 ? divisor : -divisor; diff --git a/034_search_for_a_range/range_search.c b/034_search_for_a_range/range_search.c index 96b8214..457ed51 100644 --- a/034_search_for_a_range/range_search.c +++ b/034_search_for_a_range/range_search.c @@ -45,7 +45,8 @@ static int binary_search_end(int *a, int size, int target) ** Return an array of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ -int* searchRange(int* nums, int numsSize, int target, int* returnSize) { +static int* searchRange(int* nums, int numsSize, int target, int* returnSize) +{ int *range = malloc(2 * sizeof(int)); *returnSize = 2; diff --git a/035_search_insert_position/insert_position.c b/035_search_insert_position/insert_position.c index 2d6db79..7533bc4 100644 --- a/035_search_insert_position/insert_position.c +++ b/035_search_insert_position/insert_position.c @@ -1,7 +1,8 @@ #include #include -static int searchInsert(int* nums, int numsSize, int target) { +static int searchInsert(int* nums, int numsSize, int target) +{ int low = -1; int high = numsSize; while (low + 1 < high) { diff --git a/036_valid_sudoku/valid_sudoku.c b/036_valid_sudoku/valid_sudoku.c index 452fb2e..7ee6b5b 100644 --- a/036_valid_sudoku/valid_sudoku.c +++ b/036_valid_sudoku/valid_sudoku.c @@ -67,7 +67,8 @@ static bool valid(char **board, int row, int col) return true; } -bool isValidSudoku(char** board, int boardRowSize, int boardColSize) { +static bool isValidSudoku(char** board, int boardRowSize, int boardColSize) +{ if (boardRowSize != 9 || boardColSize != 9) { return false; } diff --git a/041_first_missing_positive/missing_positive.c b/041_first_missing_positive/missing_positive.c index fc3339b..787a5a5 100644 --- a/041_first_missing_positive/missing_positive.c +++ b/041_first_missing_positive/missing_positive.c @@ -1,7 +1,7 @@ #include #include -static void swap(int *a, int *b) +static inline void swap(int *a, int *b) { int tmp = *a; *a = *b; diff --git a/042_trapping_rain_water/trap_water.c b/042_trapping_rain_water/trap_water.c index a7d5b30..2c2393a 100644 --- a/042_trapping_rain_water/trap_water.c +++ b/042_trapping_rain_water/trap_water.c @@ -1,7 +1,8 @@ #include #include -static int trap(int* height, int heightSize) { +static int trap(int* height, int heightSize) +{ if (heightSize < 2) { return 0; } diff --git a/048_rotate_image/rotate.c b/048_rotate_image/rotate.c index a332eef..f5e6c79 100644 --- a/048_rotate_image/rotate.c +++ b/048_rotate_image/rotate.c @@ -1,7 +1,8 @@ #include #include -static void rotate(int** matrix, int matrixRowSize, int matrixColSize) { +static void rotate(int** matrix, int matrixRowSize, int matrixColSize) +{ int i, j; if (matrixRowSize != matrixColSize) { return; @@ -32,8 +33,10 @@ int main(int argc, char **argv) for (i = 0; i < row_size; i++) { matrix[i] = malloc(col_size * sizeof(int)); for (j = 0; j < col_size; j++) { - matrix[i][j] = count++; + matrix[i][j] = ++count; + printf("%d ", matrix[i][j]); } + printf("\n"); } rotate(matrix, row_size, col_size); From 98bc71991c87f083b6a1416e928b550aa0c3b7bb Mon Sep 17 00:00:00 2001 From: vsyf Date: Tue, 13 Aug 2019 22:30:56 +0800 Subject: [PATCH 041/211] Improve atoi --- 008_atoi/atoi.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/008_atoi/atoi.c b/008_atoi/atoi.c index ef8cda4..3a3660f 100644 --- a/008_atoi/atoi.c +++ b/008_atoi/atoi.c @@ -26,9 +26,9 @@ static int myAtoi(char* str) } } n = n * 10 + d; - } else if (*s == '-' && isdigit(*(s + 1))) { + } else if (*s == '-' && isdigit(*(s + 1)) && (n == 0)) { sign = 1; - } else if (*s == '+' && isdigit(*(s + 1))) { + } else if (*s == '+' && isdigit(*(s + 1)) && (n == 0)) { sign = 0; } else { break; From cf2719c15e9a89fc9b5567d067b0c7b2a74842a0 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sun, 24 May 2020 21:31:20 +0800 Subject: [PATCH 042/211] Use Priority queue Signed-off-by: Leo Ma --- 023_merge_k_sorted_lists/merge_lists.c | 137 +++++++++++++++++++++---- 1 file changed, 118 insertions(+), 19 deletions(-) diff --git a/023_merge_k_sorted_lists/merge_lists.c b/023_merge_k_sorted_lists/merge_lists.c index 58a099e..3b29dd6 100644 --- a/023_merge_k_sorted_lists/merge_lists.c +++ b/023_merge_k_sorted_lists/merge_lists.c @@ -1,45 +1,144 @@ #include #include -#include +#include 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; + *a = *b; + *b = tmp; +} + +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) +{ + int i; + for (i = 0; i < queue->size; i++) { + printf("%d ", queue->nodes[i]->val); + } + printf("\n"); +} + +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); + } +} + +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; + } + } +} + +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; + } + } +} + +static void heap_build(struct PriorityQueue *queue) +{ + 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); +} + +static struct ListNode *get(struct PriorityQueue *queue) +{ + int i; + struct ListNode *p = queue->nodes[0]; + swap(queue->nodes, queue->nodes + queue->size - 1); + queue->size--; + percolate_down2(queue->nodes, queue->size); + return p; +} + +static struct PriorityQueue *init(int size) +{ + struct PriorityQueue *queue = malloc(sizeof(*queue)); + queue->nodes = malloc(size * sizeof(*queue->nodes)); + queue->size = 0; + return queue; +} + static struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) { if (listsSize == 0) { return NULL; } + if (listsSize == 1) { return lists[0]; } - int i, index; - struct ListNode dummy, *p, *prev; + int i; + struct ListNode dummy; + struct ListNode *prev; + struct PriorityQueue *queue = init(listsSize); dummy.next = NULL; prev = &dummy; - index = 0; - while (index != -1) { - int min = INT_MAX; - index = -1; - for (i = 0; i < listsSize; i++) { - if (lists[i] != NULL && lists[i]->val < min) { - min = lists[i]->val; - index = i; - } + + for (i = 0; i < listsSize; i++) { + if (lists[i] != NULL) { + put(queue, lists[i]); } + } + heap_build(queue); - if (index != -1) { - p = malloc(sizeof(*p)); - p->val = min; - p->next = NULL; - prev->next = p; - prev = p; - lists[index] = lists[index]->next; + while (queue->size > 0) { + struct ListNode *n = get(queue); + prev->next = n; + prev = n; + if (n->next != NULL) { + put(queue, n->next); } + n->next = NULL; } return dummy.next; From f755c7e13bca60a0a1cda927f075cde958318902 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 26 May 2020 09:30:37 +0800 Subject: [PATCH 043/211] Refine Signed-off-by: begeekmyfriend --- 025_reverse_nodes_in_k_group/reverse_nodes.c | 27 ++++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/025_reverse_nodes_in_k_group/reverse_nodes.c b/025_reverse_nodes_in_k_group/reverse_nodes.c index 7517559..c28dab0 100644 --- a/025_reverse_nodes_in_k_group/reverse_nodes.c +++ b/025_reverse_nodes_in_k_group/reverse_nodes.c @@ -8,22 +8,27 @@ struct ListNode { static struct ListNode* reverseKGroup(struct ListNode* head, int k) { - int i, len = 0; + int len = 0; struct ListNode dummy; - struct ListNode *p = head; struct ListNode *prev = &dummy; dummy.next = head; - for (p = head; p != NULL; p = p->next) { + for (; head != NULL; head = head->next) { if (++len % k == 0) { - struct ListNode *begin = prev->next; - for (i = 1; i < k; i++) { - struct ListNode *next = begin->next; - begin->next = next->next; - next->next = prev->next; - prev->next = next; + /* t always the original first one */ + struct ListNode *t = prev->next; + /* loop condition implicits the final state */ + while (prev->next != head) { + /* the new segment head */ + struct ListNode *h = t->next; + /* deletion */ + t->next = h->next; + /* insertion */ + h->next = prev->next; + prev->next = h; } - p = begin; - prev = p; + /* For iteration */ + prev = t; + head = t; } } return dummy.next; From 45b23e51694f0a0e838f1bae6a9ff09e348b6244 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 27 May 2020 16:02:32 +0800 Subject: [PATCH 044/211] Rename Signed-off-by: begeekmyfriend --- 022_generate_paratheses/Makefile | 2 - 022_generate_paratheses/parentheses.c | 68 --------------------------- 022_generate_parathesis/Makefile | 2 + 022_generate_parathesis/parenthesis.c | 50 ++++++++++++++++++++ 4 files changed, 52 insertions(+), 70 deletions(-) delete mode 100644 022_generate_paratheses/Makefile delete mode 100644 022_generate_paratheses/parentheses.c create mode 100644 022_generate_parathesis/Makefile create mode 100644 022_generate_parathesis/parenthesis.c diff --git a/022_generate_paratheses/Makefile b/022_generate_paratheses/Makefile deleted file mode 100644 index 5445d90..0000000 --- a/022_generate_paratheses/Makefile +++ /dev/null @@ -1,2 +0,0 @@ -all: - gcc -O2 -o test parentheses.c diff --git a/022_generate_paratheses/parentheses.c b/022_generate_paratheses/parentheses.c deleted file mode 100644 index 2f95228..0000000 --- a/022_generate_paratheses/parentheses.c +++ /dev/null @@ -1,68 +0,0 @@ -#include -#include -#include - -/** - ** Return an array of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static char** generateParenthesis(int n, int* returnSize) -{ - int left, right, cap = 5000, count = 0; - char *stack = malloc(2 * n + 1); - char **parentheses = malloc(cap * sizeof(char *)); - - char *p = stack; - left = right = 0; - stack[2 * n] = '\0'; - - /* begin and end condition of loop */ - while (p != stack || count == 0) { - if (left == n && right == n) { - parentheses[count] = malloc(2 * n + 1); - strcpy(parentheses[count], stack); - count++; - - /* back tracking */ - while (--p != stack) { - if (*p == '(') { - /* until ')' is no more than '(' is guaranteed */ - if (--left > right) { - *p++ = ')'; - right++; - break; - } - } else { - right--; - } - } - } else { - /* forward */ - while (left < n) { - *p++ = '('; - left++; - } - while (right < n) { - *p++ = ')'; - right++; - } - } - } - - *returnSize = count; - return parentheses; -} - -int main(int argc, char **argv) -{ - int i, count; - if (argc != 2) { - fprintf(stderr, "Usage: ./test 3\n"); - exit(-1); - } - char ** lists = generateParenthesis(atoi(argv[1]), &count); - for (i = 0; i < count; i++) { - printf("%s\n", lists[i]); - } - return 0; -} diff --git a/022_generate_parathesis/Makefile b/022_generate_parathesis/Makefile new file mode 100644 index 0000000..6ad72c8 --- /dev/null +++ b/022_generate_parathesis/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test parenthesis.c diff --git a/022_generate_parathesis/parenthesis.c b/022_generate_parathesis/parenthesis.c new file mode 100644 index 0000000..174b3ed --- /dev/null +++ b/022_generate_parathesis/parenthesis.c @@ -0,0 +1,50 @@ +#include +#include +#include + +static void dfs(int n, int left, int right, char *stack, int len, char **results, int *count) +{ + if (len == 2 * n) { + results[*count] = malloc((len + 1) * sizeof(char)); + strcpy(results[(*count)++], stack); + return; + } + + if (left < n) { + stack[len] = '('; + dfs(n, left + 1, right, stack, len + 1, results, count); + } + + if (right < left) { + stack[len] = ')'; + dfs(n, left, right + 1, stack, len + 1, results, count); + } +} + +/** + ** Return an array of size *returnSize. + ** Note: The returned array must be malloced, assume caller calls free(). + **/ +static char** generateParenthesis(int n, int* returnSize) +{ + char *stack = calloc(2 * n + 1, sizeof(char)); + char **parentheses = malloc(5000 * sizeof(char *)); + *returnSize = 0; + dfs(n, 0, 0, stack, 0, parentheses, returnSize); + + return parentheses; +} + +int main(int argc, char **argv) +{ + int i, count; + if (argc != 2) { + fprintf(stderr, "Usage: ./test 3\n"); + exit(-1); + } + char ** lists = generateParenthesis(atoi(argv[1]), &count); + for (i = 0; i < count; i++) { + printf("%s\n", lists[i]); + } + return 0; +} From a83a9ec20276c30976753f081666afe241c336a6 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 28 May 2020 08:10:43 +0800 Subject: [PATCH 045/211] Refine Signed-off-by: begeekmyfriend --- 028_implement_strstr/strstr.c | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/028_implement_strstr/strstr.c b/028_implement_strstr/strstr.c index 060d915..24a8c32 100644 --- a/028_implement_strstr/strstr.c +++ b/028_implement_strstr/strstr.c @@ -74,32 +74,17 @@ int strStr(char *haystack, char *needle) static int strStr(char *haystack, char *needle) { + int i, j; unsigned int hlen = strlen(haystack); unsigned int nlen = strlen(needle); - if (nlen == 0) { - return 0; - } - /* Brute force */ - int i, j; - for (i = 0; i < hlen; i++) { - int found = 1; - if (haystack[i] == needle[0]) { - for (j = 1; j < nlen; j++) { - if (i + j < hlen) { - if (haystack[i + j] != needle[j]) { - found = 0; - break; - } - } else { - return -1; - } - } - if (found) { - return i; - } - } + /* Corner condition: imagine nlen = 1 and it equals i < hlen */ + for (i = 0; i < hlen - nlen + 1; i++) { + for (j = 0; j < nlen && haystack[i + j] == needle[j]; j++) {} + if (j == nlen) { + return i; + } } return -1; From 71d24d724beda28cf0b1a5503cc3244ea26c4d3d Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 29 May 2020 09:46:10 +0800 Subject: [PATCH 046/211] Refine Signed-off-by: begeekmyfriend --- 001_two_sum/two_sum.c | 14 +++---- 015_three_sum/three_sum.c | 10 ++--- 018_four_sum/four_sum.c | 42 +++++++++---------- .../concatenation.c | 1 + 4 files changed, 34 insertions(+), 33 deletions(-) diff --git a/001_two_sum/two_sum.c b/001_two_sum/two_sum.c index 82a2770..f6a966d 100644 --- a/001_two_sum/two_sum.c +++ b/001_two_sum/two_sum.c @@ -11,7 +11,7 @@ static int compare(const void *a, const void *b) return ((struct object *) a)->val - ((struct object *) b)->val; } -static int * twosum(int *nums, int numsSize, int target) +static int * twosum(int *nums, int numsSize, int target, int *returnSize) { int i, j; struct object *objs = malloc(numsSize * sizeof(*objs)); @@ -21,19 +21,19 @@ static int * twosum(int *nums, int numsSize, int target) } qsort(objs, numsSize, sizeof(*objs), compare); - int count = 0; int *results = malloc(2 * sizeof(int)); i = 0; j = numsSize - 1; while (i < j) { - int diff = target - objs[i].val; - if (diff > objs[j].val) { - while (++i < j && objs[i].val == objs[i - 1].val) {} - } else if (diff < objs[j].val) { - while (--j > i && objs[j].val == objs[j + 1].val) {} + int sum = objs[i].val + objs[j].val; + if (sum < target) { + i++; + } else if (sum > target) { + j--; } else { results[0] = objs[i].index; results[1] = objs[j].index; + *returnSize = 2; return results; } } diff --git a/015_three_sum/three_sum.c b/015_three_sum/three_sum.c index 4a47c8a..17ff41e 100644 --- a/015_three_sum/three_sum.c +++ b/015_three_sum/three_sum.c @@ -9,11 +9,11 @@ static int compare(const void *a, const void *b) static void two_sum(int *nums, int low, int high, int target, int **results, int *count) { while (low < high) { - int diff = target - nums[low]; - if (diff > nums[high]) { - while (++low < high && nums[low] == nums[low - 1]) {} - } else if (diff < nums[high]) { - while (--high > low && nums[high] == nums[high + 1]) {} + int sum = nums[low] + nums[high]; + if (sum < target) { + low++; + } else if (sum > target) { + high--; } else { results[*count] = malloc(3 * sizeof(int)); results[*count][0] = -target; diff --git a/018_four_sum/four_sum.c b/018_four_sum/four_sum.c index f3032e1..87ce58b 100644 --- a/018_four_sum/four_sum.c +++ b/018_four_sum/four_sum.c @@ -7,22 +7,23 @@ 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) +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 *columnSizes) { int i; if (k == 2) { while (low < high) { - int diff = target - nums[low]; - if (diff > nums[high]) { - while (++low < high && nums[low] == nums[low - 1]) {} - } else if (diff < nums[high]) { - while (--high > low && nums[high] == nums[high + 1]) {} + int sum = nums[low] + nums[high]; + if (sum < target) { + low++; + } else if (sum > target) { + high--; } else { stack[len++] = nums[low]; stack[len++] = nums[high]; results[*count] = malloc(total * sizeof(int)); memcpy(results[*count], stack, total * sizeof(int)); + columnSizes[*count] = total; (*count)++; len -= 2; while (++low < high && nums[low] == nums[low - 1]) {} @@ -34,29 +35,28 @@ static void k_sum(int *nums, int low, int high, int target, int total, 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, results, count); + k_sum(nums, i + 1, high, target - nums[i], 4, k - 1, stack, len, results, count, columnSizes); len--; } } } /** - ** Return an array of arrays of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static int** fourSum(int* nums, int numsSize, int target, int* returnSize) -{ - if (numsSize < 4) { - return NULL; - } - - qsort(nums, numsSize, sizeof(*nums), compare); - + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ +int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes) { *returnSize = 0; int i, j, capacity = 50000; int **results = malloc(capacity * sizeof(int *)); - int *stack = malloc(4 * sizeof(int)); - k_sum(nums, 0, numsSize - 1, target, 4, 4, stack, 0, results, returnSize); + *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); + } return results; } diff --git a/030_substring_with_concatenation_of_all_words/concatenation.c b/030_substring_with_concatenation_of_all_words/concatenation.c index 25039b0..a2419df 100644 --- a/030_substring_with_concatenation_of_all_words/concatenation.c +++ b/030_substring_with_concatenation_of_all_words/concatenation.c @@ -128,6 +128,7 @@ static int *findSubstring(char *s, char **words, int wordsSize, int *returnSize) for (i = 0; s[i + length] != '\0'; i++) { memset(fqs, 0, wordsSize * sizeof(int)); for (j = 0; j < wordsSize; j++) { + /* concatenation */ int index = indexes[i + j * len]; if (index < 0 || ++fqs[index] > freqs[index]) { break; From 754133fbb04ff3d9afe98b400393396a9cc81326 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 30 May 2020 11:42:43 +0800 Subject: [PATCH 047/211] Refine Signed-off-by: begeekmyfriend --- 092_reverse_linked_list_ii/reverse_list.c | 24 +++++++-------- 206_reverse_linked_list/reverse_list.c | 36 +++++++++++++++-------- 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/092_reverse_linked_list_ii/reverse_list.c b/092_reverse_linked_list_ii/reverse_list.c index a3d5815..aebcf44 100644 --- a/092_reverse_linked_list_ii/reverse_list.c +++ b/092_reverse_linked_list_ii/reverse_list.c @@ -8,27 +8,25 @@ struct ListNode { static struct ListNode* reverseBetween(struct ListNode* head, int m, int n) { - int len = n - m + 1; - if (len == 1) { - return head; - } - + int i; struct ListNode dummy; - struct ListNode *p = head; struct ListNode *prev = &dummy; - prev->next = p; - while (--m > 0) { - prev = p; - p = p->next; + prev->next = head; + + for (i = 1; i < m; i++) { + prev = prev->next; } - struct ListNode *q = p->next; - while (--len > 0) { + struct ListNode *p = prev->next; + for (i = m; i < n; i++) { + struct ListNode *q = p->next; + /* deletion */ p->next = q->next; + /* insertion */ q->next = prev->next; prev->next = q; - q = p->next; } + return dummy.next; } diff --git a/206_reverse_linked_list/reverse_list.c b/206_reverse_linked_list/reverse_list.c index ed76673..c45ccc5 100644 --- a/206_reverse_linked_list/reverse_list.c +++ b/206_reverse_linked_list/reverse_list.c @@ -6,27 +6,39 @@ struct ListNode { struct ListNode *next; }; -static void recursive(struct ListNode *dummy, struct ListNode *prev, struct ListNode *p) +static struct ListNode *recursive(struct ListNode *prev, struct ListNode *p) { - if (p != NULL) { - prev->next = p->next; - p->next = dummy->next; - dummy->next = p; - recursive(dummy, prev, prev->next); + if (p == NULL) { + return prev; } + + struct ListNode *q = p->next; + p->next = prev; + return recursive(p, q); } static struct ListNode *reverseList(struct ListNode *head) { - if (head == NULL) { - return NULL; + return recursive(NULL, head); +} + + +/* Iteration */ +#if 0 +static struct ListNode *reverseList(struct ListNode *head) +{ + struct ListNode *prev = NULL; + struct ListNode *p = head; + while (p != NULL) { + struct ListNode *q = p->next; + p->next = prev; + prev = p; + p = q; } - struct ListNode dummy; - dummy.next = head; - recursive(&dummy, head, head->next); - return dummy.next; + return prev; } +#endif int main(int argc, char **argv) { From 4f58f7fb408f043d6628faba6f5b7a4d7c1c5c22 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 31 May 2020 12:06:36 +0800 Subject: [PATCH 048/211] Refine Signed-off-by: begeekmyfriend --- 051_n_queens/Makefile | 2 +- 051_n_queens/n_queens.c | 65 +++++++++++++++++++++++++++----------- 052_n_queens_ii/Makefile | 2 +- 052_n_queens_ii/n_queens.c | 37 ++++++++++++++++++---- 4 files changed, 80 insertions(+), 26 deletions(-) diff --git a/051_n_queens/Makefile b/051_n_queens/Makefile index 74f9e03..9efe93f 100644 --- a/051_n_queens/Makefile +++ b/051_n_queens/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o queen n_queens.c + gcc -O2 -o test n_queens.c diff --git a/051_n_queens/n_queens.c b/051_n_queens/n_queens.c index f01dc63..0b2a1c5 100644 --- a/051_n_queens/n_queens.c +++ b/051_n_queens/n_queens.c @@ -1,18 +1,18 @@ +#include #include #include #include -static inline int conflict(int *stack, int i, int j) +static inline int conflict(int *stack, int row, int col) { - int k; - for (k = 0; k < i; k++) { + int i; + for (i = 0; i < row; i++) { /* If occupied or in one line */ - if (j == stack[k] || abs(i - k) == abs(j - stack[k])) { - return 1; + if (col == stack[i] || abs(row - i) == abs(col - stack[i])) { + return true; } } - - return 0; + return false; } static inline void push(int *stack, int row, int col) @@ -35,11 +35,10 @@ static inline int top(int *stack, int n) return row; } } - return 0; } -static char **solution(int *stack, int n) +static char **solute(int *stack, int n) { int row, col; char **solution = malloc(n * sizeof(char *)); @@ -54,23 +53,50 @@ static char **solution(int *stack, int n) return solution; } +static void dfs(int n, int row, int *stack, char ***solutions, int *count, int *col_sizes) +{ + int col; + if (row == n) { + solutions[*count] = solute(stack, n); + col_sizes[*count] = n; + (*count)++; + } else { + for (col = 0; col < n; col++) { + if (row == 0 || !conflict(stack, row, col)) { + stack[row] = col; + dfs(n, row + 1, stack, solutions, count, col_sizes); + continue; + } + } + } +} + /** - ** Return an array of arrays of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -char*** solveNQueens(int n, int *returnSize) { + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ +char *** solveNQueens(int n, int* returnSize, int** returnColumnSizes) +{ int row = 0, col = 0, sum = 0; char ***solutions = malloc(1000 * sizeof(char **)); - + *returnColumnSizes = malloc(1000 * sizeof(int)); int *stack = malloc(n * sizeof(int)); + +#if 1 + *returnSize = 0; + dfs(n, 0, stack, solutions, returnSize, *returnColumnSizes); + return solutions; +#else for (row = 0; row < n; row++) { stack[row] = -1; } if (n == 1) { stack[0] = 0; - solutions[0] = solution(stack, n); + solutions[0] = solute(stack, n); *returnSize = 1; + *returnColumnSizes[0] = 1; return solutions; } @@ -82,7 +108,6 @@ char*** solveNQueens(int n, int *returnSize) { /* No other positions in this row and therefore backtracking */ if (--row < 0) { /* All solution provided */ - free(stack); *returnSize = sum; return solutions; } @@ -100,7 +125,9 @@ char*** solveNQueens(int n, int *returnSize) { /* Full stack, a new complete solution */ row = top(stack, n); if (row == n - 1) { - solutions[sum++] = solution(stack, n); + solutions[sum] = solute(stack, n); + (*returnColumnSizes)[sum] = n; + sum++; } /* Move on to find if there are still other solutions */ @@ -109,6 +136,7 @@ char*** solveNQueens(int n, int *returnSize) { } assert(0); +#endif } int main(int argc, char **argv) @@ -121,7 +149,8 @@ int main(int argc, char **argv) } n = atoi(argv[1]); - char ***solutions = solveNQueens(n, &num_of_solution); + int *col_sizes; + char ***solutions = solveNQueens(n, &num_of_solution, &col_sizes); for (i = 0; i < num_of_solution; i++) { char **solution = solutions[i]; for (row = 0; row < n; row++) { diff --git a/052_n_queens_ii/Makefile b/052_n_queens_ii/Makefile index 74f9e03..9efe93f 100644 --- a/052_n_queens_ii/Makefile +++ b/052_n_queens_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o queen n_queens.c + gcc -O2 -o test n_queens.c diff --git a/052_n_queens_ii/n_queens.c b/052_n_queens_ii/n_queens.c index e093550..17f387b 100644 --- a/052_n_queens_ii/n_queens.c +++ b/052_n_queens_ii/n_queens.c @@ -1,16 +1,19 @@ +#include #include #include #include -static inline int conflict(int *stack, int i, int j) + + +static inline int conflict(int *stack, int row, int col) { - int k; - for (k = 0; k < i; k++) { + int i; + for (i = 0; i < row; i++) { /* If occupied or in one line */ - if (j == stack[k] || abs(i - k) == abs(j - stack[k])) { - return 1; + if (col == stack[i] || abs(row - i) == abs(col - stack[i])) { + return true; } } - return 0; + return false; } static inline void push(int *stack, int row, int col) @@ -36,7 +39,28 @@ static inline int top(int *stack, int n) return 0; } +static void dfs(int n, int row, int *stack, int *count) +{ + int col; + if (row == n) { + (*count)++; + } else { + for (col = 0; col < n; col++) { + if (row == 0 || !conflict(stack, row, col)) { + stack[row] = col; + dfs(n, row + 1, stack, count); + } + } + } +} + int totalNQueens(int n) { +#if 1 + int count = 0; + int *stack = malloc(n * sizeof(int)); + dfs(n, 0, stack, &count); + return count; +#else int row = 0, col = 0, sum = 0, cap = 1; int *stack = malloc(n * sizeof(int)); for (row = 0; row < n; row++) { @@ -79,6 +103,7 @@ int totalNQueens(int n) { col = pop(stack, row); col++; } +#endif } int main(int argc, char **argv) From ef086ebe5ac46477498b4e6c143ded5d0eaf0856 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 1 Jun 2020 16:28:19 +0800 Subject: [PATCH 049/211] Refine Signed-off-by: begeekmyfriend --- .../permutation_sequence.c | 48 +++++++++++-------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/060_permutation_sequence/permutation_sequence.c b/060_permutation_sequence/permutation_sequence.c index 9e63960..2b17558 100644 --- a/060_permutation_sequence/permutation_sequence.c +++ b/060_permutation_sequence/permutation_sequence.c @@ -1,34 +1,40 @@ +#include #include #include #include -static int factorial(int n) -{ - if (n == 0) { - return 0; - } else if (n == 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} - static char* getPermutation(int n, int k) { int i; - int *permutation = malloc(n * sizeof(int)); - for (i = 0; i < n; i++) { - permutation[i] = i + 1; - } - char *result = malloc(n + 1); + bool *used = malloc(n * sizeof(bool)); + memset(used, false, n * sizeof(bool)); + + int total = 1; + for (i = 1; i <= n; i++) { + total *= i; /* n! */ + } + + k = k - 1; /* Begin with 0 */ for (i = 0; i < n; i++) { - int fac = factorial(n - i - 1); - int j = k > 1 ? (k - 1) / fac : 0; - result[i] = permutation[j] + '0'; - k -= j * fac; - memmove(permutation + j, permutation + j + 1, (n - j) * sizeof(int)); + /* Total elements in each group */ + total /= (n - i); + int gid = k / total; + k %= total; + + int x = -1; + int count = 0; + /* Search in the remaining numbers */ + while (count <= gid) { + x = (x + 1) % n; + if (!used[x]) { + count++; + } + } + used[x] = true; + result[i] = x + 1 + '0'; } + result[n] = '\0'; return result; } From 8f7fe310845c8df1951f7f2d26930822b67f61df Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 2 Jun 2020 16:10:19 +0800 Subject: [PATCH 050/211] Refine Signed-off-by: begeekmyfriend --- .../longest_substring_without_repeat.c | 2 + .../median_of_two_sorted_array.c | 51 +++++++------------ 2 files changed, 20 insertions(+), 33 deletions(-) diff --git a/003_longest_substring_without_repeat/longest_substring_without_repeat.c b/003_longest_substring_without_repeat/longest_substring_without_repeat.c index 27fc434..2f067ce 100644 --- a/003_longest_substring_without_repeat/longest_substring_without_repeat.c +++ b/003_longest_substring_without_repeat/longest_substring_without_repeat.c @@ -15,8 +15,10 @@ static int lengthOfLongestSubstring(char *s) len++; } else { if (index - offset[*s] > len) { + /* not include in substring, go on increasing */ len++; } else { + /* count from scratch */ len = index - offset[*s]; } } diff --git a/004_median_of_two_sorted_array/median_of_two_sorted_array.c b/004_median_of_two_sorted_array/median_of_two_sorted_array.c index 05c2998..d1472f7 100644 --- a/004_median_of_two_sorted_array/median_of_two_sorted_array.c +++ b/004_median_of_two_sorted_array/median_of_two_sorted_array.c @@ -1,42 +1,27 @@ #include #include -static double find_kth(int a[], int alen, int b[], int blen, int k) -{ - /* Always assume that alen is equal or smaller than blen */ - if (alen > blen) { - return find_kth(b, blen, a, alen, k); - } - - if (alen == 0) { - return b[k - 1]; - } - - if (k == 1) { - return a[0] < b[0] ? a[0] : b[0]; - } - - /* Divide k into two parts */ - int ia = k / 2 < alen ? k / 2 : alen; - int ib = k - ia; - if (a[ia - 1] < b[ib - 1]) { - /* a[ia - 1] must be ahead of k-th */ - return find_kth(a + ia, alen - ia, b, blen, k - ia); - } else if (a[ia - 1] > b[ib - 1]) { - /* b[ib - 1] must be ahead of k-th */ - return find_kth(a, alen, b + ib, blen - ib, k - ib); - } else { - return a[ia - 1]; - } -} - static double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { - int half = (nums1Size + nums2Size) / 2; - if ((nums1Size + nums2Size) & 0x1) { - return find_kth(nums1, nums1Size, nums2, nums2Size, half + 1); + int sum = nums1Size + nums2Size; + int *nums = malloc(sizeof(int) * sum); + int i = 0, j = 0, k = 0; + int half = sum / 2 + 1; + while (k < half) { + int n; + if (i < nums1Size && j < nums2Size) { + n = (nums1[i] < nums2[j]) ? nums1[i++] : nums2[j++]; + } else if (i < nums1Size) { + n = nums1[i++]; + } else if (j < nums2Size) { + n = nums2[j++]; + } + nums[k++] = n; + } + if (sum % 2) { + return nums[k-1]; } else { - return (find_kth(nums1, nums1Size, nums2, nums2Size, half) + find_kth(nums1, nums1Size, nums2, nums2Size, half + 1)) / 2; + return (nums[k-1] + nums[k-2]) / 2.0; } } From 5bfc56802c116ac34bf07d87f41cbd4f27aaff87 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 3 Jun 2020 09:56:55 +0800 Subject: [PATCH 051/211] Refine Signed-off-by: begeekmyfriend --- 011_container_with_most_water/container.c | 8 ++--- 021_merge_two_sorted_lists/merge_lists.c | 36 ++++++++++------------- 2 files changed, 17 insertions(+), 27 deletions(-) diff --git a/011_container_with_most_water/container.c b/011_container_with_most_water/container.c index 2534ab3..22d667e 100644 --- a/011_container_with_most_water/container.c +++ b/011_container_with_most_water/container.c @@ -9,13 +9,9 @@ static int maxArea(int* height, int heightSize) int area = (max - min) * (height[min] < height[max] ? height[min] : height[max]); area_max = area > area_max ? area : area_max; if (height[min] < height[max]) { - while (++min < max && height[min] <= height[min - 1]) { - continue; - } + min++; } else { - while (min < --max && height[max] <= height[max + 1]) { - continue; - } + max--; } } return area_max; diff --git a/021_merge_two_sorted_lists/merge_lists.c b/021_merge_two_sorted_lists/merge_lists.c index 28ee2d3..6bca7a9 100644 --- a/021_merge_two_sorted_lists/merge_lists.c +++ b/021_merge_two_sorted_lists/merge_lists.c @@ -8,33 +8,27 @@ struct ListNode { static struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { - struct ListNode dummy, *tail = &dummy; - dummy.next = NULL; + struct ListNode dummy; + struct ListNode *prev = &dummy; + dummy.next = l1; while (l1 != NULL || l2 != NULL) { - struct ListNode *node = malloc(sizeof(*node)); - node->next = NULL; - tail->next = node; - tail = node; - if (l1 != NULL) { - if (l2 != NULL) { - if (l1->val < l2->val) { - node->val = l1->val; - l1 = l1->next; - } else { - node->val = l2->val; - l2 = l2->next; - } - } else { - node->val = l1->val; - l1 = l1->next; - } + if (l1->val <= l2->val) { + prev = l1; + l1 = l1->next; } else { - node->val = l2->val; - l2 = l2->next; + struct ListNode *tmp = l2->next; + l2->next = l1; + prev->next = l2; + prev = l2; + l2 = tmp; } } + if (l2 != NULL) { + prev->next = l2; + } + return dummy.next; } From 7afe0d92400b78ade25c7f679fd93b94c8235db7 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 4 Jun 2020 09:22:36 +0800 Subject: [PATCH 052/211] Refine Signed-off-by: begeekmyfriend --- 024_swap_nodes_in_pairs/swap_nodes.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/024_swap_nodes_in_pairs/swap_nodes.c b/024_swap_nodes_in_pairs/swap_nodes.c index b94fa29..dea9621 100644 --- a/024_swap_nodes_in_pairs/swap_nodes.c +++ b/024_swap_nodes_in_pairs/swap_nodes.c @@ -15,16 +15,17 @@ static struct ListNode* swapPairs(struct ListNode* head) dummy.next = head; struct ListNode *prev = &dummy; struct ListNode *p = dummy.next; - struct ListNode *next = p->next; - while (p != NULL && next != NULL) { - prev->next = next; - p->next = next->next; - next->next = p; + + while (p != NULL && p->next != NULL) { + struct ListNode *q = p->next; + /* deletion */ + p->next = q->next; + /* insertion */ + q->next = p; + prev->next = q; + /* iteration */ prev = p; p = p->next; - if (p != NULL) { - next = p->next; - } } return dummy.next; } From b5ea0342e6a81e8b7eab3801ac42ab129829b9d3 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 5 Jun 2020 18:21:47 +0800 Subject: [PATCH 053/211] Refine Signed-off-by: begeekmyfriend --- 046_permutations/permutations.c | 37 +++++++++++++++++++----------- 047_permutations_ii/permutations.c | 23 +++++++++++-------- 077_combinations/combinations.c | 23 ++++++++----------- 078_subsets/subsets.c | 14 +++++------ 090_subsets_ii/subsets.c | 18 ++++++++------- 5 files changed, 63 insertions(+), 52 deletions(-) diff --git a/046_permutations/permutations.c b/046_permutations/permutations.c index 8ffc9d9..009669c 100644 --- a/046_permutations/permutations.c +++ b/046_permutations/permutations.c @@ -10,32 +10,42 @@ static void swap(int *a, int *b) *b = tmp; } -static void dfs(int *nums, int size, int start, int **results, int *count) +static void dfs(int *nums, int size, bool *used, int *stack, + int len, int **results, int *count, int *col_size) { int i; - if (start == size) { + if (len == size) { results[*count] = malloc(size * sizeof(int)); - memcpy(results[*count], nums, size * sizeof(int)); + memcpy(results[*count], stack, size * sizeof(int)); + col_size[*count] = size; (*count)++; } else { - for (i = start; i < size; i++) { - swap(nums + start, nums + i); - dfs(nums, size, start + 1, results, count); - swap(nums + start, nums + i); + for (i = 0; i < size; i++) { + if (!used[i]) { + used[i] = true; + stack[len] = nums[i]; + dfs(nums, size, used, stack, len + 1, results, count, col_size); + used[i] = false; + } } } } /** - ** Return an array of arrays of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static int **permute(int* nums, int numsSize, int* returnSize) + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ +static int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { int count = 0, cap = 5000; int **results = malloc(cap * sizeof(int *)); + bool *used = malloc(numsSize * sizeof(bool)); + int *stack = malloc(numsSize * sizeof(int)); *returnSize = 0; - dfs(nums, numsSize, 0, results, returnSize); + *returnColumnSizes = malloc(cap * sizeof(int)); + memset(used, false, numsSize * sizeof(bool)); + dfs(nums, numsSize, used, stack, 0, results, returnSize, *returnColumnSizes); return results; } @@ -52,7 +62,8 @@ int main(int argc, char **argv) nums[i] = atoi(argv[i + 1]); } - int **lists = permute(nums, argc - 1, &count); + int *size; + int **lists = permute(nums, argc - 1, &count, &size); for (i = 0; i < count; i++) { for (j = 0; j < argc - 1; j++) { printf("%d", lists[i][j]); diff --git a/047_permutations_ii/permutations.c b/047_permutations_ii/permutations.c index b357ef1..acf74df 100644 --- a/047_permutations_ii/permutations.c +++ b/047_permutations_ii/permutations.c @@ -8,13 +8,14 @@ static int compare(const void *a, const void *b) return *(int *) a - *(int *) b; } -static void dfs(int *nums, int size, int *stack, int len, - bool *used, int **results, int *count) +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 { for (i = 0; i < size; i++) { @@ -22,7 +23,7 @@ static void dfs(int *nums, int size, int *stack, int len, if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; used[i] = true; stack[len] = nums[i]; - dfs(nums, size, stack, len + 1, used, results, count); + dfs(nums, size, used, stack, len + 1, results, count, col_size); used[i] = false; } } @@ -30,10 +31,11 @@ static void dfs(int *nums, int size, int *stack, int len, } /** - ** Return an array of arrays of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static int **permute(int* nums, int numsSize, int* returnSize) + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ +static int **permute(int* nums, int numsSize, int* returnSize, int **returnColumnSize) { qsort(nums, numsSize, sizeof(int), compare); @@ -43,7 +45,8 @@ static int **permute(int* nums, int numsSize, int* returnSize) bool *used = malloc(numsSize); memset(used, false, numsSize); *returnSize = 0; - dfs(nums, numsSize, stack, 0, used, results, returnSize); + *returnColumnSize = malloc(cap * sizeof(int)); + dfs(nums, numsSize, used, stack, 0, results, returnSize, *returnColumnSize); return results; } @@ -58,10 +61,10 @@ int main(int argc, char **argv) int *nums = malloc(count * sizeof(int)); for (i = 0; i < count; i++) { nums[i] = atoi(argv[i + 1]); - printf("%d\n", nums[i]); } - int **lists = permute(nums, argc - 1, &count); + int *size; + int **lists = permute(nums, argc - 1, &count, &size); for (i = 0; i < count; i++) { for (j = 0; j < argc - 1; j++) { printf("%d", lists[i][j]); diff --git a/077_combinations/combinations.c b/077_combinations/combinations.c index cbe320c..7625498 100644 --- a/077_combinations/combinations.c +++ b/077_combinations/combinations.c @@ -4,7 +4,7 @@ #include static void dfs(int n, int k, int start, int *stack, int len, - bool *used, int *col_sizes, int **results, int *count) + int **results, int *count, int *col_sizes) { int i; if (len == k) { @@ -14,30 +14,25 @@ static void dfs(int n, int k, int start, int *stack, int len, (*count)++; } else { for (i = start; i <= n; i++) { - if (!used[i]) { - stack[len] = i; - used[i] = true; - dfs(n, k, i + 1, stack, len + 1, used, col_sizes, results, count); - used[i] = false; - } + /* No used marks since the order does not matter */ + stack[len] = i; + dfs(n, k, i + 1, stack, len + 1, results, count, col_sizes); } } } /** * Return an array of arrays of size *returnSize. - * The sizes of the arrays are returned as *columnSizes array. + * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ -int** combine(int n, int k, int** columnSizes, int* returnSize) { +int** combine(int n, int k, int* returnSize, int** returnColumnSizes) { int capacity = 10000; int count = 0; int **results = malloc(capacity * sizeof(int *)); int *stack = malloc(k * sizeof(int)); - bool *used = malloc((n + 1) * sizeof(bool)); - memset(used, false, n + 1); - *columnSizes = malloc(capacity * sizeof(int)); - dfs(n, k, 1, stack, 0, used, *columnSizes, results, &count); + *returnColumnSizes = malloc(capacity * sizeof(int)); + dfs(n, k, 1, stack, 0, results, &count, *returnColumnSizes); *returnSize = count; return results; } @@ -50,7 +45,7 @@ int main(int argc, char **argv) } int i, j, *col_sizes, count = 0; - int **lists = combine(atoi(argv[1]), atoi(argv[2]), &col_sizes, &count); + int **lists = combine(atoi(argv[1]), atoi(argv[2]), &count, &col_sizes); for (i = 0; i < count; i++) { for (j = 0; j < col_sizes[i]; j++) { printf("%d ", lists[i][j]); diff --git a/078_subsets/subsets.c b/078_subsets/subsets.c index 6a4d18b..a98cfcf 100644 --- a/078_subsets/subsets.c +++ b/078_subsets/subsets.c @@ -3,7 +3,7 @@ #include static void dfs(int *nums, int size, int start, int *buf, - int len, int **sets, int *sizes, int *count) + int len, int **sets, int *count, int *sizes) { int i; sets[*count] = malloc(len * sizeof(int)); @@ -12,23 +12,23 @@ static void dfs(int *nums, int size, int start, int *buf, (*count)++; for (i = start; i < size; i++) { buf[len] = nums[i]; - dfs(nums, size, i + 1, buf, len + 1, sets, sizes, count); + dfs(nums, size, i + 1, buf, len + 1, sets, count, sizes); } } /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. + ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) +int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { int capacity = 5000; int **sets = malloc(capacity * sizeof(int *)); int *buf = malloc(numsSize * sizeof(int)); - *columnSizes = malloc(capacity * sizeof(int)); + *returnColumnSizes = malloc(capacity * sizeof(int)); *returnSize = 0; - dfs(nums, numsSize, 0, buf, 0, sets, *columnSizes, returnSize); + dfs(nums, numsSize, 0, buf, 0, sets, returnSize, *returnColumnSizes); return sets; } @@ -46,7 +46,7 @@ int main(int argc, char **argv) } int *sizes; int count; - int **lists = subsets(nums, size, &sizes, &count); + int **lists = subsets(nums, size, &count, &sizes); for (i = 0; i < count; i++) { for (j = 0; j < sizes[i]; j++) { printf("%d ", lists[i][j]); diff --git a/090_subsets_ii/subsets.c b/090_subsets_ii/subsets.c index 09a38f3..095676e 100644 --- a/090_subsets_ii/subsets.c +++ b/090_subsets_ii/subsets.c @@ -9,7 +9,7 @@ static inline int compare(const void *a, const void *b) } static void dfs(int *nums, int size, int start, int *buf, int level, - bool *used, int **sets, int *sizes, int *count) + bool *used, int **sets, int *count, int *sizes) { int i; sets[*count] = malloc(level * sizeof(int)); @@ -18,10 +18,12 @@ static void dfs(int *nums, int size, int start, int *buf, int level, (*count)++; for (i = start; i < size; i++) { if (!used[i]) { - if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) continue; + if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { + continue; + } used[i] = true; buf[level] = nums[i]; - dfs(nums, size, i + 1, buf, level + 1, used, sets, sizes, count); + dfs(nums, size, i + 1, buf, level + 1, used, sets, count, sizes); used[i] = false; } } @@ -29,10 +31,10 @@ static void dfs(int *nums, int size, int start, int *buf, int level, /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. + ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -static int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) +static int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { qsort(nums, numsSize, sizeof(int), compare); int capacity = 5000; @@ -40,9 +42,9 @@ static int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize int *buf = malloc(numsSize * sizeof(int)); bool *used = malloc(numsSize); memset(used, false, numsSize); - *columnSizes = malloc(capacity * sizeof(int)); + *returnColumnSizes = malloc(capacity * sizeof(int)); *returnSize = 0; - dfs(nums, numsSize, 0, buf, 0, used, sets, *columnSizes, returnSize); + dfs(nums, numsSize, 0, buf, 0, used, sets, returnSize, *returnColumnSizes); return sets; } @@ -60,7 +62,7 @@ int main(int argc, char **argv) } int *sizes; int count; - int **lists = subsets(nums, size, &sizes, &count); + int **lists = subsets(nums, size, &count, &sizes); for (i = 0; i < count; i++) { for (j = 0; j < sizes[i]; j++) { printf("%d ", lists[i][j]); From 3649f22332187de030d8b66dfbebc65e0c5aa198 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 6 Jun 2020 11:51:08 +0800 Subject: [PATCH 054/211] Refine Signed-off-by: begeekmyfriend --- 039_combination_sum/combination_sum.c | 18 +++---- 040_combination_sum_ii/combination_sum.c | 16 +++--- 042_trapping_rain_water/trap_water.c | 64 +++++++++++------------- 3 files changed, 47 insertions(+), 51 deletions(-) diff --git a/039_combination_sum/combination_sum.c b/039_combination_sum/combination_sum.c index 8ec6845..66b597d 100644 --- a/039_combination_sum/combination_sum.c +++ b/039_combination_sum/combination_sum.c @@ -3,7 +3,7 @@ #include static void dfs(int *nums, int size, int start, int target, int *stack, - int len, int **results, int *column_sizes, int *count) + int len, int **results, int *count, int *column_sizes) { int i; if (target == 0) { @@ -24,17 +24,17 @@ static void dfs(int *nums, int size, int start, int target, int *stack, /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** The sizes of the arrays are returned as *returnColumnSizes array. + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static int** combinationSum(int* candidates, int candidatesSize, int target, int** columnSizes, int* returnSize) +static int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int **returnColumnSizes) { - int cap = 100; - int *stack = malloc(target * sizeof(int)); + int cap = 200; + int *stack = malloc(candidatesSize * sizeof(int)); int **results = malloc(cap * sizeof(int *)); - *columnSizes = malloc(cap * sizeof(int)); + *returnColumnSizes = malloc(cap * sizeof(int)); *returnSize = 0; - dfs(candidates, candidatesSize, 0, target, stack, 0, results, *columnSizes, returnSize); + dfs(candidates, candidatesSize, 0, target, stack, 0, results, returnSize, *returnColumnSizes); return results; } @@ -53,7 +53,7 @@ int main(int argc, char **argv) } int *sizes; - int **lists = combinationSum(nums, argc - 2, target, &sizes, &count); + int **lists = combinationSum(nums, argc - 2, target, &count, &sizes); for (i = 0; i < count; i++) { for (j = 0; j < sizes[i]; j++) { printf("%d ", lists[i][j]); diff --git a/040_combination_sum_ii/combination_sum.c b/040_combination_sum_ii/combination_sum.c index 5ffa641..44c8ed5 100644 --- a/040_combination_sum_ii/combination_sum.c +++ b/040_combination_sum_ii/combination_sum.c @@ -9,7 +9,7 @@ static int compare(const void *a, const void *b) } static void dfs(int *nums, int size, int start, int target, int *solution, int len, - bool *used, int **results, int *column_sizes, int *count) + bool *used, int **results, int *count, int *column_sizes) { int i; if (target == 0) { @@ -23,7 +23,7 @@ static void dfs(int *nums, int size, int start, int target, int *solution, int l if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) continue; used[i] = true; solution[len] = nums[i]; - dfs(nums, size, i + 1, target - nums[i], solution, len + 1, used, results, column_sizes, count); + dfs(nums, size, i + 1, target - nums[i], solution, len + 1, used, results, count, column_sizes); used[i] = false; } } @@ -32,10 +32,10 @@ static void dfs(int *nums, int size, int start, int target, int *solution, int l /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** The sizes of the arrays are returned as *returnColumnSizes array. + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static int** combinationSum(int* candidates, int candidatesSize, int target, int** columnSizes, int* returnSize) +static int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) { qsort(candidates, candidatesSize, sizeof(int), compare); @@ -43,9 +43,9 @@ static int** combinationSum(int* candidates, int candidatesSize, int target, int int **results = malloc(100 * sizeof(int *)); bool *used = malloc(candidatesSize); memset(used, false, candidatesSize); - *columnSizes = malloc(100 * sizeof(int)); + *returnColumnSizes = malloc(100 * sizeof(int)); *returnSize = 0; - dfs(candidates, candidatesSize, 0, target, solution, 0, used, results, *columnSizes, returnSize); + dfs(candidates, candidatesSize, 0, target, solution, 0, used, results, returnSize, *returnColumnSizes); return results; } @@ -64,7 +64,7 @@ int main(int argc, char **argv) } int *sizes; - int **lists = combinationSum(nums, argc - 2, target, &sizes, &count); + int **lists = combinationSum(nums, argc - 2, target, &count, &sizes); for (i = 0; i < count; i++) { for (j = 0; j < sizes[i]; j++) { printf("%d ", lists[i][j]); diff --git a/042_trapping_rain_water/trap_water.c b/042_trapping_rain_water/trap_water.c index 2c2393a..343b8b3 100644 --- a/042_trapping_rain_water/trap_water.c +++ b/042_trapping_rain_water/trap_water.c @@ -1,49 +1,45 @@ #include #include + +static inline int max(int a, int b) +{ + return a > b ? a : b; +} + +static inline int min(int a, int b) +{ + return a < b ? a : b; +} + static int trap(int* height, int heightSize) { - if (heightSize < 2) { + if (heightSize < 1) { return 0; } - int i, j, top0 = -1, top1 = -1, sum = 0, level = 0; - for (i = 0; i < heightSize; i++) { - if (height[i] > 0) { - top0 = i; - break; - } + int i; + int *lh = malloc(heightSize * sizeof(int)); + int *rh = malloc(heightSize * sizeof(int)); + + /* restore the max height in the left side of [i] (included) */ + lh[0] = height[0]; + for (i = 1; i < heightSize; i++) { + lh[i] = max(height[i], lh[i - 1]); } - while (i < heightSize) { - top1 = -1; - for (j = i + 1; j < heightSize; j++) { - if (height[j] >= height[j - 1]) { - if (top1 < 0 || height[j] >= height[top1]) { - top1 = j; - } - if (height[j] >= height[top0]) { - break; - } - } - } - - if (top1 >= 0) { - int level = height[top0] < height[top1] ? height[top0] : height[top1]; - while (i < top1) { - if (level > height[i]) { - sum += level - height[i]; - } - i++; - } - top0 = top1; - i = top1; - } else { - i = j; - } + /* restore the max height in the right side of [i] (included) */ + rh[heightSize - 1] = height[heightSize - 1]; + for (i = heightSize - 2; i >= 0; i--) { + rh[i] = max(height[i], rh[i + 1]); + } + + int capacity = 0; + for (i = 0; i < heightSize; i++) { + capacity += min(lh[i], rh[i]) - height[i]; } - return sum; + return capacity; } int main(int argc, char **argv) From 308683ccde483d3d970139e827d4fb08340da2b8 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 7 Jun 2020 08:08:30 +0800 Subject: [PATCH 055/211] Refine Signed-off-by: begeekmyfriend --- 001_two_sum/two_sum.c | 5 ++- 001_two_sum/two_sum.py | 11 +++++ 002_add_two_numbers/add_two_numbers.c | 58 ++++++++++++++------------- 3 files changed, 44 insertions(+), 30 deletions(-) create mode 100644 001_two_sum/two_sum.py diff --git a/001_two_sum/two_sum.c b/001_two_sum/two_sum.c index f6a966d..e91c9ff 100644 --- a/001_two_sum/two_sum.c +++ b/001_two_sum/two_sum.c @@ -47,9 +47,10 @@ int main(void) //int nums[] = {0,4,3,0}; //int target = 0; int nums[] = { 3, 2, 3 }; - int count = sizeof(nums) / sizeof(*nums); + int size = sizeof(nums) / sizeof(*nums); int target = 6; - int *indexes = twosum(nums, count, target); + int count = 0; + int *indexes = twosum(nums, size, target, &count); if (indexes != NULL) { printf("%d %d\n", indexes[0], indexes[1]); } else { diff --git a/001_two_sum/two_sum.py b/001_two_sum/two_sum.py new file mode 100644 index 0000000..2606238 --- /dev/null +++ b/001_two_sum/two_sum.py @@ -0,0 +1,11 @@ +class Solution: + def twoSum(self, nums, target): + h = {} + for i, n in enumerate(nums): + other = target - n + if other not in h: + h[n] = i + else: + return [h[other], i] + +print(Solution().twoSum([-1, -2, -3, -4, -5], -8)) diff --git a/002_add_two_numbers/add_two_numbers.c b/002_add_two_numbers/add_two_numbers.c index 3e7872b..19873e9 100644 --- a/002_add_two_numbers/add_two_numbers.c +++ b/002_add_two_numbers/add_two_numbers.c @@ -10,48 +10,50 @@ struct ListNode { static struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { - int carry_num = 0; - int first = 1; - struct ListNode *res = NULL; - struct ListNode *p = NULL; - struct ListNode *prev = p; + int carry = 0; + struct ListNode dummy; + struct ListNode *p = l1, *prev = &dummy; - while (l1 != NULL || l2 != NULL || carry_num) { + dummy.next = p; + while (l1 != NULL || l2 != NULL) { int sum = 0; - int last_carry = carry_num; + int last_carry = carry; + if (l1 != NULL) { + if (p == NULL) { + /* p never be NULL */ + prev->next = l1; + p = l1; + } sum += l1->val; l1 = l1->next; } + if (l2 != NULL) { + if (p == NULL) { + /* p never be NULL */ + prev->next = l2; + p = l2; + } sum += l2->val; l2 = l2->next; } - if (sum >= 10) { - sum -= 10; - carry_num = 1; - } else { - carry_num = 0; - } + + sum += last_carry; + carry = sum / 10; + p->val = sum % 10; + prev = p; + p = p->next; + } + if (carry) { p = malloc(sizeof(*p)); - if (first) { - res = p; - first = 0; - } - p->val = sum + last_carry; - if (p->val >= 10) { - p->val -= 10; - carry_num = 1; - } + p->val = carry; p->next = NULL; - if (prev != NULL) { - prev->next = p; - } - prev = p; + prev->next = p; } - - return res; + + return dummy.next; } static struct ListNode *node_build(const char *digits) From 4d550a5ad982d1fbbce942d78948430868b3efd9 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 7 Jun 2020 08:28:48 +0800 Subject: [PATCH 056/211] Refine Signed-off-by: begeekmyfriend --- 021_merge_two_sorted_lists/merge_lists.c | 2 +- 239_sliding_window_maximum/slide_window.c | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/021_merge_two_sorted_lists/merge_lists.c b/021_merge_two_sorted_lists/merge_lists.c index 6bca7a9..34ecdb0 100644 --- a/021_merge_two_sorted_lists/merge_lists.c +++ b/021_merge_two_sorted_lists/merge_lists.c @@ -12,7 +12,7 @@ static struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) struct ListNode *prev = &dummy; dummy.next = l1; - while (l1 != NULL || l2 != NULL) { + while (l1 != NULL && l2 != NULL) { if (l1->val <= l2->val) { prev = l1; l1 = l1->next; diff --git a/239_sliding_window_maximum/slide_window.c b/239_sliding_window_maximum/slide_window.c index 4e7ded9..5f5011b 100644 --- a/239_sliding_window_maximum/slide_window.c +++ b/239_sliding_window_maximum/slide_window.c @@ -13,16 +13,19 @@ int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) int *results = malloc((numsSize - k + 1) * sizeof(int)); for (i = 0; i < numsSize; i++) { - /* monotonous decreasing */ + /* keep the elements in slide window monotonous decreasing */ while (tail > head && nums[i] >= nums[indexes[tail - 1]]) { + /* squeeze out the previous smaller ones */ tail--; } - indexes[tail++] = i; + /* Pipe: first in last out */ + indexes[tail++] = i; if (indexes[head] <= i - k) { head++; } + /* k - 1 is the end of the first sliding window */ if (i >= k - 1) { results[count++] = nums[indexes[head]]; } From 82870a01812d14ba658d32adf71408265d1ea099 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 8 Jun 2020 11:33:02 +0800 Subject: [PATCH 057/211] Refine Signed-off-by: begeekmyfriend --- .../bst_max_path.c | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/124_binary_tree_maximum_path_sum/bst_max_path.c b/124_binary_tree_maximum_path_sum/bst_max_path.c index bf9df29..e3ecad1 100644 --- a/124_binary_tree_maximum_path_sum/bst_max_path.c +++ b/124_binary_tree_maximum_path_sum/bst_max_path.c @@ -8,35 +8,36 @@ struct TreeNode { struct TreeNode *right; }; -static int partition(struct TreeNode *node, int *max) +static inline int maximum(int a, int b) { - int left_max = 0; - int right_max = 0; + return a > b ? a : b; +} - if (node->left != NULL) { - left_max = partition(node->left, max); +static int dfs(struct TreeNode *root, int *max) +{ + if (root == NULL) { + return 0; } - if (node->right != NULL) { - right_max = partition(node->right, max); - } + /* In case of negative node value */ + int l = maximum(dfs(root->left, max), 0); + int r = maximum(dfs(root->right, max), 0); - int sum = node->val + left_max + right_max; + int sum = root->val + l + r; if (sum > *max) { *max = sum; } - return node->val + (right_max > left_max ? right_max : left_max); + /* The return value does not equal the sum value + * since we need to return path through the root node + */ + return root->val + maximum(l, r); } static int maxPathSum(struct TreeNode* root) { - if (root == NULL) { - return 0; - } - int max = INT_MIN; - partition(root, &max); + dfs(root, &max); return max; } From 131626892bfc50a03737b46b7a753ff842f590a2 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 9 Jun 2020 10:42:46 +0800 Subject: [PATCH 058/211] Refine Signed-off-by: begeekmyfriend --- .../valid_parentheses.c | 35 +++++++++---------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/032_longest_valid_parentheses/valid_parentheses.c b/032_longest_valid_parentheses/valid_parentheses.c index f4854d3..4b68595 100644 --- a/032_longest_valid_parentheses/valid_parentheses.c +++ b/032_longest_valid_parentheses/valid_parentheses.c @@ -1,40 +1,37 @@ #include #include + static int longestValidParentheses(char* s) { - int cap = 8000, error = -1; - int length = 0, max_length = 0; - char *p = s; + int i, cap = 18000, invalid = -1; + int len = 0, max_len = 0; int *stack = malloc(cap * sizeof(int)); int *top = stack; - while (*p != '\0') { - if (*p == '(') { - if (top + 1 - stack >= cap) { - cap *= 2; - stack = realloc(stack, cap * sizeof(int)); - } - *top++ = p - s; + /* We only restore index of '(' since restrain of space */ + for (i = 0; s[i] != '\0'; i++) { + if (s[i] == '(') { + *top++ = i; } else { if (top > stack) { if (--top == stack) { - /* The stack never keep ')' so we use 'error' to record index */ - length = p - (s + error); + /* distancd of the latest ')' */ + len = i - invalid; } else { - /* The *(top - 1) is the index of the last kept '(' */ - length = p - (s + *(top - 1)); + /* distance of the remote '(' */ + len = i - *(top - 1); } - if (length > max_length) { - max_length = length; + if (len > max_len) { + max_len = len; } } else { - error = p - s; + /* record the index of last ')' but no push */ + invalid = i; } } - p++; } - return max_length; + return max_len; } int main(int argc, char **argv) From d5a9a9c9fc3bd61ecd185e2df0d1d2aee55b6b68 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 10 Jun 2020 08:36:33 +0800 Subject: [PATCH 059/211] Refine Signed-off-by: begeekmyfriend --- 053_maximum_subarray/max_subarray.c | 14 ++++---- 152_maximum_product_subarray/subarray.c | 46 ++++++++++++------------- 2 files changed, 31 insertions(+), 29 deletions(-) diff --git a/053_maximum_subarray/max_subarray.c b/053_maximum_subarray/max_subarray.c index 6a0bbb4..885ce6b 100644 --- a/053_maximum_subarray/max_subarray.c +++ b/053_maximum_subarray/max_subarray.c @@ -37,14 +37,16 @@ static int partition(int *nums, int lo, int hi) static int maxSubArray(int* nums, int numsSize) { #if 1 - int i, len = 0, max = INT_MIN; + int i, sum = 0, max = INT_MIN; for (i = 0; i < numsSize; i++) { - len += nums[i]; - /* Calculate maximum each time in loop */ - max = len > max ? len : max; - if (len < 0) { - len = 0; + /* dp indicates the optimical result of nums[0...i] + * dp[i] = max(dp[i-1], 0) + nums[i] */ + if (sum < 0) { + sum = nums[i]; + } else { + sum += nums[i]; } + max = sum > max ? sum : max; } return max; #else diff --git a/152_maximum_product_subarray/subarray.c b/152_maximum_product_subarray/subarray.c index c791807..cabe83d 100644 --- a/152_maximum_product_subarray/subarray.c +++ b/152_maximum_product_subarray/subarray.c @@ -1,38 +1,38 @@ +#include #include #include -static int maxProduct(int* nums, int numsSize) +static inline int min(int a, int b) { - if (numsSize == 0) { - return 0; - } + return a < b ? a : b; +} + +static inline int max(int a, int b) +{ + return a > b ? a : b; +} - int i, global_max = nums[0], product; - int local_min = 1, local_max = 1; +static int maxProduct(int* nums, int numsSize) +{ + int i, maximum = INT_MIN; + int dp_min = 1; + int dp_max = 1; + /* dp records the min or max result of subarray nums[0...i] */ for (i = 0; i < numsSize; i++) { - if (nums[i] > 0) { - product = local_max * nums[i]; - global_max = product > global_max ? product : global_max; - local_max *= nums[i]; - local_min *= nums[i]; - } else if (nums[i] < 0) { - product = local_min * nums[i]; - global_max = product > global_max ? product : global_max; - int tmp = local_max; - local_max = product > 1 ? product : 1; - local_min = tmp * nums[i]; - } else { - global_max = global_max > 0 ? global_max : 0; - local_max = 1; - local_min = 1; - } + int prev_min = dp_min; + int prev_max = dp_max; + dp_min = min(nums[i], min(prev_min * nums[i], prev_max * nums[i])); + dp_max = max(nums[i], max(prev_min * nums[i], prev_max * nums[i])); + maximum = max(dp_max, maximum); } - return global_max; + return maximum; } int main(int argc, char **argv) { + + int i, count = argc - 1; int *nums = malloc(count * sizeof(int)); for (i = 0; i < count; i++) { From 0413736423114afc4ccab9c55198b5947c1dda9a Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 11 Jun 2020 11:54:04 +0800 Subject: [PATCH 060/211] Fix Signed-off-by: begeekmyfriend --- 172_factorial_trailing_zeros/zeroes.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/172_factorial_trailing_zeros/zeroes.c b/172_factorial_trailing_zeros/zeroes.c index cc75bff..94b7f6b 100644 --- a/172_factorial_trailing_zeros/zeroes.c +++ b/172_factorial_trailing_zeros/zeroes.c @@ -3,7 +3,8 @@ static int trailingZeroes(int n) { - return n == 0 ? 0 : trailingZeroes(n / 5); + /* As 10 = 2 * 5 so we just count how many fives in it */ + return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5); } int main(int argc, char **argv) From ebdeffe537fd7d7e6a3842f4714df2702b631905 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 12 Jun 2020 08:58:11 +0800 Subject: [PATCH 061/211] Refine Signed-off-by: begeekmyfriend --- 198_house_robber/robber.c | 22 ++++++++++++---------- 213_house_robber_ii/robber.c | 21 ++++++++++----------- 2 files changed, 22 insertions(+), 21 deletions(-) diff --git a/198_house_robber/robber.c b/198_house_robber/robber.c index b7b0db2..35d7f22 100644 --- a/198_house_robber/robber.c +++ b/198_house_robber/robber.c @@ -9,20 +9,22 @@ static inline int max(int a, int b) static int rob(int* nums, int numsSize) { - int i; - int **money = malloc((numsSize + 1) * sizeof(int *)); - for (i = 0; i < numsSize + 1; i++) { - money[i] = malloc(2 * sizeof(int)); - memset(money[i], 0, 2 * sizeof(int)); + if (numsSize == 0) { + return 0; } - for (i = 1; i <= numsSize; i++) { - int cash = nums[i - 1]; - money[i][0] = max(money[i - 1][0], money[i - 1][1]); - money[i][1] = money[i - 1][0] + cash; + int i; + int taken = nums[0]; + int untaken = 0; + /* Record max profits of nums[0...i] respectively */ + for (i = 1; i < numsSize; i++) { + int tmp_taken = taken; + int tmp_untaken = untaken; + taken = untaken + nums[i]; + untaken = max(tmp_taken, tmp_untaken); } - return max(money[numsSize][0], money[numsSize][1]); + return max(taken, untaken); } int main(int argc, char **argv) diff --git a/213_house_robber_ii/robber.c b/213_house_robber_ii/robber.c index 8e95b23..21ae639 100644 --- a/213_house_robber_ii/robber.c +++ b/213_house_robber_ii/robber.c @@ -10,19 +10,17 @@ static inline int max(int a, int b) static int _rob(int* nums, int numsSize) { int i; - int **money = malloc((numsSize + 1) * sizeof(int *)); - for (i = 0; i < numsSize + 1; i++) { - money[i] = malloc(2 * sizeof(int)); - memset(money[i], 0, 2 * sizeof(int)); + int taken = nums[0]; + int untaken = 0; + /* Record max profits of nums[0...i] respectively */ + for (i = 1; i < numsSize; i++) { + int tmp_taken = taken; + int tmp_untaken = untaken; + taken = tmp_untaken + nums[i]; + untaken = max(tmp_taken, tmp_untaken); } - for (i = 1; i <= numsSize; i++) { - int cash = nums[i - 1]; - money[i][0] = max(money[i - 1][0], money[i - 1][1]); - money[i][1] = money[i - 1][0] + cash; - } - - return max(money[numsSize][0], money[numsSize][1]); + return max(taken, untaken); } static int rob(int* nums, int numsSize) @@ -32,6 +30,7 @@ static int rob(int* nums, int numsSize) } else if (numsSize == 1) { return nums[0]; } else { + /* The first and the last element are adjacent */ return max(_rob(nums + 1, numsSize - 1), _rob(nums, numsSize - 1)); } } From b770fde7e7246f0c554744e5724152fe819a751d Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 13 Jun 2020 09:27:18 +0800 Subject: [PATCH 062/211] Refine Signed-off-by: begeekmyfriend --- 031_next_permutation/next_permutation.c | 46 ++++++++++++------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/031_next_permutation/next_permutation.c b/031_next_permutation/next_permutation.c index c73b768..49ddbe5 100644 --- a/031_next_permutation/next_permutation.c +++ b/031_next_permutation/next_permutation.c @@ -1,16 +1,21 @@ #include #include +static inline void swap(int *a, int *b) +{ + int tmp = *a; + *a = *b; + *b = tmp; +} + static void reverse(int *a, int size) { - int left = 0; - int right = size - 1; - while (left < right) { - int tmp = a[left]; - a[left] = a[right]; - a[right] = tmp; - left++; - right--; + int lo = 0; + int hi = size - 1; + while (lo < hi) { + swap(a + lo, a + hi); + lo++; + hi--; } } @@ -20,24 +25,19 @@ static void nextPermutation(int* nums, int numsSize) return; } - int *p = nums + numsSize - 1; - int *q = nums + numsSize - 1; - - while (p != nums && *(p - 1) >= *p) { - p--; + int i = numsSize - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) { + i--; } - if (p != nums) { - int n = *(p - 1); - while (*q <= n) { - q--; + if (i >= 0) { + int j = numsSize - 1; + while (j >= 0 && nums[j] <= nums[i]) { + j--; } - - int tmp = *q; - *q = *(p - 1); - *(p - 1) = tmp; + swap(nums + i, nums + j); } - reverse(p, numsSize - (p - nums)); + reverse(nums + i + 1, numsSize - i - 1); } int main(int argc, char **argv) @@ -56,7 +56,7 @@ int main(int argc, char **argv) nextPermutation(nums, argc - 1); for (i = 0; i < argc - 1; i++) { - printf("%d", nums[i]); + printf("%d ", nums[i]); } putchar('\n'); From f583b444508dd37ca186a907748162a8bd34a35b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 14 Jun 2020 09:57:48 +0800 Subject: [PATCH 063/211] Refine Signed-off-by: begeekmyfriend --- 061_rotate_list/rotate_list.c | 37 ++++++++++++++++------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/061_rotate_list/rotate_list.c b/061_rotate_list/rotate_list.c index 5e84ef5..9f8eb56 100644 --- a/061_rotate_list/rotate_list.c +++ b/061_rotate_list/rotate_list.c @@ -6,7 +6,8 @@ struct ListNode { struct ListNode *next; }; -static struct ListNode* rotateRight(struct ListNode* head, int k) { +static struct ListNode* rotateRight(struct ListNode* head, int k) +{ if (head == NULL || k <= 0) { return head; } @@ -14,33 +15,31 @@ static struct ListNode* rotateRight(struct ListNode* head, int k) { struct ListNode dummy; dummy.next = head; struct ListNode *prev = &dummy; - struct ListNode *last = &dummy; struct ListNode *p = head; - int count = k; - while (k > 0) { - if (p == NULL) { - int length = count - k; - prev = &dummy; - p = head; - k = count % length; - if (k == 0) break; - } + int len = 0; + while (p != NULL) { prev = p; p = p->next; - k--; + len++; } - while (p != NULL) { - last = last->next; + struct ListNode *last = prev; + prev = &dummy; + p = head; + len = len - (k % len); + while (len-- > 0) { prev = p; p = p->next; } - if (last != &dummy) { - prev->next = head; - dummy.next = last->next; - last->next = NULL; + if (p != NULL) { + /* deletion */ + prev->next = NULL; + /* insertion */ + last->next = dummy.next; + dummy.next = p; } + return dummy.next; } @@ -59,13 +58,11 @@ int main(int argc, char **argv) for (i = 2; i < argc; i++) { p = malloc(sizeof(*p)); int n = atoi(argv[i]); - printf("%d ", n); p->val = n; p->next = NULL; prev->next = p; prev = p; } - putchar('\n'); list = rotateRight(dummy.next, atoi(argv[1])); for (p = list; p != NULL; p = p->next) { From 72fc9100cc7b56ae141f3637247df4472fe311d1 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 15 Jun 2020 08:20:37 +0800 Subject: [PATCH 064/211] Refine Signed-off-by: begeekmyfriend --- 138_copy_list_with_random_pointer/copy_list.c | 37 +++++++------ 143_reorder_list/reorder_list.c | 55 ++++++++++--------- 2 files changed, 48 insertions(+), 44 deletions(-) diff --git a/138_copy_list_with_random_pointer/copy_list.c b/138_copy_list_with_random_pointer/copy_list.c index b35d708..5fe458f 100644 --- a/138_copy_list_with_random_pointer/copy_list.c +++ b/138_copy_list_with_random_pointer/copy_list.c @@ -1,36 +1,39 @@ #include #include -struct RandomListNode { - int label; - struct RandomListNode *next; - struct RandomListNode *random; +struct Node { + int val; + struct Node *next; + struct Node *random; }; -static struct RandomListNode *copyRandomList(struct RandomListNode *head) +static struct Node *copyRandomList(struct Node *head) { if (head == NULL) { return NULL; } - struct RandomListNode *p, *new; + /* copy and redirect next pointer */ + struct Node *p, *new; for (p = head; p != NULL; p = p->next->next) { new = malloc(sizeof(*new)); - new->label = p->label; + new->val = p->val; new->next = p->next; p->next = new; } + /* clone random pointer */ for (p = head; p != NULL; p = p->next->next) { new = p->next; new->random = p->random != NULL ? p->random->next : NULL; } - struct RandomListNode dummy; - struct RandomListNode *prev = &dummy; + struct Node dummy; + struct Node *prev = &dummy; for (p = head; p != NULL; p = p->next) { new = p->next; p->next = new->next; + /* correct the actual next pointer of the new list */ prev->next = new; prev = new; new->next = NULL; @@ -42,10 +45,10 @@ static struct RandomListNode *copyRandomList(struct RandomListNode *head) int main(int argc, char **argv) { int i, count = argc - 1; - struct RandomListNode *head = NULL, *p, *prev; + struct Node *head = NULL, *p, *prev; for (i = 0; i < count; i++) { p = malloc(sizeof(*p)); - p->label = atoi(argv[i + 1]); + p->val = atoi(argv[i + 1]); p->next = NULL; p->random = NULL; if (head == NULL) { @@ -57,26 +60,26 @@ int main(int argc, char **argv) prev = p; } - struct RandomListNode *r = head; - struct RandomListNode *q = p = copyRandomList(head); + struct Node *r = head; + struct Node *q = p = copyRandomList(head); for (r = head; r != NULL; r = r->next) { - printf("%d ", r->label); + printf("%d ", r->val); } printf("\n"); for (r = head; r != NULL; r = r->random) { - printf("%d ", r->label); + printf("%d ", r->val); } printf("\n"); for (; p != NULL; p = p->next) { - printf("%d ", p->label); + printf("%d ", p->val); } printf("\n"); for (; q != NULL; q = q->random) { - printf("%d ", q->label); + printf("%d ", q->val); } printf("\n"); return 0; diff --git a/143_reorder_list/reorder_list.c b/143_reorder_list/reorder_list.c index 4e98eec..1377e3f 100644 --- a/143_reorder_list/reorder_list.c +++ b/143_reorder_list/reorder_list.c @@ -6,47 +6,48 @@ struct ListNode { struct ListNode *next; }; -static void reverse(struct ListNode *dummy) -{ - struct ListNode *prev = dummy->next; - if (prev != NULL) { - struct ListNode *p = prev->next; - while (p != NULL) { - prev->next = p->next; - p->next = dummy->next; - dummy->next = p; - p = prev->next; - } - } -} - static void reorderList(struct ListNode *head) { - if (head == NULL) { + if (head == NULL || head->next == NULL) { return; } int count = 0; - struct ListNode *p = head; - struct ListNode *q = p; + struct ListNode dummy; + struct ListNode *prev = &dummy; + struct ListNode *p, *q; /* locate half length */ - for (; p != NULL; p = p->next) { + dummy.next = head; + for (p = head, q = head; q != NULL; q = q->next) { if ((++count & 0x1) == 0) { - q = q->next; + prev = p; + p = p->next; } } /* reverse latter half list */ - reverse(q); + while (p->next != NULL) { + q = p->next; + /* deletion */ + p->next = q->next; + /* insertion */ + q->next = prev->next; + prev->next = q; + } - /* insert each element */ - struct ListNode *r; - for (p = head, r = q->next; r != NULL; p = r->next, r = q->next) { - q->next = r->next; - r->next = p->next; - p->next = r; - } + /* insert each element interleavingly */ + struct ListNode *last = prev; + p = head; + while (p != last) { + q = last->next; + /* deletion */ + last->next = q->next; + /* insertion */ + q->next = p->next; + p->next = q; + p = q->next; + } } int main(int argc, char **argv) From 47ee06554b03f1c0fbfb49d6f2d111a8104ca7d9 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 16 Jun 2020 06:50:52 +0800 Subject: [PATCH 065/211] Refine Signed-off-by: begeekmyfriend --- 056_merge_intervals/merge_intervals.c | 160 +++++++------------------- 057_insert_interval/insert_interval.c | 156 ++++++++----------------- 2 files changed, 91 insertions(+), 225 deletions(-) diff --git a/056_merge_intervals/merge_intervals.c b/056_merge_intervals/merge_intervals.c index a07096d..c9ca555 100644 --- a/056_merge_intervals/merge_intervals.c +++ b/056_merge_intervals/merge_intervals.c @@ -2,128 +2,52 @@ #include #include -struct Interval { - int start; - int end; -}; -static int binary_search(int *nums, int size, int target) +static int compare(const void *a, const void *b) { - int low = -1; - int high = size; - while (low + 1 < high) { - int mid = low + (high - low) / 2; - if (target > nums[mid]) { - low = mid; - } else { - high = mid; - } - } - if (high == size || nums[high] != target) { - return -high - 1; - } else { - return high; - } + return ((int *) a)[0] - ((int *) b)[0]; } /** - ** Return an array of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static struct Interval* insert(struct Interval* intervals, int intervalsSize, struct Interval newInterval, int* returnSize) + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ +int** merge(int** intervals, int intervalsSize, int* intervalsColSize, int* returnSize, int** returnColumnSizes) { - struct Interval *p; if (intervalsSize == 0) { - p = malloc(sizeof(*p)); - p->start = newInterval.start; - p->end = newInterval.end; - *returnSize = 1; - return p; + *returnSize = 0; + return intervals; } - - int i, count; - int *nums = malloc(2 * intervalsSize * sizeof(int)); + + int i, len = 0; + int *tmp = malloc(intervalsSize * 2 * sizeof(int)); for (i = 0; i < intervalsSize; i++) { - nums[i * 2] = intervals[i].start; - nums[i * 2 + 1] = intervals[i].end; - } - - int start0 = binary_search(nums, 2 * intervalsSize, newInterval.start); - int end0 = binary_search(nums, 2 * intervalsSize, newInterval.end); - - int start1 = -1, end1 = -1; - int merge_start= -1, merge_end = -1; - if (start0 >= 0) { - merge_start = start0 / 2; - } else { - start1 = -start0 - 1; - merge_start = start1 / 2; + tmp[i * 2] = intervals[i][0]; + tmp[i * 2 + 1] = intervals[i][1]; } + qsort(tmp, intervalsSize, 2 * sizeof(int), compare); - if (end0 >= 0) { - merge_end = end0 / 2; - } else { - end1 = -end0 - 1; - if (end1 % 2 == 0) { - merge_end = end1 / 2 > 0 ? end1 / 2 - 1 : 0; - } else { - merge_end = end1 / 2; + intervals[0][0] = tmp[0]; + intervals[0][1] = tmp[1]; + for (i = 1; i < intervalsSize; i++) { + if (tmp[i * 2] > intervals[len][1]) { + len++; + intervals[len][0] = tmp[i * 2]; + intervals[len][1] = tmp[i * 2 + 1]; + } else if (tmp[i * 2 + 1] > intervals[len][1]) { + intervals[len][1] = tmp[i * 2 + 1]; } } - - if (merge_start == merge_end) { - if (start0 < 0 && end0 < 0 && start1 == end1 && start1 % 2 == 0) { - count = intervalsSize + 1; - p = malloc(count * sizeof(*p)); - memcpy(p, intervals, merge_start * sizeof(*p)); - p[merge_start] = newInterval; - memcpy(p + merge_start + 1, intervals + merge_start, (intervalsSize - merge_start) * sizeof(*p)); - } else { - count = intervalsSize; - p = malloc(count * sizeof(*p)); - memcpy(p, intervals, count * sizeof(*p)); - if (start0 < 0 && start1 % 2 == 0) { - p[merge_start].start = newInterval.start; - } - if (end0 < 0 && end1 % 2 == 0) { - p[merge_end].end = newInterval.end; - } - } - } else { - count = intervalsSize - (merge_end - merge_start); - p = malloc(count * sizeof(*p)); - memcpy(p, intervals, merge_start * sizeof(*p)); - memcpy(p + merge_start, intervals + merge_end, (intervalsSize - merge_end) * sizeof(*p)); - if (start0 < 0 && start1 % 2 == 0) { - p[merge_start].start = newInterval.start; - } else { - p[merge_start].start = intervals[merge_start].start; - } - if (end0 < 0 && end1 % 2 == 0) { - p[merge_start].end = newInterval.end; - } else { - p[merge_start].end = intervals[merge_end].end; - } + + len += 1; + *returnSize = len; + *returnColumnSizes = malloc(len * sizeof(int)); + for (i = 0; i < len; i++) { + (*returnColumnSizes)[i] = 2; } - - free(nums); - free(intervals); - *returnSize = count; - return p; -} - -/** - * * Return an array of size *returnSize. - * * Note: The returned array must be malloced, assume caller calls free(). - * */ -struct Interval* merge(struct Interval* intervals, int intervalsSize, int* returnSize) { - int i, count = 0; - struct Interval *p = NULL; - for (i = 0; i < intervalsSize; i++) { - p = insert(p, count, intervals[i], &count); - } - *returnSize = count; - return p; + + return intervals; } int main(int argc, char **argv) @@ -134,18 +58,20 @@ int main(int argc, char **argv) } int i, count = 0; - struct Interval *intervals = malloc((argc - 1) / 2 * sizeof(struct Interval)); - struct Interval *p = intervals; - for (i = 1; i < argc; i += 2) { - p->start = atoi(argv[i]); - p->end = atoi(argv[i + 1]); - p++; + int *sizes = malloc((argc - 1) / 2 * sizeof(int)); + int **intervals = malloc((argc - 1) / 2 * sizeof(int *)); + for (i = 0; i < (argc - 1) / 2; i++) { + sizes[i] = 2; + intervals[i] = malloc(2 * sizeof(int)); + intervals[i][0] = atoi(argv[i * 2 + 1]); + intervals[i][1] = atoi(argv[i * 2 + 2]); } - struct Interval *q = merge(intervals, (argc - 1) / 2, &count); + int *col_sizes; + int **results = merge(intervals, (argc - 1) / 2, sizes, &count, &col_sizes); for (i = 0; i < count; i++) { - printf("[%d, %d]\n", q->start, q->end); - q++; + printf("[%d,%d]\n", results[i][0], results[i][1]); } + return 0; } diff --git a/057_insert_interval/insert_interval.c b/057_insert_interval/insert_interval.c index fd29352..02cb9a3 100644 --- a/057_insert_interval/insert_interval.c +++ b/057_insert_interval/insert_interval.c @@ -1,113 +1,52 @@ #include #include -#include -struct Interval { - int start; - int end; -}; -static int binary_search(int *nums, int size, int target) +static int compare(const void *a, const void *b) { - int low = -1; - int high = size; - while (low + 1 < high) { - int mid = low + (high - low) / 2; - if (target > nums[mid]) { - low = mid; - } else { - high = mid; - } - } - if (high == size || nums[high] != target) { - return -high - 1; - } else { - return high; - } + return ((int *) a)[0] - ((int *) b)[0]; } /** - ** Return an array of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static struct Interval* insert(struct Interval* intervals, int intervalsSize, struct Interval newInterval, int* returnSize) { - struct Interval *p; - if (intervalsSize == 0) { - p = malloc(sizeof(*p)); - p->start = newInterval.start; - p->end = newInterval.end; - *returnSize = 1; - return p; - } - - int i, count; - int *nums = malloc(2 * intervalsSize * sizeof(int)); + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ +int** insert(int** intervals, int intervalsSize, int* intervalsColSize, int* newInterval, int newIntervalSize, int* returnSize, int** returnColumnSizes) +{ + int i, len = 0; + int *tmp = malloc((intervalsSize + 1) * 2 * sizeof(int)); for (i = 0; i < intervalsSize; i++) { - nums[i * 2] = intervals[i].start; - nums[i * 2 + 1] = intervals[i].end; + tmp[i * 2] = intervals[i][0]; + tmp[i * 2 + 1] = intervals[i][1]; } + tmp[i * 2] = newInterval[0]; + tmp[i * 2 + 1] = newInterval[1]; + qsort(tmp, intervalsSize + 1, 2 * sizeof(int), compare); - int start0 = binary_search(nums, 2 * intervalsSize, newInterval.start); - int end0 = binary_search(nums, 2 * intervalsSize, newInterval.end); - - int start1 = -1, end1 = -1; - int merge_start= -1, merge_end = -1; - if (start0 >= 0) { - merge_start = start0 / 2; - } else { - start1 = -start0 - 1; - merge_start = start1 / 2; - } - - if (end0 >= 0) { - merge_end = end0 / 2; - } else { - end1 = -end0 - 1; - if (end1 % 2 == 0) { - merge_end = end1 / 2 > 0 ? end1 / 2 - 1 : 0; - } else { - merge_end = end1 / 2; + int **results = malloc((intervalsSize + 1) * sizeof(int *)); + results[0] = malloc(2 * sizeof(int)); + results[0][0] = tmp[0]; + results[0][1] = tmp[1]; + for (i = 1; i < intervalsSize + 1; i++) { + results[i] = malloc(2 * sizeof(int)); + if (tmp[i * 2] > results[len][1]) { + len++; + results[len][0] = tmp[i * 2]; + results[len][1] = tmp[i * 2 + 1]; + } else if (tmp[i * 2 + 1] > results[len][1]) { + results[len][1] = tmp[i * 2 + 1]; } } - - if (merge_start == merge_end) { - if (start0 < 0 && end0 < 0 && start1 == end1 && start1 % 2 == 0) { - count = intervalsSize + 1; - p = malloc(count * sizeof(*p)); - memcpy(p, intervals, merge_start * sizeof(*p)); - p[merge_start] = newInterval; - memcpy(p + merge_start + 1, intervals + merge_start, (intervalsSize - merge_start) * sizeof(*p)); - } else { - count = intervalsSize; - p = malloc(count * sizeof(*p)); - memcpy(p, intervals, count * sizeof(*p)); - if (start0 < 0 && start1 % 2 == 0) { - p[merge_start].start = newInterval.start; - } - if (end0 < 0 && end1 % 2 == 0) { - p[merge_end].end = newInterval.end; - } - } - } else { - count = intervalsSize - (merge_end - merge_start); - p = malloc(count * sizeof(*p)); - memcpy(p, intervals, merge_start * sizeof(*p)); - memcpy(p + merge_start, intervals + merge_end, (intervalsSize - merge_end) * sizeof(*p)); - if (start0 < 0 && start1 % 2 == 0) { - p[merge_start].start = newInterval.start; - } else { - p[merge_start].start = intervals[merge_start].start; - } - if (end0 < 0 && end1 % 2 == 0) { - p[merge_start].end = newInterval.end; - } else { - p[merge_start].end = intervals[merge_end].end; - } + + len += 1; + *returnSize = len; + *returnColumnSizes = malloc(len * sizeof(int)); + for (i = 0; i < len; i++) { + (*returnColumnSizes)[i] = 2; } - - free(nums); - *returnSize = count; - return p; + + return results; } int main(int argc, char **argv) @@ -117,23 +56,24 @@ int main(int argc, char **argv) exit(-1); } - struct Interval new_interv; - new_interv.start = atoi(argv[1]); - new_interv.end = atoi(argv[2]); + int new_interv[2]; + new_interv[0] = atoi(argv[1]); + new_interv[1] = atoi(argv[2]); int i, count = 0; - struct Interval *intervals = malloc((argc - 3) / 2 * sizeof(struct Interval)); - struct Interval *p = intervals; - for (i = 3; i < argc; i += 2) { - p->start = atoi(argv[i]); - p->end = atoi(argv[i + 1]); - p++; + int *size = malloc((argc - 3) / 2 * sizeof(int)); + int **intervals = malloc((argc - 3) / 2 * sizeof(int *)); + for (i = 0; i < (argc - 3) / 2; i++) { + intervals[i] = malloc(2 * sizeof(int)); + intervals[i][0] = atoi(argv[i * 2 + 3]); + intervals[i][1] = atoi(argv[i * 2 + 4]); } - struct Interval *q = insert(intervals, (argc - 3) / 2, new_interv, &count); + int *col_sizes; + int **results = insert(intervals, (argc - 3) / 2, size, new_interv, 2, &count, &col_sizes); for (i = 0; i < count; i++) { - printf("[%d, %d]\n", q->start, q->end); - q++; + printf("[%d,%d]\n", results[i][0], results[i][1]); } + return 0; } From a67731315f48775b4fc94d07cff5403bdfc643d4 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 17 Jun 2020 08:49:55 +0800 Subject: [PATCH 066/211] Refine Signed-off-by: begeekmyfriend --- .../window_substring.c | 79 +++++++------------ 1 file changed, 29 insertions(+), 50 deletions(-) diff --git a/076_minimum_window_substring/window_substring.c b/076_minimum_window_substring/window_substring.c index 50970ee..a9e87ab 100644 --- a/076_minimum_window_substring/window_substring.c +++ b/076_minimum_window_substring/window_substring.c @@ -1,72 +1,51 @@ #include #include #include -#include static char *minWindow(char *s, char *t) { - /* - * Declare two "hash map" for ASCII chars - * f[]: represents the char found in s - * m[]: stores the chars in t - */ - int i, f[256], m[256], pat_len = 0; - memset(m, 0, sizeof(m)); - memset(f, 0, sizeof(f)); - - /* - * Go through t, and inital the m[] and f[] - * Notes: duplicate char is allowed. - */ - for (i = 0; t[i] != '\0'; i++) { - m[t[i]]++; - pat_len++; + int i, j, count[256] = { 0 }; + int slen = strlen(s); + int tlen = strlen(t); + for (i = 0; i < tlen; i++) { + count[t[i]]++; } - int start =-1; - int size = INT_MAX; - int found = 0; - int begin = 0; - for (i = 0; s[i] != '\0'; i++) { - /* First, find the right side of the window which should be in t */ - if (m[s[i]] > 0) { - /* if one char has been found enough times, then do not do found++ */ - if (++f[s[i]] <= m[s[i]]) { - found++; - } + /* 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) { + /* pattern found */ + chars_to_meet--; + } - /* the right side of the window is confirmed as i */ - /* The found counter will no more increase if the first right side of the window is confirmed, - * the next step run here can also be regarded as a new right side of a new window. */ - if (found == pat_len) { - /* Then we need to find the left side of the window - * 1) m[s[begin]] == 0 => Both left and right side should be found in t - * 2) f[s[begin]] > m[s[begin]] => duplicate chars are more than excepted in the window so that we can even shrink the size. */ - while (m[s[begin]] == 0 || f[s[begin]] > m[s[begin]]) { - if (f[s[begin]] > m[s[begin]]) { - f[s[begin]]--; - } - begin++; - } + while (chars_to_meet == 0) { + if (hi - lo < min_len) { + min_len = hi - lo; + start = lo; + } - /* Calculate the minimized window size */ - if (size > i - begin + 1) { - start = begin; - size = i - begin + 1; - } + /* Chars with negative count are not included in the pattern string */ + if (++count[s[lo++]] > 0) { + /* chars_to_meet == 1 */ + chars_to_meet++; } } } char *result; - if (start >= 0 && size > 0) { - result = malloc(size + 1); - memcpy(result, s + start, size); - result[size] = '\0'; + if (min_len <= slen) { + result = malloc(min_len + 1); + memcpy(result, s + start, min_len); + result[min_len] = '\0'; } else { result = malloc(1); result[0] = '\0'; } + return result; } From 9eec632d0535ebe3614f9afdd24ed27c72d56e02 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 18 Jun 2020 08:24:52 +0800 Subject: [PATCH 067/211] Refine Signed-off-by: begeekmyfriend --- 088_merge_sorted_array/merge_array.c | 35 +++++++--------------------- 1 file changed, 9 insertions(+), 26 deletions(-) diff --git a/088_merge_sorted_array/merge_array.c b/088_merge_sorted_array/merge_array.c index dcc4e94..7f65d98 100644 --- a/088_merge_sorted_array/merge_array.c +++ b/088_merge_sorted_array/merge_array.c @@ -1,38 +1,21 @@ #include #include -static int binary_search(int *nums, int len, int target) +static void merge(int* nums1, int m, int* nums2, int n) { - int low = -1; - int high = len; - while (low + 1 < high) { - int mid = high - (high - low) / 2; - if (target > nums[mid]) { - low = mid; + int i = m - 1, j = n - 1, k = nums1Size - 1; + while (i >= 0 && j >= 0 && k >= 0) { + if (nums1[i] >= nums2[j]) { + nums1[k--] = nums1[i--]; } else { - high = mid; + nums1[k--] = nums2[j--]; } } - if (high == len || nums[high] != target) { - return -high - 1; - } else { - return high; - } -} -static void merge(int* nums1, int m, int* nums2, int n) -{ - int i, j, len1 = m; - for (i = 0; i < n; i++) { - int index = binary_search(nums1, len1, nums2[i]); - if (index < 0) { - index = -index - 1; - } - for (j = len1 - 1; j >= index; j--) { - nums1[j + 1] = nums1[j]; + if (i == -1) { + while (j >= 0) { + nums1[k--] = nums2[j--]; } - nums1[index] = nums2[i]; - len1++; } } From b7a7c354d300c572b60d2847687c231a93ed33e5 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 19 Jun 2020 12:11:06 +0800 Subject: [PATCH 068/211] Refine Signed-off-by: begeekmyfriend --- 050_pow/pow.c | 5 +++++ 070_climbing_stairs/climb_stairs.c | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/050_pow/pow.c b/050_pow/pow.c index 515454e..ce98a46 100644 --- a/050_pow/pow.c +++ b/050_pow/pow.c @@ -1,3 +1,4 @@ +#include #include #include @@ -11,6 +12,10 @@ static double fast_pow(double x, int n) static double my_pow(double x, int n) { + if (n == INT_MIN) { + double t = 1 / fast_pow(x, -(n / 2)); + return t * t; + } return n < 0 ? 1 / fast_pow(x, -n) : fast_pow(x, n); } diff --git a/070_climbing_stairs/climb_stairs.c b/070_climbing_stairs/climb_stairs.c index 54645c6..3ecc50c 100644 --- a/070_climbing_stairs/climb_stairs.c +++ b/070_climbing_stairs/climb_stairs.c @@ -21,11 +21,21 @@ static int dfs(int n, int *count) static int climbStairs(int n) { +#if 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; + for (i = 3; i <= n; i++) { + c = a + b; + a = b; + b = c; + } + return n == 1 ? a : (n == 2 ? b : c); +#endif } int main(int argc, char **argv) From 37f2e43a420fec23c0309746e8a27516a30dfcdd Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 20 Jun 2020 08:05:01 +0800 Subject: [PATCH 069/211] Refine Signed-off-by: begeekmyfriend --- .../bst_bfs.c | 144 ++-------------- .../bst_zigzag.c | 14 +- .../bst_bfs.c | 157 +++--------------- 3 files changed, 50 insertions(+), 265 deletions(-) diff --git a/102_binary_tree_level_order_traversal/bst_bfs.c b/102_binary_tree_level_order_traversal/bst_bfs.c index af2f81c..b12c5ce 100644 --- a/102_binary_tree_level_order_traversal/bst_bfs.c +++ b/102_binary_tree_level_order_traversal/bst_bfs.c @@ -4,154 +4,46 @@ #define BST_MAX_LEVEL 800 -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) - -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; -struct list_head { - struct list_head *next, *prev; -}; - -static inline void INIT_LIST_HEAD(struct list_head *list) -{ - list->next = list->prev = list; -} - -static inline int list_empty(const struct list_head *head) -{ - return (head->next == head); -} - -static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) -{ - next->prev = new; - new->next = next; - new->prev = prev; - prev->next = new; -} - -static inline void list_add(struct list_head *_new, struct list_head *head) -{ - __list_add(_new, head, head->next); -} - -static inline void list_add_tail(struct list_head *_new, struct list_head *head) -{ - __list_add(_new, head->prev, head); -} - -static inline void __list_del(struct list_head *entry) +static void bfs(struct TreeNode *root, int **results, int *count, int *col_sizes, int *size, int level) { - entry->next->prev = entry->prev; - entry->prev->next = entry->next; -} - -static inline void list_del(struct list_head *entry) -{ - __list_del(entry); - entry->next = entry->prev = NULL; -} - -struct bfs_node { - struct TreeNode *node; - struct list_head link; -}; - -static struct bfs_node *node_new(struct list_head *free_list, struct TreeNode *node) -{ - struct bfs_node *new; - if (list_empty(free_list)) { - new = malloc(sizeof(*new)); - } else { - new = list_first_entry(free_list, struct bfs_node, link); - list_del(&new->link); - } - new->node = node; - return new; -} - -static void queue(struct list_head *parents, struct list_head *children, - struct list_head *free_list, int **results, int *col_sizes, int level) -{ - struct list_head *p, *n; - list_for_each(p, parents) { - struct bfs_node *new; - struct bfs_node *parent = list_entry(p, struct bfs_node, link); - if (parent->node->left != NULL) { - new = node_new(free_list, parent->node->left); - list_add_tail(&new->link, children); - } - if (parent->node->right != NULL) { - new = node_new(free_list, parent->node->right); - list_add_tail(&new->link, children); - } - col_sizes[level]++; + if (root == NULL) { + return; } - int i = 0; - results[level] = malloc(col_sizes[level] * sizeof(int)); - list_for_each_safe(p, n, parents) { - struct bfs_node *parent = list_entry(p, struct bfs_node, link); - results[level][i++] = parent->node->val; - list_del(p); - list_add(p, free_list); + *count = level + 1 > *count ? level + 1 : *count; + if (col_sizes[level] == 0) { + *size = *size > 256 ? 256 : *size * 2; + results[level] = malloc(*size * sizeof(int)); } + results[level][col_sizes[level]++] = root->val; + bfs(root->left, results, count, col_sizes, size, level + 1); + bfs(root->right, results, count, col_sizes, size, level + 1); } /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. + ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -static int** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) +static int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) { if (root == NULL) { *returnSize = 0; return NULL; } - struct list_head free_list; - struct list_head q0; - struct list_head q1; - INIT_LIST_HEAD(&free_list); - INIT_LIST_HEAD(&q0); - INIT_LIST_HEAD(&q1); - + int size = 1; + *returnSize = 0; int **results = malloc(BST_MAX_LEVEL * sizeof(int *)); - *columnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); - memset(*columnSizes, 0, BST_MAX_LEVEL * sizeof(int)); - - int level = 0; - struct bfs_node *new = node_new(&free_list, root); - list_add_tail(&new->link, &q0); - - while (!list_empty(&q0) || !list_empty(&q1)) { - if (level & 0x1) { - queue(&q1, &q0, &free_list, results, *columnSizes, level); - } else { - queue(&q0, &q1, &free_list, results, *columnSizes, level); - } - level++; - } - - *returnSize = level; + *returnColumnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); + memset(*returnColumnSizes, 0, BST_MAX_LEVEL * sizeof(int)); + bfs(root, results, returnSize, *returnColumnSizes, &size, 0); return results; } @@ -186,7 +78,7 @@ int main(void) node2[3].right = NULL; int i, j, count = 0, *col_sizes; - int **lists = levelOrder(&root, &col_sizes, &count); + int **lists = levelOrder(&root, &count, &col_sizes); for (i = 0; i < count; i++) { for (j = 0; j < col_sizes[i]; j++) { printf("%d ", lists[i][j]); diff --git a/103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c b/103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c index fae68dc..3e7c28d 100644 --- a/103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c +++ b/103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c @@ -133,10 +133,10 @@ static void queue(struct list_head *parents, struct list_head *children, int rev /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. + ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -static int** zigzagLevelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) +static int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) { if (root == NULL) { *returnSize = 0; @@ -151,8 +151,8 @@ static int** zigzagLevelOrder(struct TreeNode* root, int** columnSizes, int* ret INIT_LIST_HEAD(&q1); int **results = malloc(BST_MAX_LEVEL * sizeof(int *)); - *columnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); - memset(*columnSizes, 0, BST_MAX_LEVEL * sizeof(int)); + *returnColumnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); + memset(*returnColumnSizes, 0, BST_MAX_LEVEL * sizeof(int)); int level = 0; struct bfs_node *new = node_new(&free_list, root); @@ -160,9 +160,9 @@ static int** zigzagLevelOrder(struct TreeNode* root, int** columnSizes, int* ret while (!list_empty(&q0) || !list_empty(&q1)) { if (level & 0x1) { - queue(&q1, &q0, 1, &free_list, results, *columnSizes, level); + queue(&q1, &q0, 1, &free_list, results, *returnColumnSizes, level); } else { - queue(&q0, &q1, 0, &free_list, results, *columnSizes, level); + queue(&q0, &q1, 0, &free_list, results, *returnColumnSizes, level); } level++; } @@ -223,7 +223,7 @@ int main(void) node2[3].right = NULL; int i, j, count = 0, *col_sizes; - int **lists = zigzagLevelOrder(&root, &col_sizes, &count); + int **lists = zigzagLevelOrder(&root, &count, &col_sizes); for (i = 0; i < count; i++) { for (j = 0; j < col_sizes[i]; j++) { printf("%d ", lists[i][j]); diff --git a/107_binary_tree_level_order_traversal_ii/bst_bfs.c b/107_binary_tree_level_order_traversal_ii/bst_bfs.c index b9cc5ba..564ae71 100644 --- a/107_binary_tree_level_order_traversal_ii/bst_bfs.c +++ b/107_binary_tree_level_order_traversal_ii/bst_bfs.c @@ -4,164 +4,57 @@ #define BST_MAX_LEVEL 800 -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) - -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) - -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; -struct list_head { - struct list_head *next, *prev; -}; - -static inline void INIT_LIST_HEAD(struct list_head *list) -{ - list->next = list->prev = list; -} - -static inline int list_empty(const struct list_head *head) -{ - return (head->next == head); -} - -static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) -{ - next->prev = new; - new->next = next; - new->prev = prev; - prev->next = new; -} - -static inline void list_add(struct list_head *_new, struct list_head *head) -{ - __list_add(_new, head, head->next); -} - -static inline void list_add_tail(struct list_head *_new, struct list_head *head) -{ - __list_add(_new, head->prev, head); -} - -static inline void __list_del(struct list_head *entry) -{ - entry->next->prev = entry->prev; - entry->prev->next = entry->next; -} - -static inline void list_del(struct list_head *entry) -{ - __list_del(entry); - entry->next = entry->prev = NULL; -} - -struct bfs_node { - struct TreeNode *node; - struct list_head link; -}; - -static struct bfs_node *node_new(struct list_head *free_list, struct TreeNode *node) +static void bfs(struct TreeNode *root, int **results, int *count, int *col_sizes, int *size, int level) { - struct bfs_node *new; - if (list_empty(free_list)) { - new = malloc(sizeof(*new)); - } else { - new = list_first_entry(free_list, struct bfs_node, link); - list_del(&new->link); - } - new->node = node; - return new; -} - -static void queue(struct list_head *parents, struct list_head *children, - struct list_head *free_list, int **results, int *col_sizes, int level) -{ - struct list_head *p, *n; - list_for_each(p, parents) { - struct bfs_node *new; - struct bfs_node *parent = list_entry(p, struct bfs_node, link); - if (parent->node->left != NULL) { - new = node_new(free_list, parent->node->left); - list_add_tail(&new->link, children); - } - if (parent->node->right != NULL) { - new = node_new(free_list, parent->node->right); - list_add_tail(&new->link, children); - } - col_sizes[level]++; + if (root == NULL) { + return; } - int i = 0; - results[level] = malloc(col_sizes[level] * sizeof(int)); - list_for_each_safe(p, n, parents) { - struct bfs_node *parent = list_entry(p, struct bfs_node, link); - results[level][i++] = parent->node->val; - list_del(p); - list_add(p, free_list); + *count = level + 1 > *count ? level + 1 : *count; + if (col_sizes[level] == 0) { + *size = *size > 256 ? 256 : *size * 2; + results[level] = malloc(*size * sizeof(int)); } + results[level][col_sizes[level]++] = root->val; + bfs(root->left, results, count, col_sizes, size, level + 1); + bfs(root->right, results, count, col_sizes, size, level + 1); } /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. + ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -static int** levelOrderBottom(struct TreeNode* root, int** columnSizes, int* returnSize) +static int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes) { if (root == NULL) { *returnSize = 0; return NULL; } - struct list_head free_list; - struct list_head q0; - struct list_head q1; - INIT_LIST_HEAD(&free_list); - INIT_LIST_HEAD(&q0); - INIT_LIST_HEAD(&q1); - + int size = 1; + *returnSize = 0; int **results = malloc(BST_MAX_LEVEL * sizeof(int *)); - *columnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); - memset(*columnSizes, 0, BST_MAX_LEVEL * sizeof(int)); - - int level = 0; - struct bfs_node *new = node_new(&free_list, root); - list_add_tail(&new->link, &q0); - - while (!list_empty(&q0) || !list_empty(&q1)) { - if (level & 0x1) { - queue(&q1, &q0, &free_list, results, *columnSizes, level); - } else { - queue(&q0, &q1, &free_list, results, *columnSizes, level); - } - level++; - } - - *returnSize = level; + *returnColumnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); + memset(*returnColumnSizes, 0, BST_MAX_LEVEL * sizeof(int)); + bfs(root, results, returnSize, *returnColumnSizes, &size, 0); int i, j; - for (i = 0, j = level - 1; i < j; i++, j--) { - int *tmp = results[i]; + for (i = 0, j = *returnSize - 1; i < j; i++, j--) { + int *ptmp = results[i]; results[i] = results[j]; - results[j] = tmp; - int t = (*columnSizes)[i]; - (*columnSizes)[i] = (*columnSizes)[j]; - (*columnSizes)[j] = t; + results[j] = ptmp; + int tmp = (*returnColumnSizes)[i]; + (*returnColumnSizes)[i] = (*returnColumnSizes)[j]; + (*returnColumnSizes)[j] = tmp; } + return results; } @@ -196,7 +89,7 @@ int main(void) node2[3].right = NULL; int i, j, count = 0, *col_sizes; - int **lists = levelOrderBottom(&root, &col_sizes, &count); + int **lists = levelOrderBottom(&root, &count, &col_sizes); for (i = 0; i < count; i++) { for (j = 0; j < col_sizes[i]; j++) { printf("%d ", lists[i][j]); From f429ac02710412c7e86e52532bb1404239331663 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 21 Jun 2020 13:40:58 +0800 Subject: [PATCH 070/211] Refine Signed-off-by: begeekmyfriend --- .../rotated_array.c | 70 ++++++------------- .../search_rotated_array.c | 62 +++++++--------- 2 files changed, 45 insertions(+), 87 deletions(-) diff --git a/033_search_in_rotated_sorted_array/rotated_array.c b/033_search_in_rotated_sorted_array/rotated_array.c index b022f7b..822c2ee 100644 --- a/033_search_in_rotated_sorted_array/rotated_array.c +++ b/033_search_in_rotated_sorted_array/rotated_array.c @@ -1,61 +1,33 @@ #include #include -static int binary_search(int *nums, int size, int target) -{ - int low = -1; - int high = size; - while (low + 1 < high) { - int mid = low + (high - low) / 2; - if (target > nums[mid]) { - low = mid; - } else { - high = mid; - } - } - if (high == size || nums[high] != target) { - return -1; - } else { - return high; - } -} -static int start_find(int *nums, int size) +static int search(int* nums, int numsSize, int target) { - int low = 0; - int high = size - 1; - while (low < high && nums[low] > nums[high]) { - int mid = low + (high - low) / 2; - if (nums[mid] > nums[high]) { - low = mid + 1; - } else if (nums[mid] < nums[low]) { - /* Assume no duplicate exists in arry */ - high = mid; + int lo = 0; + int hi = numsSize - 1; + while (lo <= hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] == target) { + return mid; } - } - return low; -} -static int search(int* nums, int numsSize, int target) -{ - if (numsSize <= 0) { - return -1; - } - if (numsSize == 1) { - return target == nums[0] ? 0 : -1; + if (nums[lo] <= nums[mid]) { + if (nums[lo] <= target && target < nums[mid]) { + hi = mid - 1; + } else { + lo = mid + 1; + } + } else { + if (nums[mid] < target && target <= nums[hi]) { + lo = mid + 1; + } else { + hi = mid - 1; + } + } } - int i = start_find(nums, numsSize); - if (i == 0) { - return binary_search(nums, numsSize, target); - } else if (target >= nums[0]) { - return binary_search(nums, i, target); - } else if (target <= nums[numsSize - 1]) { - int index = binary_search(nums + i, numsSize - i, target); - return index >= 0 ? index + i : -1; - } else { - return -1; - } + return -1; } int main(int argc, char **argv) diff --git a/081_search_in_rotated_sorted_array_ii/search_rotated_array.c b/081_search_in_rotated_sorted_array_ii/search_rotated_array.c index a271eff..7d4e24e 100644 --- a/081_search_in_rotated_sorted_array_ii/search_rotated_array.c +++ b/081_search_in_rotated_sorted_array_ii/search_rotated_array.c @@ -2,51 +2,37 @@ #include #include -static int binary_search(int *nums, int size, int target) -{ - int low = -1; - int high = size; - while (low + 1 < high) { - int mid = low + (high - low) / 2; - if (target > nums[mid]) { - low = mid; - } else { - high = mid; - } - } - if (high == size || nums[high] != target) { - return -1; - } else { - return high; - } -} static bool search(int* nums, int numsSize, int target) { - if (numsSize <= 0) { - return false; - } - - if (numsSize == 1) { - return target == nums[0]; - } + int lo = 0; + int hi = numsSize - 1; + while (lo <= hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] == target) { + return true; + } - int i; - for (i = 1; i < numsSize; i++) { - if (nums[i] < nums[i - 1]) { - break; + if (nums[lo] == nums[mid] && nums[mid] == nums[hi]) { + /* Not sure which side contains the peak value, reduce search range */ + lo++; + hi--; + } else if (nums[lo] <= nums[mid]) { /* lo might be equal to mid */ + if (nums[lo] <= target && target < nums[mid]) { + hi = mid - 1; + } else { + lo = mid + 1; + } + } else { + if (nums[mid] < target && target <= nums[hi]) { + lo = mid + 1; + } else { + hi = mid - 1; + } } } - if (i == 0) { - return binary_search(nums, numsSize, target) >= 0; - } else if (target >= nums[0]) { - return binary_search(nums, i, target) >= 0; - } else if (target <= nums[numsSize - 1]) { - return binary_search(nums + i, numsSize - i, target) >= 0; - } else { - return -1; - } + return false; } int main(int argc, char **argv) From 042fe663a587ad487194aaeca4c44a2c5f0fbafd Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 22 Jun 2020 22:34:12 +0800 Subject: [PATCH 071/211] Fix Signed-off-by: begeekmyfriend --- 020_valid_parentheses/valid_parentheses.c | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/020_valid_parentheses/valid_parentheses.c b/020_valid_parentheses/valid_parentheses.c index 8fa87c8..3e825e3 100644 --- a/020_valid_parentheses/valid_parentheses.c +++ b/020_valid_parentheses/valid_parentheses.c @@ -4,28 +4,24 @@ static bool isValid(char *s) { - int n = 0, cap = 100; - char *stack = malloc(cap); + int n = 0; + char stack[100]; while (*s != '\0') { switch(*s) { case '(': case '[': case '{': - if (n + 1 >= cap) { - cap *= 2; - stack = realloc(stack, cap); - } stack[n++] = *s; break; case ')': - if (stack[--n] != '(') return false; + if (n == 0 || stack[--n] != '(') return false; break; case ']': - if (stack[--n] != '[') return false; + if (n == 0 || stack[--n] != '[') return false; break; case '}': - if (stack[--n] != '{') return false; + if (n == 0 || stack[--n] != '{') return false; break; default: return false; From f0a827e828bd574451d1b430353c002656792f77 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 22 Jun 2020 22:48:57 +0800 Subject: [PATCH 072/211] Refine Signed-off-by: begeekmyfriend --- 002_add_two_numbers/add_two_numbers.c | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/002_add_two_numbers/add_two_numbers.c b/002_add_two_numbers/add_two_numbers.c index 19873e9..a85ba71 100644 --- a/002_add_two_numbers/add_two_numbers.c +++ b/002_add_two_numbers/add_two_numbers.c @@ -20,25 +20,20 @@ static struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) int last_carry = carry; if (l1 != NULL) { - if (p == NULL) { - /* p never be NULL */ - prev->next = l1; - p = l1; - } sum += l1->val; l1 = l1->next; } if (l2 != NULL) { if (p == NULL) { - /* p never be NULL */ + /* l2 longer than l1 */ prev->next = l2; p = l2; } sum += l2->val; l2 = l2->next; } - + sum += last_carry; carry = sum / 10; p->val = sum % 10; From 7ae92507f409cee3410776724eee9ef132d144dd Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 23 Jun 2020 22:57:29 +0800 Subject: [PATCH 073/211] Refine Signed-off-by: begeekmyfriend --- .../rm_dup.c | 18 ++++++++++-------- .../rm_dup.c | 16 +++++++++------- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/082_remove_duplicates_from_sorted_list_ii/rm_dup.c b/082_remove_duplicates_from_sorted_list_ii/rm_dup.c index c451d79..35e6324 100644 --- a/082_remove_duplicates_from_sorted_list_ii/rm_dup.c +++ b/082_remove_duplicates_from_sorted_list_ii/rm_dup.c @@ -1,27 +1,29 @@ #include #include + struct ListNode { int val; struct ListNode *next; }; -struct ListNode* deleteDuplicates(struct ListNode* head) { +struct ListNode* deleteDuplicates(struct ListNode* head) +{ struct ListNode dummy; - struct ListNode *p, *next, *prev; + struct ListNode *p, *q, *prev; prev = &dummy; dummy.next = head; - p = next = head; + p = q = head; while (p != NULL) { - while (next != NULL && next->val == p->val) { - next = next->next; + while (q != NULL && q->val == p->val) { + q = q->next; } - if (p->next == next) { + if (p->next == q) { prev = p; } else { - prev->next = next; + prev->next = q; } - p = next; + p = q; } return dummy.next; } diff --git a/083_remove_duplicates_from_sorted_list/rm_dup.c b/083_remove_duplicates_from_sorted_list/rm_dup.c index d5de716..f5b7c7f 100644 --- a/083_remove_duplicates_from_sorted_list/rm_dup.c +++ b/083_remove_duplicates_from_sorted_list/rm_dup.c @@ -1,20 +1,22 @@ #include #include + struct ListNode { int val; struct ListNode *next; }; -struct ListNode* deleteDuplicates(struct ListNode* head) { - struct ListNode *p, *next; - p = next = head; +struct ListNode* deleteDuplicates(struct ListNode* head) +{ + struct ListNode *p, *q; + p = q = head; while (p != NULL) { - while (next != NULL && next->val == p->val) { - next = next->next; + while (q != NULL && q->val == p->val) { + q = q->next; } - p->next = next; - p = next; + p->next = q; + p = q; } return head; } From acdf017d924f6a663f0406f956136d886a4934a6 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 23 Jun 2020 23:56:28 +0800 Subject: [PATCH 074/211] Refine Signed-off-by: begeekmyfriend --- 039_combination_sum/combination_sum.c | 3 --- 040_combination_sum_ii/combination_sum.c | 7 ++++++- 047_permutations_ii/permutations.c | 8 ++++++-- 090_subsets_ii/subsets.c | 3 +++ 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/039_combination_sum/combination_sum.c b/039_combination_sum/combination_sum.c index 66b597d..c360117 100644 --- a/039_combination_sum/combination_sum.c +++ b/039_combination_sum/combination_sum.c @@ -13,9 +13,6 @@ static void dfs(int *nums, int size, int start, int target, int *stack, (*count)++; } else if (target > 0) { for (i = start; i < size; i++) { - if (i > 0 && nums[i] == nums[i - 1]) { - continue; - } stack[len] = nums[i]; dfs(nums, size, i, target - nums[i], stack, len + 1, results, column_sizes, count); } diff --git a/040_combination_sum_ii/combination_sum.c b/040_combination_sum_ii/combination_sum.c index 44c8ed5..a46d3ab 100644 --- a/040_combination_sum_ii/combination_sum.c +++ b/040_combination_sum_ii/combination_sum.c @@ -20,9 +20,14 @@ static void dfs(int *nums, int size, int start, int target, int *solution, int l } else if (target > 0) { for (i = start; i < size; i++) { if (!used[i]) { - if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) continue; + if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { + /* Forbid same elements in same level */ + /* Used marks allow same elements in different levels */ + continue; + } used[i] = true; solution[len] = nums[i]; + /* i + 1 limits the selecting range in following levels */ dfs(nums, size, i + 1, target - nums[i], solution, len + 1, used, results, count, column_sizes); used[i] = false; } diff --git a/047_permutations_ii/permutations.c b/047_permutations_ii/permutations.c index acf74df..1ba93e2 100644 --- a/047_permutations_ii/permutations.c +++ b/047_permutations_ii/permutations.c @@ -20,7 +20,11 @@ static void dfs(int *nums, int size, bool *used, int *stack, } else { for (i = 0; i < size; i++) { if (!used[i]) { - if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; + if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) { + /* Forbid same elements on same level */ + /* Used marks allow same elements in different levels */ + continue; + } used[i] = true; stack[len] = nums[i]; dfs(nums, size, used, stack, len + 1, results, count, col_size); @@ -33,7 +37,7 @@ static void dfs(int *nums, int size, bool *used, int *stack, /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + * Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). */ static int **permute(int* nums, int numsSize, int* returnSize, int **returnColumnSize) { diff --git a/090_subsets_ii/subsets.c b/090_subsets_ii/subsets.c index 095676e..e2f40db 100644 --- a/090_subsets_ii/subsets.c +++ b/090_subsets_ii/subsets.c @@ -19,10 +19,13 @@ static void dfs(int *nums, int size, int start, int *buf, int level, for (i = start; i < size; i++) { if (!used[i]) { if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { + /* Forbid same elements on same level */ + /* Used marks allow same elements in different levels */ continue; } used[i] = true; buf[level] = nums[i]; + /* i + 1 limits the selecting range in following levels */ dfs(nums, size, i + 1, buf, level + 1, used, sets, count, sizes); used[i] = false; } From 463ef54e78336ef6742f2780126c83b2d84ef32c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 24 Jun 2020 17:03:23 +0800 Subject: [PATCH 075/211] Annotation Signed-off-by: begeekmyfriend --- 041_first_missing_positive/missing_positive.c | 4 +- 045_jump_game_ii/jump_game.c | 2 + 055_jump_game/jump_game.c | 1 + 075_sort_colors/sort_colors.c | 41 +++++------- .../rm_dups.c | 5 +- 085_maximal_rectangle/maximal_rectangle.c | 14 ++-- 086_partition_list/partition_list.c | 32 ++++++---- 087_scramble_string/scramble_string.c | 8 +-- .../bst_inorder_traversal.c | 22 +++---- 113_path_sum_ii/path_sum.c | 13 ++-- .../stock.c | 30 +++++++++ 126_word_ladder_ii/word_ladder.c | 16 +++-- 127_word_ladder/word_ladder.c | 2 + .../palindrome_partition.c | 14 ++-- 134_gas_station/gas_station.c | 17 +++-- .../bst_preorder.c | 7 +- 155_min_stack/stack.c | 1 + 173_binary_search_tree_iterator/bst_iter.c | 64 ++++++------------- 174_dungeon_game/dungeon.c | 29 ++++++--- 199_binary_tree_right_side_view/bst_right.c | 10 +-- 209_minimum_size_subarray_sum/mini_size.c | 27 ++++---- 216_combination_sum_iii/combination_sum.c | 22 +++---- 221_maximal_square/maximal_square.c | 6 ++ .../bst_lca.c | 2 + 24 files changed, 213 insertions(+), 176 deletions(-) diff --git a/041_first_missing_positive/missing_positive.c b/041_first_missing_positive/missing_positive.c index 787a5a5..c047ef0 100644 --- a/041_first_missing_positive/missing_positive.c +++ b/041_first_missing_positive/missing_positive.c @@ -16,7 +16,9 @@ static int firstMissingPositive(int* nums, int numsSize) int i = 0; while (i < numsSize) { - if (nums[i] != i + 1 && nums[i] > 0 && nums[i] <= numsSize && nums[i] != nums[nums[i] - 1]) { + /* nums[i] should be i+1 and nums[nums[i] - 1] should be nums[i] */ + if (nums[i] != i + 1 && nums[i] > 0 && nums[i] <= numsSize && nums[nums[i] - 1] != nums[i]) { + /* nums[nums[i] - 1] <- nums[i] */ swap(nums + i, nums + nums[i] - 1); } else { i++; diff --git a/045_jump_game_ii/jump_game.c b/045_jump_game_ii/jump_game.c index 30a0202..b6d2ed3 100644 --- a/045_jump_game_ii/jump_game.c +++ b/045_jump_game_ii/jump_game.c @@ -12,7 +12,9 @@ static int jump(int* nums, int numsSize) int steps = 0; while (hi < numsSize - 1) { int right = 0; + /* [lo, hi] is the next location range, find the farest jump */ for (i = lo; i <= hi; i++) { + /* Assume right > hi for the purpose of the problem */ right = max(i + nums[i], right); } lo = hi + 1; diff --git a/055_jump_game/jump_game.c b/055_jump_game/jump_game.c index a768dc4..7dd5825 100644 --- a/055_jump_game/jump_game.c +++ b/055_jump_game/jump_game.c @@ -14,6 +14,7 @@ static bool canJump(int* nums, int numsSize) if (pos < i || pos >= numsSize - 1) { break; } + /* if all positive number it always can arrive. */ pos = max(i + nums[i], pos); } diff --git a/075_sort_colors/sort_colors.c b/075_sort_colors/sort_colors.c index d7017ad..0791746 100644 --- a/075_sort_colors/sort_colors.c +++ b/075_sort_colors/sort_colors.c @@ -9,49 +9,38 @@ static inline void swap(int *a, int *b) *b = tmp; } -/* - * RED = 0 - * WHITE = 1 - * BLUE = 2 - */ static void sortColors(int* nums, int numsSize) { - int i = 0, j = numsSize - 1; - while (i < j) { - while (nums[i] == 0 && i < j) { - i++; + int i, j = 0; + for (i = 0; i < numsSize; i++) { + if (nums[i] == 0) { + swap(nums + j, nums + i); + j++; } - while (nums[j] != 0 && j > i) { - j--; - } - swap(nums + i, nums + j); } - j = numsSize - 1; - while (i < j) { - while (nums[i] == 1 && i < j) { - i++; - } - while (nums[j] != 1 && j > i) { - j--; + + for (i = j; i < numsSize; i++) { + if (nums[i] == 1) { + swap(nums + j, nums + i); + j++; } - swap(nums + i, nums + j); } } int main(int argc, char **argv) { - if (argc != 2) { - fprintf(stderr, "Usage: ./test colors\n"); + if (argc < 2) { + fprintf(stderr, "Usage: ./test 2 0 2 1 1 0\n"); exit(-1); } - int i, count = strlen(argv[1]); + int i, count = argc - 1; int *nums = malloc(count * sizeof(int)); for (i = 0; i < count; i++) { - nums[i] = argv[1][i] - '0'; + nums[i] = atoi(argv[i + 1]); } sortColors(nums, count); for (i = 0; i < count; i++) { - printf("%d", nums[i]); + printf("%d ", nums[i]); } printf("\n"); return 0; diff --git a/080_remove_duplicates_from_sorted_array_ii/rm_dups.c b/080_remove_duplicates_from_sorted_array_ii/rm_dups.c index bc529ce..628761c 100644 --- a/080_remove_duplicates_from_sorted_array_ii/rm_dups.c +++ b/080_remove_duplicates_from_sorted_array_ii/rm_dups.c @@ -9,14 +9,17 @@ static int removeDuplicates(int* nums, int numsSize) int i; int len = 0; - int count = 0; + int count = 1; for (i = 1; i < numsSize; i++) { + /* Find the start position to be replaced */ if (nums[len] == nums[i]) { if (count < 2) { count++; + /* Replace in each iteration */ nums[++len] = nums[i]; } } else { + /* Here there are more than 2 duplicates */ count = 1; nums[++len] = nums[i]; } diff --git a/085_maximal_rectangle/maximal_rectangle.c b/085_maximal_rectangle/maximal_rectangle.c index 3edadbd..c33ad1c 100644 --- a/085_maximal_rectangle/maximal_rectangle.c +++ b/085_maximal_rectangle/maximal_rectangle.c @@ -11,32 +11,32 @@ static inline int max(int a, int b) static int area_calc(int *heights, int size) { int *indexes = malloc(size * sizeof(int)); - int *left = malloc(size * sizeof(int)); - int *right = malloc(size * sizeof(int)); + int *lhist = malloc(size * sizeof(int)); + int *rhist = malloc(size * sizeof(int)); int i, pos = 0; for (i = 0; i < size; i++) { - /* monotonous increasing stack */ + /* squeeze to keep monotonous increasing histograms */ while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { pos--; } - left[i] = pos == 0 ? -1 : indexes[pos - 1]; + lhist[i] = pos == 0 ? -1 : indexes[pos - 1]; indexes[pos++] = i; } pos = 0; for (i = size - 1; i >= 0; i--) { - /* monotonous increasing stack */ + /* squeeze to keep monotonous increasing histograms */ while (pos > 0 && heights[indexes[pos - 1]] >= heights[i]) { pos--; } - right[i] = pos == 0 ? size : indexes[pos - 1]; + rhist[i] = pos == 0 ? size : indexes[pos - 1]; indexes[pos++] = i; } int max_area = 0; for (i = 0; i < size; i++) { - int area = heights[i] * (right[i] - left[i] - 1); + int area = heights[i] * (rhist[i] - lhist[i] - 1); max_area = max(area, max_area); } diff --git a/086_partition_list/partition_list.c b/086_partition_list/partition_list.c index 1dcc37c..090b469 100644 --- a/086_partition_list/partition_list.c +++ b/086_partition_list/partition_list.c @@ -6,29 +6,37 @@ struct ListNode { struct ListNode *next; }; -struct ListNode* partition(struct ListNode* head, int x) { +struct ListNode* partition(struct ListNode* head, int x) +{ struct ListNode dummy; - struct ListNode *p = NULL, *start = &dummy, *pivot; + struct ListNode *prev1 = &dummy, *pivot; + dummy.next = head; for (pivot = head; pivot != NULL; pivot = pivot->next) { if (pivot->val >= x) { - /* start->next == pivot */ break; } - start = pivot; + prev1 = pivot; } - struct ListNode *prev; - for (p = pivot; p != NULL; p = p->next) { + struct ListNode *p = pivot->next; + struct ListNode *prev2 = pivot; + while (p != NULL) { if (p->val < x) { - prev->next = p->next; - p->next = start->next; - start->next = p; - start = p; - p = prev; + /* deletion */ + prev2->next = p->next; + /* insertion */ + p->next = prev1->next; + prev1->next = p; + /* iteration */ + prev1 = p; + p = prev2->next; + } else { + prev2 = p; + p = p->next; } - prev = p; } + return dummy.next; } diff --git a/087_scramble_string/scramble_string.c b/087_scramble_string/scramble_string.c index 7e379bd..a595bf3 100644 --- a/087_scramble_string/scramble_string.c +++ b/087_scramble_string/scramble_string.c @@ -12,8 +12,6 @@ * or * isScramble(s1[0..j], s2[n - j - 1, n]) && isScramble(s1[j+1..n], s2[0..n - j]) */ -#define N 128 - static bool scramble(char *s1, int low1, int high1, char *s2, int low2, int high2) { if (high1 - low1 != high2 - low2) { @@ -21,16 +19,14 @@ static bool scramble(char *s1, int low1, int high1, char *s2, int low2, int high } else if (!memcmp(s1 + low1, s2 + low2, high1 - low1 + 1)) { return true; } else { - int i, c1[N], c2[N]; - memset(c1, 0, N * sizeof(int)); - memset(c2, 0, N * sizeof(int)); + int i, c1[128] = { 0 }, c2[128] = { 0 }; for (i = low1; i <= high1; i++) { c1[s1[i]]++; } for (i = low2; i <= high2; i++) { c2[s2[i]]++; } - if (memcmp(c1, c2, N * sizeof(int))) { + if (memcmp(c1, c2, 128 * sizeof(int))) { return false; } else { int len = high1 - low1 + 1; diff --git a/094_binary_tree_inorder_traversal/bst_inorder_traversal.c b/094_binary_tree_inorder_traversal/bst_inorder_traversal.c index ad7253f..1c248c1 100644 --- a/094_binary_tree_inorder_traversal/bst_inorder_traversal.c +++ b/094_binary_tree_inorder_traversal/bst_inorder_traversal.c @@ -1,24 +1,22 @@ #include #include - struct TreeNode { - int val; - struct TreeNode *left; - struct TreeNode *right; - }; +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; static void traverse(struct TreeNode *node, int *result, int *count) { - if (node->left != NULL) { - traverse(node->left, result, count); + if (node == NULL) { + return; } - + + traverse(node->left, result, count); result[*count] = node->val; (*count)++; - - if (node->right != NULL) { - traverse(node->right, result, count); - } + traverse(node->right, result, count); } /** diff --git a/113_path_sum_ii/path_sum.c b/113_path_sum_ii/path_sum.c index 5ab7343..43071cc 100644 --- a/113_path_sum_ii/path_sum.c +++ b/113_path_sum_ii/path_sum.c @@ -12,20 +12,17 @@ static void dfs(struct TreeNode *node, int sum, int *stack, int len, int **resul { if (node == NULL) { return; - } - - sum -= node->val; - if (node->left == NULL && node->right == NULL && sum == 0) { + } else if (node->left == NULL && node->right == NULL && sum == node->val) { results[*count] = malloc((len + 1) * sizeof(int)); memcpy(results[*count], stack, len * sizeof(int)); results[*count][len] = node->val; sizes[*count] = len + 1; (*count)++; - return; + } else { + stack[len] = node->val; + dfs(node->left, sum - node->val, stack, len + 1, results, sizes, count); + dfs(node->right, sum - node->val, stack, len + 1, results, sizes, count); } - stack[len] = node->val; - dfs(node->left, sum, stack, len + 1, results, sizes, count); - dfs(node->right, sum, stack, len + 1, results, sizes, count); } static int **pathSum(struct TreeNode *root, int sum, int **columnSizes, int *returnSize) diff --git a/123_best_time_to_buy_and_sell_stock_iii/stock.c b/123_best_time_to_buy_and_sell_stock_iii/stock.c index 86d0f95..c0e38ef 100644 --- a/123_best_time_to_buy_and_sell_stock_iii/stock.c +++ b/123_best_time_to_buy_and_sell_stock_iii/stock.c @@ -1,6 +1,34 @@ +#include #include #include + +#if 0 +static inline max(int a, int b) +{ + return a > b ? a : b; +} + +static int maxProfit(int* prices, int pricesSize) +{ + int i; + int s1 = INT_MIN; /* first buy state */ + int s2 = 0; /* first sell state */ + int s3 = INT_MIN; /* second buy state */ + int s4 = 0; /* second sell state */ + + for (i = 0; i < pricesSize; i++) { + /* state transition */ + s1 = max(s1, 0 - prices[i]); + s2 = max(s2, s1 + prices[i]); + s3 = max(s3, s2 - prices[i]); + s4 = max(s4, s3 + prices[i]); + } + + return max(s2, s4); +} +#else + static int maxProfit(int* prices, int pricesSize) { if (pricesSize == 0) { @@ -9,6 +37,7 @@ static int maxProfit(int* prices, int pricesSize) int i, tmp, diff = 0, min = prices[0]; int *left_profit = malloc(pricesSize * sizeof(int)); + left_profit[0] = 0; for (i = 1; i < pricesSize; i++) { if (prices[i] < min) { min = prices[i]; @@ -35,6 +64,7 @@ static int maxProfit(int* prices, int pricesSize) return total; } +#endif int main(int argc, char **argv) { diff --git a/126_word_ladder_ii/word_ladder.c b/126_word_ladder_ii/word_ladder.c index 7305ddc..a4cd2f7 100644 --- a/126_word_ladder_ii/word_ladder.c +++ b/126_word_ladder_ii/word_ladder.c @@ -150,10 +150,10 @@ static void parent_add(struct word_tree *parent, struct word_tree *child) /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** The sizes of the arrays are returned as *returnColumnSizes array. + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordListSize, int** columnSizes, int* returnSize) +static char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordListSize, int* returnSize, int** returnColumnSizes) { int i, j, k; int len = strlen(beginWord); @@ -180,9 +180,11 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int hlist_add_head(&node->node, &hhead[hash]); } + /* FIFO */ struct list_head *p, queue; INIT_LIST_HEAD(&queue); + /* Build tree structure for BFS */ struct word_tree *root = malloc(sizeof(*root)); root->word = beginWord; root->step = 1; @@ -196,6 +198,7 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int node->step = 1; } + /* BFS with FIFO for shortest path */ struct word_tree *first = root; while (strcmp(first->word, endWord)) { strcpy(word, first->word); @@ -211,6 +214,7 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int struct word_tree *w = list_entry(p, struct word_tree, sibling); if (!strcmp(w->word, node->word)) { enqueue = 0; + /* record the parant relation */ parent_add(first, w); break; } @@ -279,9 +283,9 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int } } - *columnSizes = malloc(i * sizeof(int)); + *returnColumnSizes = malloc(i * sizeof(int)); for (j = 0; j < i; j++) { - (*columnSizes)[j] = size; + (*returnColumnSizes)[j] = size; } *returnSize = i; return results; @@ -295,7 +299,7 @@ int main(int argc, char **argv) } int i, j, *sizes, count = 0; - char ***lists = findLadders(argv[1], argv[2], argv + 3, argc - 3, &sizes, &count); + char ***lists = findLadders(argv[1], argv[2], argv + 3, argc - 3, &count, &sizes); for (i = 0; i < count; i++) { for (j = 0; j < sizes[i]; j++) { printf("%s ", lists[i][j]); diff --git a/127_word_ladder/word_ladder.c b/127_word_ladder/word_ladder.c index 0ae1d43..c025ce4 100644 --- a/127_word_ladder/word_ladder.c +++ b/127_word_ladder/word_ladder.c @@ -142,11 +142,13 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor hlist_add_head(&node->node, &hhead[hash]); } + /* FIFO */ INIT_LIST_HEAD(&queue); struct word_node *first = malloc(sizeof(*node)); first->word = beginWord; first->step = 1; + /* BFS with FIFO for shortest path */ while (strcmp(first->word, endWord)) { strcpy(word, first->word); for (i = 0; i < len; i++) { diff --git a/131_palindrome_patitioning/palindrome_partition.c b/131_palindrome_patitioning/palindrome_partition.c index 2691e0f..cc83084 100644 --- a/131_palindrome_patitioning/palindrome_partition.c +++ b/131_palindrome_patitioning/palindrome_partition.c @@ -21,7 +21,7 @@ static void collect(char *s, int len, int low, int high, struct palindrome *resu static void dfs(struct palindrome *pal_set, int num, int start, char *s, int len, struct palindrome **stack, int size, - char ***results, int *col_sizes, int *count) + char ***results, int *count, int *col_sizes) { int i; if (size > 0 && stack[size - 1]->high == len - 1) { @@ -40,7 +40,7 @@ static void dfs(struct palindrome *pal_set, int num, int start, if ((size == 0 && pal_set[i].low == 0) || (size > 0 && stack[size - 1]->high + 1 == pal_set[i].low)) { stack[size] = &pal_set[i]; - dfs(pal_set, num, i + 1, s, len, stack, size + 1, results, col_sizes, count); + dfs(pal_set, num, i + 1, s, len, stack, size + 1, results, count, col_sizes); } } } @@ -48,10 +48,10 @@ static void dfs(struct palindrome *pal_set, int num, int start, /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. + ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). **/ -static char ***partition(char* s, int** columnSizes, int* returnSize) +static char ***partition(char* s, int* returnSize, int** returnColumnSizes) { int len = strlen(s); if (len == 0) { @@ -68,8 +68,8 @@ static char ***partition(char* s, int** columnSizes, int* returnSize) char ***results = malloc(cap * sizeof(char **)); struct palindrome **stack = malloc(count * sizeof(*stack)); - *columnSizes = malloc(cap * sizeof(int)); - dfs(pal_set, count, 0, s, len, stack, 0, results, *columnSizes, returnSize); + *returnColumnSizes = malloc(cap * sizeof(int)); + dfs(pal_set, count, 0, s, len, stack, 0, results, returnSize, *returnColumnSizes); return results; } @@ -82,7 +82,7 @@ int main(int argc, char **argv) int i, j, count = 0; int *col_sizes; - char ***lists = partition(argv[1], &col_sizes, &count); + char ***lists = partition(argv[1], &count, &col_sizes); for (i = 0; i < count; i++) { char **list = lists[i]; for (j = 0; j < col_sizes[i]; j++) { diff --git a/134_gas_station/gas_station.c b/134_gas_station/gas_station.c index f9e1641..4c0e85e 100644 --- a/134_gas_station/gas_station.c +++ b/134_gas_station/gas_station.c @@ -4,6 +4,10 @@ static int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) { int i, j, store = 0, start = -1; + + /* the solution(start) is guaranteed to be + * unique for the purpose of this problem + */ for (i = 0; i < gasSize; i++) { if (start < 0) { start = i; @@ -14,14 +18,15 @@ static int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) start = -1; } } - if (start > 0) { - for (i = 0; i < start; i++) { - store += gas[i] - cost[i]; - if (store < 0) { - return -1; - } + + /* if start == -1 just return */ + for (i = 0; i < start; i++) { + store += gas[i] - cost[i]; + if (store < 0) { + return -1; } } + return start; } diff --git a/144_binary_tree_preorder_traversal/bst_preorder.c b/144_binary_tree_preorder_traversal/bst_preorder.c index 1a5e9a8..a639003 100644 --- a/144_binary_tree_preorder_traversal/bst_preorder.c +++ b/144_binary_tree_preorder_traversal/bst_preorder.c @@ -11,7 +11,8 @@ struct TreeNode { ** Return an array of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ -static int* preorderTraversal(struct TreeNode* root, int* returnSize) { +static int* preorderTraversal(struct TreeNode* root, int* returnSize) +{ if (root == NULL) { return NULL; } @@ -22,8 +23,12 @@ static int* preorderTraversal(struct TreeNode* root, int* returnSize) { struct TreeNode **top = stack; struct TreeNode *node = root; + /* node != NULL condition is just for the first iteration and + * never push NULL into the stack + */ while (node != NULL || top != stack) { if (node == NULL) { + /* pop up */ node = *--top; } diff --git a/155_min_stack/stack.c b/155_min_stack/stack.c index d846d35..d21ba29 100644 --- a/155_min_stack/stack.c +++ b/155_min_stack/stack.c @@ -27,6 +27,7 @@ static void minStackPush(MinStack* const obj, const int x) static void minStackPop(MinStack* const obj) { int i; + /* We records min index but not min value to save unnecessary operation */ if (--obj->num == obj->min_idx) { int min_idx = 0; for (i = 1; i < obj->num; i++) { diff --git a/173_binary_search_tree_iterator/bst_iter.c b/173_binary_search_tree_iterator/bst_iter.c index bfe2955..2dead2f 100644 --- a/173_binary_search_tree_iterator/bst_iter.c +++ b/173_binary_search_tree_iterator/bst_iter.c @@ -8,70 +8,48 @@ struct TreeNode { struct TreeNode *right; }; -struct ListNode { - int val; - struct ListNode *next; -}; +typedef struct { + int size; + int index; + int nums[10000]; +} BSTIterator; -struct BSTIterator { - struct ListNode dummy; - struct ListNode *p; -}; - -static void bst_iter_generater(struct TreeNode *node, struct BSTIterator *iter) +static void dfs(struct TreeNode* root, BSTIterator *obj) { - if (node->left != NULL) { - bst_iter_generater(node->left, iter); + if (root == NULL) { + return; } - struct ListNode *new = malloc(sizeof(*new)); - new->val = node->val; - new->next = NULL; - if (iter->p != NULL) { - iter->p->next = new; - } else { - iter->dummy.next = new; - } - iter->p = new; - - if (node->right != NULL) { - bst_iter_generater(node->right, iter); - } + dfs(root->left, obj); + obj->nums[obj->size++] = root->val; + dfs(root->right, obj); } static struct BSTIterator *bstIteratorCreate(struct TreeNode *root) { - struct BSTIterator *iter = malloc(sizeof(*iter)); - if (root != NULL) { - iter->p = NULL; - bst_iter_generater(root, iter); - } - iter->p = &iter->dummy; + struct BSTIterator *obj = malloc(sizeof(*obj)); + obj->index = 0; + obj->size = 0; + dfs(root, obj); return iter; } /** @return whether we have a next smallest number */ -static bool bstIteratorHasNext(struct BSTIterator *iter) +static bool bstIteratorHasNext(struct BSTIterator *obj) { - return iter->p->next != NULL; + return obj->index < obj->size; } /** @return the next smallest number */ -static int bstIteratorNext(struct BSTIterator *iter) +static int bstIteratorNext(struct BSTIterator *obj) { - iter->p = iter->p->next; - return iter->p->val; + return obj->nums[obj->index++]; } /** Deallocates memory iteriously allocated for the iterator */ -static void bstIteratorFree(struct BSTIterator *iter) +static void bstIteratorFree(struct BSTIterator *obj) { - iter->p = iter->dummy.next; - while (iter->p != NULL) { - iter->dummy.next = iter->p->next; - free(iter->p); - iter->p = iter->dummy.next; - } + free(obj); } int main(void) diff --git a/174_dungeon_game/dungeon.c b/174_dungeon_game/dungeon.c index 9e78f73..c1ab8a5 100644 --- a/174_dungeon_game/dungeon.c +++ b/174_dungeon_game/dungeon.c @@ -1,6 +1,5 @@ #include #include -#include static int calculateMinimumHP(int** dungeon, int dungeonRowSize, int dungeonColSize) { @@ -10,15 +9,25 @@ static int calculateMinimumHP(int** dungeon, int dungeonRowSize, int dungeonColS dp[i] = malloc(dungeonColSize * sizeof(int)); } - for (i = dungeonRowSize - 1; i >= 0; i--) { - for (j = dungeonColSize - 1; j >= 0; j--) { - if (i == dungeonRowSize - 1 && j == dungeonColSize - 1) { - dp[i][j] = 1 - dungeon[i][j] > 1 ? 1 - dungeon[i][j] : 1; - } else { - int hp1 = i == dungeonRowSize - 1 ? INT_MAX : (dp[i + 1][j] - dungeon[i][j] > 1 ? dp[i + 1][j] - dungeon[i][j] : 1); - int hp2 = j == dungeonColSize - 1 ? INT_MAX : (dp[i][j + 1] - dungeon[i][j] > 1 ? dp[i][j + 1] - dungeon[i][j] : 1); - dp[i][j] = hp1 < hp2 ? hp1 : hp2; - } + int hp = 1 - dungeon[dungeonRowSize - 1][dungeonColSize - 1]; + dp[dungeonRowSize - 1][dungeonColSize - 1] = hp >= 1 ? hp : 1; + for (i = dungeonRowSize - 2; i >= 0; i--) { + hp = dp[i + 1][dungeonColSize - 1] - dungeon[i][dungeonColSize - 1]; + dp[i][dungeonColSize - 1] = hp >= 1 ? hp : 1; + } + + for (i = dungeonColSize - 2; i >= 0; i--) { + hp = dp[dungeonRowSize - 1][i + 1] - dungeon[dungeonRowSize - 1][i]; + dp[dungeonRowSize - 1][i] = hp >= 1 ? hp : 1; + } + + for (i = dungeonRowSize - 2; i >= 0; i--) { + for (j = dungeonColSize - 2; j >= 0; j--) { + int hp_r = dp[i][j + 1] - dungeon[i][j]; + int hp_d = dp[i + 1][j] - dungeon[i][j]; + hp_r = hp_r >= 1 ? hp_r : 1; + hp_d = hp_d >= 1 ? hp_d : 1; + dp[i][j] = hp_r < hp_d ? hp_r : hp_d; } } diff --git a/199_binary_tree_right_side_view/bst_right.c b/199_binary_tree_right_side_view/bst_right.c index 9956c90..4993d08 100644 --- a/199_binary_tree_right_side_view/bst_right.c +++ b/199_binary_tree_right_side_view/bst_right.c @@ -76,6 +76,7 @@ struct bfs_node { static struct bfs_node *node_new(struct list_head *free_list, struct TreeNode *node) { + /* Reusage in free node pool */ struct bfs_node *new; if (list_empty(free_list)) { new = malloc(sizeof(*new)); @@ -87,8 +88,8 @@ static struct bfs_node *node_new(struct list_head *free_list, struct TreeNode *n return new; } -static void queue(struct list_head *parents, struct list_head *children, - struct list_head *free_list, int *results, int *count) +static void bfs(struct list_head *parents, struct list_head *children, + struct list_head *free_list, int *results, int *count) { struct list_head *p, *n; list_for_each(p, parents) { @@ -141,11 +142,12 @@ static int* rightSideView(struct TreeNode* root, int* returnSize) struct bfs_node *new = node_new(&free_list, root); list_add_tail(&new->link, &q0); + /* Interleaving parent and children FIFO queues */ while (!list_empty(&q0) || !list_empty(&q1)) { if (level & 0x1) { - queue(&q1, &q0, &free_list, results, returnSize); + bfs(&q1, &q0, &free_list, results, returnSize); } else { - queue(&q0, &q1, &free_list, results, returnSize); + bfs(&q0, &q1, &free_list, results, returnSize); } level++; } diff --git a/209_minimum_size_subarray_sum/mini_size.c b/209_minimum_size_subarray_sum/mini_size.c index 7e915b9..303907f 100644 --- a/209_minimum_size_subarray_sum/mini_size.c +++ b/209_minimum_size_subarray_sum/mini_size.c @@ -2,27 +2,24 @@ #include #include +static inline int min(int a, int b) +{ + return a < b ? a : b; +} + static int minSubArrayLen(int s, int* nums, int numsSize) { - int i, j, sum = 0, min = INT_MAX; - for (i = 0, j = 0; i < numsSize; i++) { + int i, sum = 0, len = INT_MAX, start = 0; + for (i = 0; i < numsSize; i++) { sum += nums[i]; - if (sum >= s) { - while (j <= i) { - sum -= nums[j++]; - if (sum < s) { - int interv = i - j + 2; - min = interv < min ? interv : min; - if (min == 1) { - return 1; - } - break; - } - } + while (sum >= s) { + /* sliding window */ + len = min(len, i - start + 1); + sum -= nums[start++]; } } - return min == INT_MAX ? 0 : min; + return len == INT_MAX ? 0 : len; } int main(int argc, char **argv) diff --git a/216_combination_sum_iii/combination_sum.c b/216_combination_sum_iii/combination_sum.c index 52b124e..a51761a 100644 --- a/216_combination_sum_iii/combination_sum.c +++ b/216_combination_sum_iii/combination_sum.c @@ -3,31 +3,31 @@ #include #include -static void dfs(int *nums, int size, int start, int target, int num, - int *solution, int len, int **results, int *column_sizes, int *count) +static void dfs(int *nums, int size, int start, int target, int k, + int *solution, int len, int **results, int *count, int *col_sizes) { int i; - if (len == num) { + if (len == k) { if (target == 0) { results[*count] = malloc(len * sizeof(int)); memcpy(results[*count], solution, len * sizeof(int)); - column_sizes[*count] = len; + col_sizes[*count] = len; (*count)++; } } else if (target > 0) { for (i = start; i < size; i++) { solution[len] = nums[i]; - dfs(nums, size, i + 1, target - nums[i], num, solution, len + 1, results, column_sizes, count); + dfs(nums, size, i + 1, target - nums[i], k, solution, len + 1, results, count, col_sizes); } } } /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** The sizes of the arrays are returned as *returnColumnSizes array. + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static int** combinationSum3(int k, int n, int** columnSizes, int* returnSize) +static int** combinationSum3(int k, int n, int* returnSize, int** returnColumnSizes) { int i, count = 9; int *nums = malloc(count * sizeof(int)); @@ -37,9 +37,9 @@ static int** combinationSum3(int k, int n, int** columnSizes, int* returnSize) int *solution = malloc(k * sizeof(int)); int **results = malloc(100 * sizeof(int *)); - *columnSizes = malloc(100 * sizeof(int)); + *returnColumnSizes = malloc(100 * sizeof(int)); *returnSize = 0; - dfs(nums, count, 0, n, k, solution, 0, results, *columnSizes, returnSize); + dfs(nums, count, 0, n, k, solution, 0, results, returnSize, *returnColumnSizes); return results; } @@ -54,7 +54,7 @@ int main(int argc, char **argv) int k = atoi(argv[1]); int n = atoi(argv[2]); int *sizes, count = 0; - int **lists = combinationSum3(k, n, &sizes, &count); + int **lists = combinationSum3(k, n, &count, &sizes); for (i = 0; i < count; i++) { for (j = 0; j < sizes[i]; j++) { printf("%d ", lists[i][j]); diff --git a/221_maximal_square/maximal_square.c b/221_maximal_square/maximal_square.c index c014308..e21ec4b 100644 --- a/221_maximal_square/maximal_square.c +++ b/221_maximal_square/maximal_square.c @@ -41,6 +41,12 @@ static int maximalSquare(char** matrix, int matrixRowSize, int matrixColSize) max_len = max(max_len, lens[i][j]); } } + for (i = 0; i < matrixRowSize; i++) { + for (j = 0; j < matrixColSize; j++) { + printf("%d ", lens[i][j]); + } + printf("\n"); + } return max_len * max_len; } diff --git a/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c b/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c index 28c9ab7..2b83bef 100644 --- a/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c +++ b/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c @@ -16,11 +16,13 @@ static struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeN struct TreeNode *l = lowestCommonAncestor(root->left, p, q); if (l != NULL && l != p && l != q) { + /* both p and q in left subtree: l->left != NULL && l->right != NULL */ return l; } struct TreeNode *r = lowestCommonAncestor(root->right, p, q); if (r != NULL && r != p && r != q) { + /* both p and q in right subtree: r->left != NULL && r->right != NULL */ return r; } From 56790b9aebd152e4dbf588b2a9f0fe436a8892a4 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 28 Jun 2020 09:49:37 +0800 Subject: [PATCH 076/211] Use -O1 option for makefile Signed-off-by: begeekmyfriend --- 001_two_sum/Makefile | 2 +- 002_add_two_numbers/Makefile | 2 +- 003_longest_substring_without_repeat/Makefile | 2 +- 004_median_of_two_sorted_array/Makefile | 2 +- 005_longest_palindromic_substring/Makefile | 2 +- 006_zigzag_conversion/Makefile | 2 +- 007_reverse_integer/Makefile | 2 +- 008_atoi/Makefile | 2 +- 009_palindrome_number/Makefile | 2 +- 010_regular_expression_matching/Makefile | 2 +- 011_container_with_most_water/Makefile | 2 +- 012_roman_numeral/Makefile | 2 +- 013_roman_to_integer/Makefile | 2 +- 014_longest_common_prefix/Makefile | 2 +- 015_three_sum/Makefile | 2 +- 016_three_sum_closest/Makefile | 2 +- 017_letter_combinations_of_a_phone_number/Makefile | 2 +- 018_four_sum/Makefile | 2 +- 019_remove_nth_node_from_end_of_list/Makefile | 2 +- 020_valid_parentheses/Makefile | 2 +- 021_merge_two_sorted_lists/Makefile | 2 +- 022_generate_parathesis/Makefile | 2 +- 023_merge_k_sorted_lists/Makefile | 2 +- 024_swap_nodes_in_pairs/Makefile | 2 +- 025_reverse_nodes_in_k_group/Makefile | 2 +- 026_remove_duplicates_from_sorted_array/Makefile | 2 +- 027_remove_element/Makefile | 2 +- 028_implement_strstr/Makefile | 2 +- 029_divide_two_integers/Makefile | 2 +- 030_substring_with_concatenation_of_all_words/Makefile | 2 +- 031_next_permutation/Makefile | 2 +- 032_longest_valid_parentheses/Makefile | 2 +- 033_search_in_rotated_sorted_array/Makefile | 2 +- 034_search_for_a_range/Makefile | 2 +- 035_search_insert_position/Makefile | 2 +- 036_valid_sudoku/Makefile | 2 +- 037_sudoku_solver/Makefile | 2 +- 038_count_and_say/Makefile | 2 +- 039_combination_sum/Makefile | 2 +- 040_combination_sum_ii/Makefile | 2 +- 041_first_missing_positive/Makefile | 2 +- 042_trapping_rain_water/Makefile | 2 +- 043_multiply_strings/Makefile | 2 +- 044_wildcard_matching/Makefile | 2 +- 045_jump_game_ii/Makefile | 2 +- 046_permutations/Makefile | 2 +- 047_permutations_ii/Makefile | 2 +- 048_rotate_image/Makefile | 2 +- 049_group_anagrams/Makefile | 2 +- 050_pow/Makefile | 2 +- 051_n_queens/Makefile | 2 +- 052_n_queens_ii/Makefile | 2 +- 053_maximum_subarray/Makefile | 2 +- 054_spiral_matrix/Makefile | 2 +- 055_jump_game/Makefile | 2 +- 056_merge_intervals/Makefile | 2 +- 057_insert_interval/Makefile | 2 +- 058_length_of_last_word/Makefile | 2 +- 059_spiral_matrix_ii/Makefile | 2 +- 060_permutation_sequence/Makefile | 2 +- 061_rotate_list/Makefile | 2 +- 062_unique_path/Makefile | 2 +- 063_unique_paths_ii/Makefile | 2 +- 064_minumum_path_sum/Makefile | 2 +- 065_valid_number/Makefile | 2 +- 066_plus_one/Makefile | 2 +- 067_add_binary/Makefile | 2 +- 068_text_justification/Makefile | 2 +- 069_sqrt/Makefile | 2 +- 070_climbing_stairs/Makefile | 2 +- 071_simplify_path/Makefile | 2 +- 072_edit_distance/Makefile | 2 +- 073_set_matrix_zeroes/Makefile | 2 +- 074_search_a_2d_matrix/Makefile | 2 +- 075_sort_colors/Makefile | 2 +- 076_minimum_window_substring/Makefile | 2 +- 077_combinations/Makefile | 2 +- 078_subsets/Makefile | 2 +- 079_word_search/Makefile | 2 +- 080_remove_duplicates_from_sorted_array_ii/Makefile | 2 +- 081_search_in_rotated_sorted_array_ii/Makefile | 2 +- 082_remove_duplicates_from_sorted_list_ii/Makefile | 2 +- 083_remove_duplicates_from_sorted_list/Makefile | 2 +- 084_largest_rectangle_in_histogram/Makefile | 2 +- 085_maximal_rectangle/Makefile | 2 +- 086_partition_list/Makefile | 2 +- 087_scramble_string/Makefile | 2 +- 088_merge_sorted_array/Makefile | 2 +- 089_gray_code/Makefile | 2 +- 090_subsets_ii/Makefile | 2 +- 091_decode_ways/Makefile | 2 +- 092_reverse_linked_list_ii/Makefile | 2 +- 093_restore_ip_addresses/Makefile | 2 +- 094_binary_tree_inorder_traversal/Makefile | 2 +- 095_unique_binary_search_trees_ii/Makefile | 2 +- 096_unique_binary_search_trees/Makefile | 2 +- 097_interleaving_string/Makefile | 2 +- 098_validate_binary_search_tree/Makefile | 2 +- 099_recover_binary_search_tree/Makefile | 2 +- 100_same_tree/Makefile | 2 +- 101_symmetric_tree/Makefile | 2 +- 102_binary_tree_level_order_traversal/Makefile | 2 +- 103_binary_tree_zigzag_level_order_traversal/Makefile | 2 +- 104_maximum_depth_of_binary_tree/Makefile | 2 +- .../Makefile | 2 +- .../Makefile | 2 +- 107_binary_tree_level_order_traversal_ii/Makefile | 2 +- 108_convert_sorted_array_to_binary_search_tree/Makefile | 2 +- 109_convert_sorted_list_to_binary_search_tree/Makefile | 2 +- 110_balanced_binary_tree/Makefile | 2 +- 111_minimum_depth_of_binary_tree/Makefile | 2 +- 112_path_sum/Makefile | 2 +- 113_path_sum_ii/Makefile | 2 +- 114_flatten_binary_tree_to_linked_list/Makefile | 2 +- 115_distinct_subsequences/Makefile | 2 +- 116_populating_next_right_pointers_in_each_node/Makefile | 2 +- 117_populating_next_right_pointers_in_each_node_ii/Makefile | 2 +- 118_pascal_triangle/Makefile | 2 +- 119_pascal_triangle_ii/Makefile | 2 +- 120_triangle/Makefile | 2 +- 121_best_time_to_buy_and_sell_stock/Makefile | 2 +- 122_best_time_to_buy_and_sell_stock_ii/Makefile | 2 +- 123_best_time_to_buy_and_sell_stock_iii/Makefile | 2 +- 124_binary_tree_maximum_path_sum/Makefile | 2 +- 125_valid_palindrome/Makefile | 2 +- 126_word_ladder_ii/Makefile | 2 +- 127_word_ladder/Makefile | 2 +- 128_longest_consecutive_sequence/Makefile | 2 +- 129_sum_root_to_leaf_numbers/Makefile | 2 +- 130_surrounded_regions/Makefile | 2 +- 131_palindrome_patitioning/Makefile | 2 +- 132_palindrome_patitioning_ii/Makefile | 2 +- 133_clone_graph/Makefile | 2 +- 134_gas_station/Makefile | 2 +- 135_candy/Makefile | 2 +- 136_single_number/Makefile | 2 +- 137_single_number_ii/Makefile | 2 +- 138_copy_list_with_random_pointer/Makefile | 2 +- 139_word_break/Makefile | 2 +- 140_word_break_ii/Makefile | 2 +- 141_linked_list_cycle/Makefile | 2 +- 142_linked_list_cycle_ii/Makefile | 2 +- 143_reorder_list/Makefile | 2 +- 144_binary_tree_preorder_traversal/Makefile | 2 +- 145_binary_tree_postorder_traversal/Makefile | 2 +- 146_lru_cache/Makefile | 2 +- 147_insertion_sort_list/Makefile | 2 +- 148_sort_list/Makefile | 2 +- 149_max_points_on_a_line/Makefile | 2 +- 150_evaluate_reverse_polish_notation/Makefile | 2 +- 151_reverse_words_in_a_string/Makefile | 2 +- 152_maximum_product_subarray/Makefile | 2 +- 153_find_minimum_in_rotated_sorted_array/Makefile | 2 +- 154_find_minimum_in_rotated_sorted_array_ii/Makefile | 2 +- 155_min_stack/Makefile | 2 +- 160_intersection_of_two_linked_list/Makefile | 2 +- 162_find_peak_element/Makefile | 2 +- 164_maximum_gap/Makefile | 2 +- 165_compare_version_numbers/Makefile | 2 +- 166_fraction_to_recurring_decimal/Makefile | 2 +- 167_two_sum_ii/Makefile | 2 +- 168_excel_sheet_column_title/Makefile | 2 +- 169_majority_element/Makefile | 2 +- 171_excel_sheet_column_number/Makefile | 2 +- 172_factorial_trailing_zeros/Makefile | 2 +- 173_binary_search_tree_iterator/Makefile | 2 +- 174_dungeon_game/Makefile | 2 +- 179_largest_number/Makefile | 2 +- 188_best_time_to_buy_and_sell_stock_iv/Makefile | 2 +- 189_rotate_array/Makefile | 2 +- 190_reverse_bits/Makefile | 2 +- 191_number_of_one_bits/Makefile | 2 +- 198_house_robber/Makefile | 2 +- 199_binary_tree_right_side_view/Makefile | 2 +- 200_number_of_islands/Makefile | 2 +- 201_bitwise_and_of_numbers_range/Makefile | 2 +- 202_happy_number/Makefile | 2 +- 203_remove_linked_list_element/Makefile | 2 +- 204_count_primes/Makefile | 2 +- 205_isomorphic_strings/Makefile | 2 +- 206_reverse_linked_list/Makefile | 2 +- 207_course_schedule/Makefile | 2 +- 208_implement_trie/Makefile | 2 +- 209_minimum_size_subarray_sum/Makefile | 2 +- 210_course_schedule_ii/Makefile | 2 +- 211_add_and_search_word/Makefile | 2 +- 212_word_search_ii/Makefile | 2 +- 213_house_robber_ii/Makefile | 2 +- 214_shortest_palindrome/Makefile | 2 +- 215_kth_largest_element_in_an_array/Makefile | 2 +- 216_combination_sum_iii/Makefile | 2 +- 221_maximal_square/Makefile | 2 +- 224_basic_calculator/Makefile | 2 +- 226_invert_binary_tree/Makefile | 2 +- 227_basic_calculator_ii/Makefile | 2 +- 229_majority_element_ii/Makefile | 2 +- 230_kth_smallest_element_in_a_bst/Makefile | 2 +- 235_lowest_common_ancestor_of_a_binary_search_tree/Makefile | 2 +- 236_lowest_common_ancestor_of_a_binary_tree/Makefile | 2 +- 239_sliding_window_maximum/Makefile | 2 +- 200 files changed, 200 insertions(+), 200 deletions(-) diff --git a/001_two_sum/Makefile b/001_two_sum/Makefile index ffb6456..e896cb5 100644 --- a/001_two_sum/Makefile +++ b/001_two_sum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test two_sum.c + gcc -O1 -o test two_sum.c diff --git a/002_add_two_numbers/Makefile b/002_add_two_numbers/Makefile index 9270c00..f5dfb55 100644 --- a/002_add_two_numbers/Makefile +++ b/002_add_two_numbers/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test add_two_numbers.c + gcc -O1 -o test add_two_numbers.c diff --git a/003_longest_substring_without_repeat/Makefile b/003_longest_substring_without_repeat/Makefile index b5dda9e..984d74e 100644 --- a/003_longest_substring_without_repeat/Makefile +++ b/003_longest_substring_without_repeat/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test longest_substring_without_repeat.c + gcc -O1 -o test longest_substring_without_repeat.c diff --git a/004_median_of_two_sorted_array/Makefile b/004_median_of_two_sorted_array/Makefile index 6fb3d51..7f15f60 100644 --- a/004_median_of_two_sorted_array/Makefile +++ b/004_median_of_two_sorted_array/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test median_of_two_sorted_array.c + gcc -O1 -o test median_of_two_sorted_array.c diff --git a/005_longest_palindromic_substring/Makefile b/005_longest_palindromic_substring/Makefile index d2434e6..4fe893e 100644 --- a/005_longest_palindromic_substring/Makefile +++ b/005_longest_palindromic_substring/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test longest_palindromic_substring.c + gcc -O1 -o test longest_palindromic_substring.c diff --git a/006_zigzag_conversion/Makefile b/006_zigzag_conversion/Makefile index 44cf21b..6c464e1 100644 --- a/006_zigzag_conversion/Makefile +++ b/006_zigzag_conversion/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test zigzag_conversion.c + gcc -O1 -o test zigzag_conversion.c diff --git a/007_reverse_integer/Makefile b/007_reverse_integer/Makefile index cf50d4d..100f5b9 100644 --- a/007_reverse_integer/Makefile +++ b/007_reverse_integer/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test reverse_integer.c + gcc -O1 -o test reverse_integer.c diff --git a/008_atoi/Makefile b/008_atoi/Makefile index 5910ca2..c401790 100644 --- a/008_atoi/Makefile +++ b/008_atoi/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test atoi.c + gcc -O1 -o test atoi.c diff --git a/009_palindrome_number/Makefile b/009_palindrome_number/Makefile index 5036f09..b8ce0a3 100644 --- a/009_palindrome_number/Makefile +++ b/009_palindrome_number/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test palindrome_number.c + gcc -O1 -o test palindrome_number.c diff --git a/010_regular_expression_matching/Makefile b/010_regular_expression_matching/Makefile index e012347..1f5279e 100644 --- a/010_regular_expression_matching/Makefile +++ b/010_regular_expression_matching/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test regular_expression.c + gcc -O1 -o test regular_expression.c diff --git a/011_container_with_most_water/Makefile b/011_container_with_most_water/Makefile index cfc4a90..f262392 100644 --- a/011_container_with_most_water/Makefile +++ b/011_container_with_most_water/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test container.c + gcc -O1 -o test container.c diff --git a/012_roman_numeral/Makefile b/012_roman_numeral/Makefile index b38195c..f27ed8d 100644 --- a/012_roman_numeral/Makefile +++ b/012_roman_numeral/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o roman_numeral roman_numeral.c + gcc -O1 -o roman_numeral roman_numeral.c diff --git a/013_roman_to_integer/Makefile b/013_roman_to_integer/Makefile index c713a4f..48e0ed0 100644 --- a/013_roman_to_integer/Makefile +++ b/013_roman_to_integer/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test roman_to_integer.c + gcc -O1 -o test roman_to_integer.c diff --git a/014_longest_common_prefix/Makefile b/014_longest_common_prefix/Makefile index 1003ec6..dd6aa66 100644 --- a/014_longest_common_prefix/Makefile +++ b/014_longest_common_prefix/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test common_prefix.c + gcc -O1 -o test common_prefix.c diff --git a/015_three_sum/Makefile b/015_three_sum/Makefile index 81b0519..fb5e2bb 100644 --- a/015_three_sum/Makefile +++ b/015_three_sum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test three_sum.c + gcc -O1 -o test three_sum.c diff --git a/016_three_sum_closest/Makefile b/016_three_sum_closest/Makefile index 4e07f03..71f9b43 100644 --- a/016_three_sum_closest/Makefile +++ b/016_three_sum_closest/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test three_sum_closest.c -lm + gcc -O1 -o test three_sum_closest.c -lm diff --git a/017_letter_combinations_of_a_phone_number/Makefile b/017_letter_combinations_of_a_phone_number/Makefile index 4016483..8b9d35d 100644 --- a/017_letter_combinations_of_a_phone_number/Makefile +++ b/017_letter_combinations_of_a_phone_number/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o letter_combinations letter_combinations.c + gcc -O1 -o letter_combinations letter_combinations.c diff --git a/018_four_sum/Makefile b/018_four_sum/Makefile index f1a42a7..8b576d1 100644 --- a/018_four_sum/Makefile +++ b/018_four_sum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test four_sum.c + gcc -O1 -o test four_sum.c diff --git a/019_remove_nth_node_from_end_of_list/Makefile b/019_remove_nth_node_from_end_of_list/Makefile index 41a447c..0ec5947 100644 --- a/019_remove_nth_node_from_end_of_list/Makefile +++ b/019_remove_nth_node_from_end_of_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test remove_end.c + gcc -O1 -o test remove_end.c diff --git a/020_valid_parentheses/Makefile b/020_valid_parentheses/Makefile index 04fa256..4a73e93 100644 --- a/020_valid_parentheses/Makefile +++ b/020_valid_parentheses/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test valid_parentheses.c + gcc -O1 -o test valid_parentheses.c diff --git a/021_merge_two_sorted_lists/Makefile b/021_merge_two_sorted_lists/Makefile index 9c7c9b0..aca334a 100644 --- a/021_merge_two_sorted_lists/Makefile +++ b/021_merge_two_sorted_lists/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test merge_lists.c + gcc -O1 -o test merge_lists.c diff --git a/022_generate_parathesis/Makefile b/022_generate_parathesis/Makefile index 6ad72c8..fb8a13d 100644 --- a/022_generate_parathesis/Makefile +++ b/022_generate_parathesis/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test parenthesis.c + gcc -O1 -o test parenthesis.c diff --git a/023_merge_k_sorted_lists/Makefile b/023_merge_k_sorted_lists/Makefile index 9c7c9b0..aca334a 100644 --- a/023_merge_k_sorted_lists/Makefile +++ b/023_merge_k_sorted_lists/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test merge_lists.c + gcc -O1 -o test merge_lists.c diff --git a/024_swap_nodes_in_pairs/Makefile b/024_swap_nodes_in_pairs/Makefile index a3f3513..8d9393d 100644 --- a/024_swap_nodes_in_pairs/Makefile +++ b/024_swap_nodes_in_pairs/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test swap_nodes.c + gcc -O1 -o test swap_nodes.c diff --git a/025_reverse_nodes_in_k_group/Makefile b/025_reverse_nodes_in_k_group/Makefile index d0564d0..24a4db6 100644 --- a/025_reverse_nodes_in_k_group/Makefile +++ b/025_reverse_nodes_in_k_group/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test reverse_nodes.c + gcc -O1 -o test reverse_nodes.c diff --git a/026_remove_duplicates_from_sorted_array/Makefile b/026_remove_duplicates_from_sorted_array/Makefile index 5cf5932..a4e0790 100644 --- a/026_remove_duplicates_from_sorted_array/Makefile +++ b/026_remove_duplicates_from_sorted_array/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rm_dup.c + gcc -O1 -o test rm_dup.c diff --git a/027_remove_element/Makefile b/027_remove_element/Makefile index 210f162..8c8bea3 100644 --- a/027_remove_element/Makefile +++ b/027_remove_element/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rm_elem.c + gcc -O1 -o test rm_elem.c diff --git a/028_implement_strstr/Makefile b/028_implement_strstr/Makefile index 2feaab7..7fedca7 100644 --- a/028_implement_strstr/Makefile +++ b/028_implement_strstr/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test strstr.c + gcc -O1 -o test strstr.c diff --git a/029_divide_two_integers/Makefile b/029_divide_two_integers/Makefile index 0c80c5b..2092b85 100644 --- a/029_divide_two_integers/Makefile +++ b/029_divide_two_integers/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test divide.c + gcc -O1 -o test divide.c diff --git a/030_substring_with_concatenation_of_all_words/Makefile b/030_substring_with_concatenation_of_all_words/Makefile index e9e4958..c0cbbfe 100644 --- a/030_substring_with_concatenation_of_all_words/Makefile +++ b/030_substring_with_concatenation_of_all_words/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test concatenation.c + gcc -O1 -o test concatenation.c diff --git a/031_next_permutation/Makefile b/031_next_permutation/Makefile index 437189e..cb26956 100644 --- a/031_next_permutation/Makefile +++ b/031_next_permutation/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test next_permutation.c + gcc -O1 -o test next_permutation.c diff --git a/032_longest_valid_parentheses/Makefile b/032_longest_valid_parentheses/Makefile index 04fa256..4a73e93 100644 --- a/032_longest_valid_parentheses/Makefile +++ b/032_longest_valid_parentheses/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test valid_parentheses.c + gcc -O1 -o test valid_parentheses.c diff --git a/033_search_in_rotated_sorted_array/Makefile b/033_search_in_rotated_sorted_array/Makefile index 18163ef..525f67a 100644 --- a/033_search_in_rotated_sorted_array/Makefile +++ b/033_search_in_rotated_sorted_array/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rotated_array.c + gcc -O1 -o test rotated_array.c diff --git a/034_search_for_a_range/Makefile b/034_search_for_a_range/Makefile index 8660352..8564929 100644 --- a/034_search_for_a_range/Makefile +++ b/034_search_for_a_range/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test range_search.c + gcc -O1 -o test range_search.c diff --git a/035_search_insert_position/Makefile b/035_search_insert_position/Makefile index 6a4bcfc..a86bd9f 100644 --- a/035_search_insert_position/Makefile +++ b/035_search_insert_position/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test insert_position.c + gcc -O1 -o test insert_position.c diff --git a/036_valid_sudoku/Makefile b/036_valid_sudoku/Makefile index fcc56aa..8564020 100644 --- a/036_valid_sudoku/Makefile +++ b/036_valid_sudoku/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test valid_sudoku.c + gcc -O1 -o test valid_sudoku.c diff --git a/037_sudoku_solver/Makefile b/037_sudoku_solver/Makefile index debabd7..bdb9f00 100644 --- a/037_sudoku_solver/Makefile +++ b/037_sudoku_solver/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test sudoku_solver.c + gcc -O1 -o test sudoku_solver.c diff --git a/038_count_and_say/Makefile b/038_count_and_say/Makefile index 27b8e9a..14c94b0 100644 --- a/038_count_and_say/Makefile +++ b/038_count_and_say/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test count_and_say.c + gcc -O1 -o test count_and_say.c diff --git a/039_combination_sum/Makefile b/039_combination_sum/Makefile index e5462fa..dafaf31 100644 --- a/039_combination_sum/Makefile +++ b/039_combination_sum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test combination_sum.c + gcc -O1 -o test combination_sum.c diff --git a/040_combination_sum_ii/Makefile b/040_combination_sum_ii/Makefile index e5462fa..dafaf31 100644 --- a/040_combination_sum_ii/Makefile +++ b/040_combination_sum_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test combination_sum.c + gcc -O1 -o test combination_sum.c diff --git a/041_first_missing_positive/Makefile b/041_first_missing_positive/Makefile index 4c24d01..d536d9b 100644 --- a/041_first_missing_positive/Makefile +++ b/041_first_missing_positive/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test missing_positive.c + gcc -O1 -o test missing_positive.c diff --git a/042_trapping_rain_water/Makefile b/042_trapping_rain_water/Makefile index 8d38674..79f7d1f 100644 --- a/042_trapping_rain_water/Makefile +++ b/042_trapping_rain_water/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test trap_water.c + gcc -O1 -o test trap_water.c diff --git a/043_multiply_strings/Makefile b/043_multiply_strings/Makefile index b90103f..237fde9 100644 --- a/043_multiply_strings/Makefile +++ b/043_multiply_strings/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test multiply_strings.c + gcc -O1 -o test multiply_strings.c diff --git a/044_wildcard_matching/Makefile b/044_wildcard_matching/Makefile index 9543392..8283d7f 100644 --- a/044_wildcard_matching/Makefile +++ b/044_wildcard_matching/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test wildcard_matching.c + gcc -O1 -o test wildcard_matching.c diff --git a/045_jump_game_ii/Makefile b/045_jump_game_ii/Makefile index e39cccc..d1332e7 100644 --- a/045_jump_game_ii/Makefile +++ b/045_jump_game_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test jump_game.c + gcc -O1 -o test jump_game.c diff --git a/046_permutations/Makefile b/046_permutations/Makefile index 25f7501..ba5645a 100644 --- a/046_permutations/Makefile +++ b/046_permutations/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test permutations.c + gcc -O1 -o test permutations.c diff --git a/047_permutations_ii/Makefile b/047_permutations_ii/Makefile index 25f7501..ba5645a 100644 --- a/047_permutations_ii/Makefile +++ b/047_permutations_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test permutations.c + gcc -O1 -o test permutations.c diff --git a/048_rotate_image/Makefile b/048_rotate_image/Makefile index 152b201..ab13146 100644 --- a/048_rotate_image/Makefile +++ b/048_rotate_image/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rotate.c + gcc -O1 -o test rotate.c diff --git a/049_group_anagrams/Makefile b/049_group_anagrams/Makefile index 787d9da..ce82d29 100644 --- a/049_group_anagrams/Makefile +++ b/049_group_anagrams/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test anagrams.c + gcc -O1 -o test anagrams.c diff --git a/050_pow/Makefile b/050_pow/Makefile index 59054b3..f5d61b6 100644 --- a/050_pow/Makefile +++ b/050_pow/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test pow.c + gcc -O1 -o test pow.c diff --git a/051_n_queens/Makefile b/051_n_queens/Makefile index 9efe93f..008246e 100644 --- a/051_n_queens/Makefile +++ b/051_n_queens/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test n_queens.c + gcc -O1 -o test n_queens.c diff --git a/052_n_queens_ii/Makefile b/052_n_queens_ii/Makefile index 9efe93f..008246e 100644 --- a/052_n_queens_ii/Makefile +++ b/052_n_queens_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test n_queens.c + gcc -O1 -o test n_queens.c diff --git a/053_maximum_subarray/Makefile b/053_maximum_subarray/Makefile index 32c2032..7eae3f9 100644 --- a/053_maximum_subarray/Makefile +++ b/053_maximum_subarray/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test max_subarray.c + gcc -O1 -o test max_subarray.c diff --git a/054_spiral_matrix/Makefile b/054_spiral_matrix/Makefile index 273c67f..1f55502 100644 --- a/054_spiral_matrix/Makefile +++ b/054_spiral_matrix/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test spiral_matrix.c + gcc -O1 -o test spiral_matrix.c diff --git a/055_jump_game/Makefile b/055_jump_game/Makefile index e39cccc..d1332e7 100644 --- a/055_jump_game/Makefile +++ b/055_jump_game/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test jump_game.c + gcc -O1 -o test jump_game.c diff --git a/056_merge_intervals/Makefile b/056_merge_intervals/Makefile index 9b568bc..ff7462d 100644 --- a/056_merge_intervals/Makefile +++ b/056_merge_intervals/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test merge_intervals.c + gcc -O1 -o test merge_intervals.c diff --git a/057_insert_interval/Makefile b/057_insert_interval/Makefile index bc9dd24..ce67b1c 100644 --- a/057_insert_interval/Makefile +++ b/057_insert_interval/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test insert_interval.c + gcc -O1 -o test insert_interval.c diff --git a/058_length_of_last_word/Makefile b/058_length_of_last_word/Makefile index fe49695..f31104a 100644 --- a/058_length_of_last_word/Makefile +++ b/058_length_of_last_word/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test word_length.c + gcc -O1 -o test word_length.c diff --git a/059_spiral_matrix_ii/Makefile b/059_spiral_matrix_ii/Makefile index 273c67f..1f55502 100644 --- a/059_spiral_matrix_ii/Makefile +++ b/059_spiral_matrix_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test spiral_matrix.c + gcc -O1 -o test spiral_matrix.c diff --git a/060_permutation_sequence/Makefile b/060_permutation_sequence/Makefile index 21302bd..59ea6ed 100644 --- a/060_permutation_sequence/Makefile +++ b/060_permutation_sequence/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test permutation_sequence.c + gcc -O1 -o test permutation_sequence.c diff --git a/061_rotate_list/Makefile b/061_rotate_list/Makefile index dd0aef9..cff17df 100644 --- a/061_rotate_list/Makefile +++ b/061_rotate_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rotate_list.c + gcc -O1 -o test rotate_list.c diff --git a/062_unique_path/Makefile b/062_unique_path/Makefile index 63953c4..9cf8815 100644 --- a/062_unique_path/Makefile +++ b/062_unique_path/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test unique_path.c + gcc -O1 -o test unique_path.c diff --git a/063_unique_paths_ii/Makefile b/063_unique_paths_ii/Makefile index 63953c4..9cf8815 100644 --- a/063_unique_paths_ii/Makefile +++ b/063_unique_paths_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test unique_path.c + gcc -O1 -o test unique_path.c diff --git a/064_minumum_path_sum/Makefile b/064_minumum_path_sum/Makefile index a70641a..71f593e 100644 --- a/064_minumum_path_sum/Makefile +++ b/064_minumum_path_sum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test minimum_path_sum.c + gcc -O1 -o test minimum_path_sum.c diff --git a/065_valid_number/Makefile b/065_valid_number/Makefile index bef5548..0490ac2 100644 --- a/065_valid_number/Makefile +++ b/065_valid_number/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test valid_number.c + gcc -O1 -o test valid_number.c diff --git a/066_plus_one/Makefile b/066_plus_one/Makefile index 954c8bf..5b94a50 100644 --- a/066_plus_one/Makefile +++ b/066_plus_one/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test plus_one.c + gcc -O1 -o test plus_one.c diff --git a/067_add_binary/Makefile b/067_add_binary/Makefile index 5b996ad..7a598de 100644 --- a/067_add_binary/Makefile +++ b/067_add_binary/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test add_binary.c + gcc -O1 -o test add_binary.c diff --git a/068_text_justification/Makefile b/068_text_justification/Makefile index afcf23f..b61a02c 100644 --- a/068_text_justification/Makefile +++ b/068_text_justification/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test justification.c + gcc -O1 -o test justification.c diff --git a/069_sqrt/Makefile b/069_sqrt/Makefile index 3d94c52..e7d7846 100644 --- a/069_sqrt/Makefile +++ b/069_sqrt/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test sqrt.c + gcc -O1 -o test sqrt.c diff --git a/070_climbing_stairs/Makefile b/070_climbing_stairs/Makefile index 8573363..b91c664 100644 --- a/070_climbing_stairs/Makefile +++ b/070_climbing_stairs/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test climb_stairs.c + gcc -O1 -o test climb_stairs.c diff --git a/071_simplify_path/Makefile b/071_simplify_path/Makefile index 5e49404..ba88f3d 100644 --- a/071_simplify_path/Makefile +++ b/071_simplify_path/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test simplify_path.c + gcc -O1 -o test simplify_path.c diff --git a/072_edit_distance/Makefile b/072_edit_distance/Makefile index b8aad45..328780a 100644 --- a/072_edit_distance/Makefile +++ b/072_edit_distance/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test edit_distance.c + gcc -O1 -o test edit_distance.c diff --git a/073_set_matrix_zeroes/Makefile b/073_set_matrix_zeroes/Makefile index 85d2147..b4a437b 100644 --- a/073_set_matrix_zeroes/Makefile +++ b/073_set_matrix_zeroes/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test set_zero.c + gcc -O1 -o test set_zero.c diff --git a/074_search_a_2d_matrix/Makefile b/074_search_a_2d_matrix/Makefile index ea35465..dd33b1e 100644 --- a/074_search_a_2d_matrix/Makefile +++ b/074_search_a_2d_matrix/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test matrix_search.c + gcc -O1 -o test matrix_search.c diff --git a/075_sort_colors/Makefile b/075_sort_colors/Makefile index 9cd170a..98448ea 100644 --- a/075_sort_colors/Makefile +++ b/075_sort_colors/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test sort_colors.c + gcc -O1 -o test sort_colors.c diff --git a/076_minimum_window_substring/Makefile b/076_minimum_window_substring/Makefile index 5cd14dc..5cd507a 100644 --- a/076_minimum_window_substring/Makefile +++ b/076_minimum_window_substring/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test window_substring.c + gcc -O1 -o test window_substring.c diff --git a/077_combinations/Makefile b/077_combinations/Makefile index 6361695..8c0689f 100644 --- a/077_combinations/Makefile +++ b/077_combinations/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test combinations.c + gcc -O1 -o test combinations.c diff --git a/078_subsets/Makefile b/078_subsets/Makefile index 580c713..92ed3f7 100644 --- a/078_subsets/Makefile +++ b/078_subsets/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test subsets.c + gcc -O1 -o test subsets.c diff --git a/079_word_search/Makefile b/079_word_search/Makefile index 99bef24..2eab6c6 100644 --- a/079_word_search/Makefile +++ b/079_word_search/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test word_search.c + gcc -O1 -o test word_search.c diff --git a/080_remove_duplicates_from_sorted_array_ii/Makefile b/080_remove_duplicates_from_sorted_array_ii/Makefile index 863c440..a842a72 100644 --- a/080_remove_duplicates_from_sorted_array_ii/Makefile +++ b/080_remove_duplicates_from_sorted_array_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rm_dups.c + gcc -O1 -o test rm_dups.c diff --git a/081_search_in_rotated_sorted_array_ii/Makefile b/081_search_in_rotated_sorted_array_ii/Makefile index 751e614..8ab5ddc 100644 --- a/081_search_in_rotated_sorted_array_ii/Makefile +++ b/081_search_in_rotated_sorted_array_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test search_rotated_array.c + gcc -O1 -o test search_rotated_array.c diff --git a/082_remove_duplicates_from_sorted_list_ii/Makefile b/082_remove_duplicates_from_sorted_list_ii/Makefile index 5cf5932..a4e0790 100644 --- a/082_remove_duplicates_from_sorted_list_ii/Makefile +++ b/082_remove_duplicates_from_sorted_list_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rm_dup.c + gcc -O1 -o test rm_dup.c diff --git a/083_remove_duplicates_from_sorted_list/Makefile b/083_remove_duplicates_from_sorted_list/Makefile index 5cf5932..a4e0790 100644 --- a/083_remove_duplicates_from_sorted_list/Makefile +++ b/083_remove_duplicates_from_sorted_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rm_dup.c + gcc -O1 -o test rm_dup.c diff --git a/084_largest_rectangle_in_histogram/Makefile b/084_largest_rectangle_in_histogram/Makefile index 8306292..a8c4132 100644 --- a/084_largest_rectangle_in_histogram/Makefile +++ b/084_largest_rectangle_in_histogram/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rect_in_histogram.c + gcc -O1 -o test rect_in_histogram.c diff --git a/085_maximal_rectangle/Makefile b/085_maximal_rectangle/Makefile index c85beaa..c3439ab 100644 --- a/085_maximal_rectangle/Makefile +++ b/085_maximal_rectangle/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test maximal_rectangle.c + gcc -O1 -o test maximal_rectangle.c diff --git a/086_partition_list/Makefile b/086_partition_list/Makefile index eabdaba..abdad5b 100644 --- a/086_partition_list/Makefile +++ b/086_partition_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test partition_list.c + gcc -O1 -o test partition_list.c diff --git a/087_scramble_string/Makefile b/087_scramble_string/Makefile index 52cecd7..e081260 100644 --- a/087_scramble_string/Makefile +++ b/087_scramble_string/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test scramble_string.c + gcc -O1 -o test scramble_string.c diff --git a/088_merge_sorted_array/Makefile b/088_merge_sorted_array/Makefile index e286d3c..8db1be1 100644 --- a/088_merge_sorted_array/Makefile +++ b/088_merge_sorted_array/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test merge_array.c + gcc -O1 -o test merge_array.c diff --git a/089_gray_code/Makefile b/089_gray_code/Makefile index dbe10ea..6580690 100644 --- a/089_gray_code/Makefile +++ b/089_gray_code/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test gray_code.c + gcc -O1 -o test gray_code.c diff --git a/090_subsets_ii/Makefile b/090_subsets_ii/Makefile index 580c713..92ed3f7 100644 --- a/090_subsets_ii/Makefile +++ b/090_subsets_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test subsets.c + gcc -O1 -o test subsets.c diff --git a/091_decode_ways/Makefile b/091_decode_ways/Makefile index 165f550..c958fe7 100644 --- a/091_decode_ways/Makefile +++ b/091_decode_ways/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test decode_ways.c + gcc -O1 -o test decode_ways.c diff --git a/092_reverse_linked_list_ii/Makefile b/092_reverse_linked_list_ii/Makefile index d480ecf..efe146e 100644 --- a/092_reverse_linked_list_ii/Makefile +++ b/092_reverse_linked_list_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test reverse_list.c + gcc -O1 -o test reverse_list.c diff --git a/093_restore_ip_addresses/Makefile b/093_restore_ip_addresses/Makefile index eae26d6..e224a93 100644 --- a/093_restore_ip_addresses/Makefile +++ b/093_restore_ip_addresses/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test ip_addr.c + gcc -O1 -o test ip_addr.c diff --git a/094_binary_tree_inorder_traversal/Makefile b/094_binary_tree_inorder_traversal/Makefile index d3ae6df..2e2f5f9 100644 --- a/094_binary_tree_inorder_traversal/Makefile +++ b/094_binary_tree_inorder_traversal/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_inorder_traversal.c + gcc -O1 -o test bst_inorder_traversal.c diff --git a/095_unique_binary_search_trees_ii/Makefile b/095_unique_binary_search_trees_ii/Makefile index c64e979..551f77b 100644 --- a/095_unique_binary_search_trees_ii/Makefile +++ b/095_unique_binary_search_trees_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test unique_bst.c + gcc -O1 -o test unique_bst.c diff --git a/096_unique_binary_search_trees/Makefile b/096_unique_binary_search_trees/Makefile index c64e979..551f77b 100644 --- a/096_unique_binary_search_trees/Makefile +++ b/096_unique_binary_search_trees/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test unique_bst.c + gcc -O1 -o test unique_bst.c diff --git a/097_interleaving_string/Makefile b/097_interleaving_string/Makefile index 8b5afb2..81bd21a 100644 --- a/097_interleaving_string/Makefile +++ b/097_interleaving_string/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test interleaving_string.c + gcc -O1 -o test interleaving_string.c diff --git a/098_validate_binary_search_tree/Makefile b/098_validate_binary_search_tree/Makefile index 72cc896..860620b 100644 --- a/098_validate_binary_search_tree/Makefile +++ b/098_validate_binary_search_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test valid_bst.c + gcc -O1 -o test valid_bst.c diff --git a/099_recover_binary_search_tree/Makefile b/099_recover_binary_search_tree/Makefile index 95d5434..2072b00 100644 --- a/099_recover_binary_search_tree/Makefile +++ b/099_recover_binary_search_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test recover_bst.c + gcc -O1 -o test recover_bst.c diff --git a/100_same_tree/Makefile b/100_same_tree/Makefile index cbec06a..c3ddded 100644 --- a/100_same_tree/Makefile +++ b/100_same_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test same_tree.c + gcc -O1 -o test same_tree.c diff --git a/101_symmetric_tree/Makefile b/101_symmetric_tree/Makefile index eb640cf..2ecc74a 100644 --- a/101_symmetric_tree/Makefile +++ b/101_symmetric_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test symmetric_tree.c + gcc -O1 -o test symmetric_tree.c diff --git a/102_binary_tree_level_order_traversal/Makefile b/102_binary_tree_level_order_traversal/Makefile index d8026db..e07b89e 100644 --- a/102_binary_tree_level_order_traversal/Makefile +++ b/102_binary_tree_level_order_traversal/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_bfs.c + gcc -O1 -o test bst_bfs.c diff --git a/103_binary_tree_zigzag_level_order_traversal/Makefile b/103_binary_tree_zigzag_level_order_traversal/Makefile index 48851f2..7e68f18 100644 --- a/103_binary_tree_zigzag_level_order_traversal/Makefile +++ b/103_binary_tree_zigzag_level_order_traversal/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_zigzag.c + gcc -O1 -o test bst_zigzag.c diff --git a/104_maximum_depth_of_binary_tree/Makefile b/104_maximum_depth_of_binary_tree/Makefile index 5a375a6..43333d6 100644 --- a/104_maximum_depth_of_binary_tree/Makefile +++ b/104_maximum_depth_of_binary_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_depth.c + gcc -O1 -o test bst_depth.c diff --git a/105_construct_binary_tree_from_preorder_and_inorder_traversal/Makefile b/105_construct_binary_tree_from_preorder_and_inorder_traversal/Makefile index fe2f6d1..737631e 100644 --- a/105_construct_binary_tree_from_preorder_and_inorder_traversal/Makefile +++ b/105_construct_binary_tree_from_preorder_and_inorder_traversal/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test binary_tree_build.c + gcc -O1 -o test binary_tree_build.c diff --git a/106_construct_binary_tree_from_inorder_and_postorder_traversal/Makefile b/106_construct_binary_tree_from_inorder_and_postorder_traversal/Makefile index fe2f6d1..737631e 100644 --- a/106_construct_binary_tree_from_inorder_and_postorder_traversal/Makefile +++ b/106_construct_binary_tree_from_inorder_and_postorder_traversal/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test binary_tree_build.c + gcc -O1 -o test binary_tree_build.c diff --git a/107_binary_tree_level_order_traversal_ii/Makefile b/107_binary_tree_level_order_traversal_ii/Makefile index d8026db..e07b89e 100644 --- a/107_binary_tree_level_order_traversal_ii/Makefile +++ b/107_binary_tree_level_order_traversal_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_bfs.c + gcc -O1 -o test bst_bfs.c diff --git a/108_convert_sorted_array_to_binary_search_tree/Makefile b/108_convert_sorted_array_to_binary_search_tree/Makefile index 113460f..cbb552d 100644 --- a/108_convert_sorted_array_to_binary_search_tree/Makefile +++ b/108_convert_sorted_array_to_binary_search_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_convert.c + gcc -O1 -o test bst_convert.c diff --git a/109_convert_sorted_list_to_binary_search_tree/Makefile b/109_convert_sorted_list_to_binary_search_tree/Makefile index 113460f..cbb552d 100644 --- a/109_convert_sorted_list_to_binary_search_tree/Makefile +++ b/109_convert_sorted_list_to_binary_search_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_convert.c + gcc -O1 -o test bst_convert.c diff --git a/110_balanced_binary_tree/Makefile b/110_balanced_binary_tree/Makefile index b36d4d9..5c6b35d 100644 --- a/110_balanced_binary_tree/Makefile +++ b/110_balanced_binary_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test balanced_bst.c + gcc -O1 -o test balanced_bst.c diff --git a/111_minimum_depth_of_binary_tree/Makefile b/111_minimum_depth_of_binary_tree/Makefile index 5a375a6..43333d6 100644 --- a/111_minimum_depth_of_binary_tree/Makefile +++ b/111_minimum_depth_of_binary_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_depth.c + gcc -O1 -o test bst_depth.c diff --git a/112_path_sum/Makefile b/112_path_sum/Makefile index 770d42b..6f978a5 100644 --- a/112_path_sum/Makefile +++ b/112_path_sum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test path_sum.c + gcc -O1 -o test path_sum.c diff --git a/113_path_sum_ii/Makefile b/113_path_sum_ii/Makefile index 770d42b..6f978a5 100644 --- a/113_path_sum_ii/Makefile +++ b/113_path_sum_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test path_sum.c + gcc -O1 -o test path_sum.c diff --git a/114_flatten_binary_tree_to_linked_list/Makefile b/114_flatten_binary_tree_to_linked_list/Makefile index b4afb6d..2c1b4b2 100644 --- a/114_flatten_binary_tree_to_linked_list/Makefile +++ b/114_flatten_binary_tree_to_linked_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test flatten.c + gcc -O1 -o test flatten.c diff --git a/115_distinct_subsequences/Makefile b/115_distinct_subsequences/Makefile index 63c359e..03f027e 100644 --- a/115_distinct_subsequences/Makefile +++ b/115_distinct_subsequences/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test distinct_subseq.c + gcc -O1 -o test distinct_subseq.c diff --git a/116_populating_next_right_pointers_in_each_node/Makefile b/116_populating_next_right_pointers_in_each_node/Makefile index 3cc79a6..d856c85 100644 --- a/116_populating_next_right_pointers_in_each_node/Makefile +++ b/116_populating_next_right_pointers_in_each_node/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test connect.c + gcc -O1 -o test connect.c diff --git a/117_populating_next_right_pointers_in_each_node_ii/Makefile b/117_populating_next_right_pointers_in_each_node_ii/Makefile index 3cc79a6..d856c85 100644 --- a/117_populating_next_right_pointers_in_each_node_ii/Makefile +++ b/117_populating_next_right_pointers_in_each_node_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test connect.c + gcc -O1 -o test connect.c diff --git a/118_pascal_triangle/Makefile b/118_pascal_triangle/Makefile index 41a60e8..309f7fe 100644 --- a/118_pascal_triangle/Makefile +++ b/118_pascal_triangle/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test pascal_triangle.c + gcc -O1 -o test pascal_triangle.c diff --git a/119_pascal_triangle_ii/Makefile b/119_pascal_triangle_ii/Makefile index 41a60e8..309f7fe 100644 --- a/119_pascal_triangle_ii/Makefile +++ b/119_pascal_triangle_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test pascal_triangle.c + gcc -O1 -o test pascal_triangle.c diff --git a/120_triangle/Makefile b/120_triangle/Makefile index 44d928f..7b0c42e 100644 --- a/120_triangle/Makefile +++ b/120_triangle/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test triangle.c + gcc -O1 -o test triangle.c diff --git a/121_best_time_to_buy_and_sell_stock/Makefile b/121_best_time_to_buy_and_sell_stock/Makefile index c638fbb..5d7d4bd 100644 --- a/121_best_time_to_buy_and_sell_stock/Makefile +++ b/121_best_time_to_buy_and_sell_stock/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test stock.c + gcc -O1 -o test stock.c diff --git a/122_best_time_to_buy_and_sell_stock_ii/Makefile b/122_best_time_to_buy_and_sell_stock_ii/Makefile index c638fbb..5d7d4bd 100644 --- a/122_best_time_to_buy_and_sell_stock_ii/Makefile +++ b/122_best_time_to_buy_and_sell_stock_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test stock.c + gcc -O1 -o test stock.c diff --git a/123_best_time_to_buy_and_sell_stock_iii/Makefile b/123_best_time_to_buy_and_sell_stock_iii/Makefile index c638fbb..5d7d4bd 100644 --- a/123_best_time_to_buy_and_sell_stock_iii/Makefile +++ b/123_best_time_to_buy_and_sell_stock_iii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test stock.c + gcc -O1 -o test stock.c diff --git a/124_binary_tree_maximum_path_sum/Makefile b/124_binary_tree_maximum_path_sum/Makefile index 2f04423..e973351 100644 --- a/124_binary_tree_maximum_path_sum/Makefile +++ b/124_binary_tree_maximum_path_sum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_max_path.c + gcc -O1 -o test bst_max_path.c diff --git a/125_valid_palindrome/Makefile b/125_valid_palindrome/Makefile index fc2acce..a28cb86 100644 --- a/125_valid_palindrome/Makefile +++ b/125_valid_palindrome/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test valid_palindrome.c + gcc -O1 -o test valid_palindrome.c diff --git a/126_word_ladder_ii/Makefile b/126_word_ladder_ii/Makefile index eb51704..0485a4b 100644 --- a/126_word_ladder_ii/Makefile +++ b/126_word_ladder_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test word_ladder.c + gcc -O1 -o test word_ladder.c diff --git a/127_word_ladder/Makefile b/127_word_ladder/Makefile index eb51704..0485a4b 100644 --- a/127_word_ladder/Makefile +++ b/127_word_ladder/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test word_ladder.c + gcc -O1 -o test word_ladder.c diff --git a/128_longest_consecutive_sequence/Makefile b/128_longest_consecutive_sequence/Makefile index 7b3d506..687920c 100644 --- a/128_longest_consecutive_sequence/Makefile +++ b/128_longest_consecutive_sequence/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test consec_seq.c + gcc -O1 -o test consec_seq.c diff --git a/129_sum_root_to_leaf_numbers/Makefile b/129_sum_root_to_leaf_numbers/Makefile index 013b36e..3b4d94c 100644 --- a/129_sum_root_to_leaf_numbers/Makefile +++ b/129_sum_root_to_leaf_numbers/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test sum_tree.c + gcc -O1 -o test sum_tree.c diff --git a/130_surrounded_regions/Makefile b/130_surrounded_regions/Makefile index 0743ff4..9cc7f01 100644 --- a/130_surrounded_regions/Makefile +++ b/130_surrounded_regions/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test surrounded_regions.c + gcc -O1 -o test surrounded_regions.c diff --git a/131_palindrome_patitioning/Makefile b/131_palindrome_patitioning/Makefile index 3179327..34cbc1a 100644 --- a/131_palindrome_patitioning/Makefile +++ b/131_palindrome_patitioning/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test palindrome_partition.c + gcc -O1 -o test palindrome_partition.c diff --git a/132_palindrome_patitioning_ii/Makefile b/132_palindrome_patitioning_ii/Makefile index 3179327..34cbc1a 100644 --- a/132_palindrome_patitioning_ii/Makefile +++ b/132_palindrome_patitioning_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test palindrome_partition.c + gcc -O1 -o test palindrome_partition.c diff --git a/133_clone_graph/Makefile b/133_clone_graph/Makefile index 4e700dc..02b8339 100644 --- a/133_clone_graph/Makefile +++ b/133_clone_graph/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test clone_graph.c + gcc -O1 -o test clone_graph.c diff --git a/134_gas_station/Makefile b/134_gas_station/Makefile index f2ca4c0..868fcf3 100644 --- a/134_gas_station/Makefile +++ b/134_gas_station/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test gas_station.c + gcc -O1 -o test gas_station.c diff --git a/135_candy/Makefile b/135_candy/Makefile index 36411f5..44aae97 100644 --- a/135_candy/Makefile +++ b/135_candy/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test candy.c + gcc -O1 -o test candy.c diff --git a/136_single_number/Makefile b/136_single_number/Makefile index f992802..ba4bb3e 100644 --- a/136_single_number/Makefile +++ b/136_single_number/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test single_number.c + gcc -O1 -o test single_number.c diff --git a/137_single_number_ii/Makefile b/137_single_number_ii/Makefile index f992802..ba4bb3e 100644 --- a/137_single_number_ii/Makefile +++ b/137_single_number_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test single_number.c + gcc -O1 -o test single_number.c diff --git a/138_copy_list_with_random_pointer/Makefile b/138_copy_list_with_random_pointer/Makefile index 87e8a90..7f02416 100644 --- a/138_copy_list_with_random_pointer/Makefile +++ b/138_copy_list_with_random_pointer/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test copy_list.c + gcc -O1 -o test copy_list.c diff --git a/139_word_break/Makefile b/139_word_break/Makefile index a9604bc..0763077 100644 --- a/139_word_break/Makefile +++ b/139_word_break/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test word_break.c + gcc -O1 -o test word_break.c diff --git a/140_word_break_ii/Makefile b/140_word_break_ii/Makefile index a9604bc..0763077 100644 --- a/140_word_break_ii/Makefile +++ b/140_word_break_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test word_break.c + gcc -O1 -o test word_break.c diff --git a/141_linked_list_cycle/Makefile b/141_linked_list_cycle/Makefile index cf8bd0d..695aff0 100644 --- a/141_linked_list_cycle/Makefile +++ b/141_linked_list_cycle/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test list_cycle.c + gcc -O1 -o test list_cycle.c diff --git a/142_linked_list_cycle_ii/Makefile b/142_linked_list_cycle_ii/Makefile index cf8bd0d..695aff0 100644 --- a/142_linked_list_cycle_ii/Makefile +++ b/142_linked_list_cycle_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test list_cycle.c + gcc -O1 -o test list_cycle.c diff --git a/143_reorder_list/Makefile b/143_reorder_list/Makefile index c6ca20b..c4009ef 100644 --- a/143_reorder_list/Makefile +++ b/143_reorder_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test reorder_list.c + gcc -O1 -o test reorder_list.c diff --git a/144_binary_tree_preorder_traversal/Makefile b/144_binary_tree_preorder_traversal/Makefile index f08c087..0362c20 100644 --- a/144_binary_tree_preorder_traversal/Makefile +++ b/144_binary_tree_preorder_traversal/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_preorder.c + gcc -O1 -o test bst_preorder.c diff --git a/145_binary_tree_postorder_traversal/Makefile b/145_binary_tree_postorder_traversal/Makefile index c35a74f..1a34f47 100644 --- a/145_binary_tree_postorder_traversal/Makefile +++ b/145_binary_tree_postorder_traversal/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_postorder.c + gcc -O1 -o test bst_postorder.c diff --git a/146_lru_cache/Makefile b/146_lru_cache/Makefile index b64babf..30aa1f2 100644 --- a/146_lru_cache/Makefile +++ b/146_lru_cache/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test lru_cache.c + gcc -O1 -o test lru_cache.c diff --git a/147_insertion_sort_list/Makefile b/147_insertion_sort_list/Makefile index 576b707..f0c8610 100644 --- a/147_insertion_sort_list/Makefile +++ b/147_insertion_sort_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test insert_sort_list.c + gcc -O1 -o test insert_sort_list.c diff --git a/148_sort_list/Makefile b/148_sort_list/Makefile index c8c671c..0f4bed1 100644 --- a/148_sort_list/Makefile +++ b/148_sort_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test sort_list.c + gcc -O1 -o test sort_list.c diff --git a/149_max_points_on_a_line/Makefile b/149_max_points_on_a_line/Makefile index b3597be..fb4da58 100644 --- a/149_max_points_on_a_line/Makefile +++ b/149_max_points_on_a_line/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test points_on_line.c + gcc -O1 -o test points_on_line.c diff --git a/150_evaluate_reverse_polish_notation/Makefile b/150_evaluate_reverse_polish_notation/Makefile index 173a84c..597b8ab 100644 --- a/150_evaluate_reverse_polish_notation/Makefile +++ b/150_evaluate_reverse_polish_notation/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test eval_rpn.c + gcc -O1 -o test eval_rpn.c diff --git a/151_reverse_words_in_a_string/Makefile b/151_reverse_words_in_a_string/Makefile index 60a46ef..6d216b5 100644 --- a/151_reverse_words_in_a_string/Makefile +++ b/151_reverse_words_in_a_string/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test reverse.c + gcc -O1 -o test reverse.c diff --git a/152_maximum_product_subarray/Makefile b/152_maximum_product_subarray/Makefile index 59aa57a..b216c6f 100644 --- a/152_maximum_product_subarray/Makefile +++ b/152_maximum_product_subarray/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test subarray.c + gcc -O1 -o test subarray.c diff --git a/153_find_minimum_in_rotated_sorted_array/Makefile b/153_find_minimum_in_rotated_sorted_array/Makefile index b6eb212..5cd0451 100644 --- a/153_find_minimum_in_rotated_sorted_array/Makefile +++ b/153_find_minimum_in_rotated_sorted_array/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test minimum.c + gcc -O1 -o test minimum.c diff --git a/154_find_minimum_in_rotated_sorted_array_ii/Makefile b/154_find_minimum_in_rotated_sorted_array_ii/Makefile index b6eb212..5cd0451 100644 --- a/154_find_minimum_in_rotated_sorted_array_ii/Makefile +++ b/154_find_minimum_in_rotated_sorted_array_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test minimum.c + gcc -O1 -o test minimum.c diff --git a/155_min_stack/Makefile b/155_min_stack/Makefile index b02d414..5dd72fe 100644 --- a/155_min_stack/Makefile +++ b/155_min_stack/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test stack.c + gcc -O1 -o test stack.c diff --git a/160_intersection_of_two_linked_list/Makefile b/160_intersection_of_two_linked_list/Makefile index 8a7201e..e3e5099 100644 --- a/160_intersection_of_two_linked_list/Makefile +++ b/160_intersection_of_two_linked_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test intersection.c + gcc -O1 -o test intersection.c diff --git a/162_find_peak_element/Makefile b/162_find_peak_element/Makefile index 3e53c7d..2e3077e 100644 --- a/162_find_peak_element/Makefile +++ b/162_find_peak_element/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test peak.c + gcc -O1 -o test peak.c diff --git a/164_maximum_gap/Makefile b/164_maximum_gap/Makefile index e011d5f..62fb524 100644 --- a/164_maximum_gap/Makefile +++ b/164_maximum_gap/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test max_gap.c + gcc -O1 -o test max_gap.c diff --git a/165_compare_version_numbers/Makefile b/165_compare_version_numbers/Makefile index a373113..faf78bf 100644 --- a/165_compare_version_numbers/Makefile +++ b/165_compare_version_numbers/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test version.c + gcc -O1 -o test version.c diff --git a/166_fraction_to_recurring_decimal/Makefile b/166_fraction_to_recurring_decimal/Makefile index 75c36fa..432c76c 100644 --- a/166_fraction_to_recurring_decimal/Makefile +++ b/166_fraction_to_recurring_decimal/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test fraction.c + gcc -O1 -o test fraction.c diff --git a/167_two_sum_ii/Makefile b/167_two_sum_ii/Makefile index ffb6456..e896cb5 100644 --- a/167_two_sum_ii/Makefile +++ b/167_two_sum_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test two_sum.c + gcc -O1 -o test two_sum.c diff --git a/168_excel_sheet_column_title/Makefile b/168_excel_sheet_column_title/Makefile index fd0a780..7a8047f 100644 --- a/168_excel_sheet_column_title/Makefile +++ b/168_excel_sheet_column_title/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test sheet_column.c + gcc -O1 -o test sheet_column.c diff --git a/169_majority_element/Makefile b/169_majority_element/Makefile index 9741c71..84ca762 100644 --- a/169_majority_element/Makefile +++ b/169_majority_element/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test majority.c + gcc -O1 -o test majority.c diff --git a/171_excel_sheet_column_number/Makefile b/171_excel_sheet_column_number/Makefile index fd0a780..7a8047f 100644 --- a/171_excel_sheet_column_number/Makefile +++ b/171_excel_sheet_column_number/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test sheet_column.c + gcc -O1 -o test sheet_column.c diff --git a/172_factorial_trailing_zeros/Makefile b/172_factorial_trailing_zeros/Makefile index 24a32d9..54e68c3 100644 --- a/172_factorial_trailing_zeros/Makefile +++ b/172_factorial_trailing_zeros/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test zeroes.c + gcc -O1 -o test zeroes.c diff --git a/173_binary_search_tree_iterator/Makefile b/173_binary_search_tree_iterator/Makefile index 9a51897..96cca66 100644 --- a/173_binary_search_tree_iterator/Makefile +++ b/173_binary_search_tree_iterator/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_iter.c + gcc -O1 -o test bst_iter.c diff --git a/174_dungeon_game/Makefile b/174_dungeon_game/Makefile index d36477a..81bc0ed 100644 --- a/174_dungeon_game/Makefile +++ b/174_dungeon_game/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test dungeon.c + gcc -O1 -o test dungeon.c diff --git a/179_largest_number/Makefile b/179_largest_number/Makefile index a78cc73..0d8eafc 100644 --- a/179_largest_number/Makefile +++ b/179_largest_number/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test largest_number.c + gcc -O1 -o test largest_number.c diff --git a/188_best_time_to_buy_and_sell_stock_iv/Makefile b/188_best_time_to_buy_and_sell_stock_iv/Makefile index c638fbb..5d7d4bd 100644 --- a/188_best_time_to_buy_and_sell_stock_iv/Makefile +++ b/188_best_time_to_buy_and_sell_stock_iv/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test stock.c + gcc -O1 -o test stock.c diff --git a/189_rotate_array/Makefile b/189_rotate_array/Makefile index 8a313f9..adec477 100644 --- a/189_rotate_array/Makefile +++ b/189_rotate_array/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rotate_array.c + gcc -O1 -o test rotate_array.c diff --git a/190_reverse_bits/Makefile b/190_reverse_bits/Makefile index d693eb9..ef041ad 100644 --- a/190_reverse_bits/Makefile +++ b/190_reverse_bits/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test reverse_bits.c + gcc -O1 -o test reverse_bits.c diff --git a/191_number_of_one_bits/Makefile b/191_number_of_one_bits/Makefile index c73d03b..fd6ea08 100644 --- a/191_number_of_one_bits/Makefile +++ b/191_number_of_one_bits/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test hamming_weight.c + gcc -O1 -o test hamming_weight.c diff --git a/198_house_robber/Makefile b/198_house_robber/Makefile index b7bb446..16f41d2 100644 --- a/198_house_robber/Makefile +++ b/198_house_robber/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test robber.c + gcc -O1 -o test robber.c diff --git a/199_binary_tree_right_side_view/Makefile b/199_binary_tree_right_side_view/Makefile index 0304665..316f349 100644 --- a/199_binary_tree_right_side_view/Makefile +++ b/199_binary_tree_right_side_view/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_right.c + gcc -O1 -o test bst_right.c diff --git a/200_number_of_islands/Makefile b/200_number_of_islands/Makefile index 05ad586..aa9ae7a 100644 --- a/200_number_of_islands/Makefile +++ b/200_number_of_islands/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test islands.c + gcc -O1 -o test islands.c diff --git a/201_bitwise_and_of_numbers_range/Makefile b/201_bitwise_and_of_numbers_range/Makefile index cc9cd33..7f8c06c 100644 --- a/201_bitwise_and_of_numbers_range/Makefile +++ b/201_bitwise_and_of_numbers_range/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test and.c + gcc -O1 -o test and.c diff --git a/202_happy_number/Makefile b/202_happy_number/Makefile index 7b43a8a..c4394cc 100644 --- a/202_happy_number/Makefile +++ b/202_happy_number/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test happy_number.c + gcc -O1 -o test happy_number.c diff --git a/203_remove_linked_list_element/Makefile b/203_remove_linked_list_element/Makefile index 210f162..8c8bea3 100644 --- a/203_remove_linked_list_element/Makefile +++ b/203_remove_linked_list_element/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test rm_elem.c + gcc -O1 -o test rm_elem.c diff --git a/204_count_primes/Makefile b/204_count_primes/Makefile index 0937319..db7f392 100644 --- a/204_count_primes/Makefile +++ b/204_count_primes/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test count_primes.c + gcc -O1 -o test count_primes.c diff --git a/205_isomorphic_strings/Makefile b/205_isomorphic_strings/Makefile index ef9f896..e2eff8d 100644 --- a/205_isomorphic_strings/Makefile +++ b/205_isomorphic_strings/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test isomorphic_strings.c + gcc -O1 -o test isomorphic_strings.c diff --git a/206_reverse_linked_list/Makefile b/206_reverse_linked_list/Makefile index d480ecf..efe146e 100644 --- a/206_reverse_linked_list/Makefile +++ b/206_reverse_linked_list/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test reverse_list.c + gcc -O1 -o test reverse_list.c diff --git a/207_course_schedule/Makefile b/207_course_schedule/Makefile index 0657996..213bc14 100644 --- a/207_course_schedule/Makefile +++ b/207_course_schedule/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test course_schedule.c + gcc -O1 -o test course_schedule.c diff --git a/208_implement_trie/Makefile b/208_implement_trie/Makefile index 45a3810..81a10e7 100644 --- a/208_implement_trie/Makefile +++ b/208_implement_trie/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test trie.c + gcc -O1 -o test trie.c diff --git a/209_minimum_size_subarray_sum/Makefile b/209_minimum_size_subarray_sum/Makefile index 4584902..bac59d5 100644 --- a/209_minimum_size_subarray_sum/Makefile +++ b/209_minimum_size_subarray_sum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test mini_size.c + gcc -O1 -o test mini_size.c diff --git a/210_course_schedule_ii/Makefile b/210_course_schedule_ii/Makefile index 0657996..213bc14 100644 --- a/210_course_schedule_ii/Makefile +++ b/210_course_schedule_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test course_schedule.c + gcc -O1 -o test course_schedule.c diff --git a/211_add_and_search_word/Makefile b/211_add_and_search_word/Makefile index d5b19d5..5f82d6f 100644 --- a/211_add_and_search_word/Makefile +++ b/211_add_and_search_word/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test word_dict.c + gcc -O1 -o test word_dict.c diff --git a/212_word_search_ii/Makefile b/212_word_search_ii/Makefile index 99bef24..2eab6c6 100644 --- a/212_word_search_ii/Makefile +++ b/212_word_search_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test word_search.c + gcc -O1 -o test word_search.c diff --git a/213_house_robber_ii/Makefile b/213_house_robber_ii/Makefile index b7bb446..16f41d2 100644 --- a/213_house_robber_ii/Makefile +++ b/213_house_robber_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test robber.c + gcc -O1 -o test robber.c diff --git a/214_shortest_palindrome/Makefile b/214_shortest_palindrome/Makefile index 7e3dc1a..3e05ad5 100644 --- a/214_shortest_palindrome/Makefile +++ b/214_shortest_palindrome/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test shortest_palindrome.c + gcc -O1 -o test shortest_palindrome.c diff --git a/215_kth_largest_element_in_an_array/Makefile b/215_kth_largest_element_in_an_array/Makefile index 9d8632c..4caf991 100644 --- a/215_kth_largest_element_in_an_array/Makefile +++ b/215_kth_largest_element_in_an_array/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test kth_elem.c + gcc -O1 -o test kth_elem.c diff --git a/216_combination_sum_iii/Makefile b/216_combination_sum_iii/Makefile index e5462fa..dafaf31 100644 --- a/216_combination_sum_iii/Makefile +++ b/216_combination_sum_iii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test combination_sum.c + gcc -O1 -o test combination_sum.c diff --git a/221_maximal_square/Makefile b/221_maximal_square/Makefile index 635083b..f7a10f7 100644 --- a/221_maximal_square/Makefile +++ b/221_maximal_square/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test maximal_square.c + gcc -O1 -o test maximal_square.c diff --git a/224_basic_calculator/Makefile b/224_basic_calculator/Makefile index 2446711..b12a1c8 100644 --- a/224_basic_calculator/Makefile +++ b/224_basic_calculator/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test calculator.c + gcc -O1 -o test calculator.c diff --git a/226_invert_binary_tree/Makefile b/226_invert_binary_tree/Makefile index 1a8a9fe..842878d 100644 --- a/226_invert_binary_tree/Makefile +++ b/226_invert_binary_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test invert_binary_tree.c + gcc -O1 -o test invert_binary_tree.c diff --git a/227_basic_calculator_ii/Makefile b/227_basic_calculator_ii/Makefile index 2446711..b12a1c8 100644 --- a/227_basic_calculator_ii/Makefile +++ b/227_basic_calculator_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test calculator.c + gcc -O1 -o test calculator.c diff --git a/229_majority_element_ii/Makefile b/229_majority_element_ii/Makefile index 9741c71..84ca762 100644 --- a/229_majority_element_ii/Makefile +++ b/229_majority_element_ii/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test majority.c + gcc -O1 -o test majority.c diff --git a/230_kth_smallest_element_in_a_bst/Makefile b/230_kth_smallest_element_in_a_bst/Makefile index 755b6b9..7fe9d06 100644 --- a/230_kth_smallest_element_in_a_bst/Makefile +++ b/230_kth_smallest_element_in_a_bst/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test kth_bst.c + gcc -O1 -o test kth_bst.c diff --git a/235_lowest_common_ancestor_of_a_binary_search_tree/Makefile b/235_lowest_common_ancestor_of_a_binary_search_tree/Makefile index 32b0df5..1cfab66 100644 --- a/235_lowest_common_ancestor_of_a_binary_search_tree/Makefile +++ b/235_lowest_common_ancestor_of_a_binary_search_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_lca.c + gcc -O1 -o test bst_lca.c diff --git a/236_lowest_common_ancestor_of_a_binary_tree/Makefile b/236_lowest_common_ancestor_of_a_binary_tree/Makefile index 32b0df5..1cfab66 100644 --- a/236_lowest_common_ancestor_of_a_binary_tree/Makefile +++ b/236_lowest_common_ancestor_of_a_binary_tree/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test bst_lca.c + gcc -O1 -o test bst_lca.c diff --git a/239_sliding_window_maximum/Makefile b/239_sliding_window_maximum/Makefile index 3ef9a2f..59c5a61 100644 --- a/239_sliding_window_maximum/Makefile +++ b/239_sliding_window_maximum/Makefile @@ -1,2 +1,2 @@ all: - gcc -O2 -o test slide_window.c + gcc -O1 -o test slide_window.c From 85243ba2f6139c265f5c47c96932043711e697dd Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 17 Jul 2020 12:18:01 +0800 Subject: [PATCH 077/211] Refine Signed-off-by: begeekmyfriend --- 002_add_two_numbers/add_two_numbers.c | 3 +-- .../longest_substring_without_repeat.c | 4 +-- 007_reverse_integer/reverse_integer.c | 18 +++++++------ 008_atoi/atoi.c | 25 +++++++++++++++---- 009_palindrome_number/palindrome_number.c | 17 ++++++++++--- 5 files changed, 47 insertions(+), 20 deletions(-) diff --git a/002_add_two_numbers/add_two_numbers.c b/002_add_two_numbers/add_two_numbers.c index a85ba71..acc3ebb 100644 --- a/002_add_two_numbers/add_two_numbers.c +++ b/002_add_two_numbers/add_two_numbers.c @@ -17,7 +17,6 @@ static struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) dummy.next = p; while (l1 != NULL || l2 != NULL) { int sum = 0; - int last_carry = carry; if (l1 != NULL) { sum += l1->val; @@ -34,7 +33,7 @@ static struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) l2 = l2->next; } - sum += last_carry; + sum += carry; carry = sum / 10; p->val = sum % 10; prev = p; diff --git a/003_longest_substring_without_repeat/longest_substring_without_repeat.c b/003_longest_substring_without_repeat/longest_substring_without_repeat.c index 2f067ce..701efa4 100644 --- a/003_longest_substring_without_repeat/longest_substring_without_repeat.c +++ b/003_longest_substring_without_repeat/longest_substring_without_repeat.c @@ -15,10 +15,10 @@ static int lengthOfLongestSubstring(char *s) len++; } else { if (index - offset[*s] > len) { - /* not include in substring, go on increasing */ + /* not included in sliding window, go on increasing */ len++; } else { - /* count from scratch */ + /* repetition in sliding window, count from scratch */ len = index - offset[*s]; } } diff --git a/007_reverse_integer/reverse_integer.c b/007_reverse_integer/reverse_integer.c index 07a3b69..a319c5b 100644 --- a/007_reverse_integer/reverse_integer.c +++ b/007_reverse_integer/reverse_integer.c @@ -2,20 +2,24 @@ #include #include + static int reverse(int x) { - int y = 0; + int n = 0; while (x != 0) { - int n = x % 10; - // Checking the over/underflow. - // Actually, it should be y>(INT_MAX-n)/10, but n/10 is 0, so omit it. - if (y > INT_MAX / 10 || y < INT_MIN / 10) { + int r = x % 10; + /* Checking the over/underflow. */ + if (n > INT_MAX / 10 || (n == INT_MAX / 10 && r > 7)) { + return 0; + } + if (n < INT_MIN / 10 || (n == INT_MIN / 10 && r < -8)) { return 0; } - y = y * 10 + n; + + n = n * 10 + r; x /= 10; } - return y; + return n; } #define TEST(n, e) printf("%12d => %-12d %s!\n", n, reverse(n), e == reverse(n)?"passed":"failed") diff --git a/008_atoi/atoi.c b/008_atoi/atoi.c index 3a3660f..c57769b 100644 --- a/008_atoi/atoi.c +++ b/008_atoi/atoi.c @@ -1,16 +1,35 @@ +#include #include #include #include + static int myAtoi(char* str) { char *s; - int n = 0, sign = 0; + long n = 0; + int sign = 0; while (*str == ' ' || *str == '\t') { str++; } + if (*str == '-') { + if (isdigit(*++str)) { + sign = 1; + } else { + return 0; + } + } + + if (*str == '+') { + if (isdigit(*++str)) { + sign = 0; + } else { + return 0; + } + } + for (s = str; *s != '\0'; s++) { if (isdigit(*s)) { int d = *s - '0'; @@ -26,10 +45,6 @@ static int myAtoi(char* str) } } n = n * 10 + d; - } else if (*s == '-' && isdigit(*(s + 1)) && (n == 0)) { - sign = 1; - } else if (*s == '+' && isdigit(*(s + 1)) && (n == 0)) { - sign = 0; } else { break; } diff --git a/009_palindrome_number/palindrome_number.c b/009_palindrome_number/palindrome_number.c index 0c59619..c870b2b 100644 --- a/009_palindrome_number/palindrome_number.c +++ b/009_palindrome_number/palindrome_number.c @@ -2,14 +2,23 @@ #include #include + static int reverse(int x) { - int y = 0; - while (x) { - y = y * 10 + x % 10; + int n = 0; + while (x != 0) { + int r = x % 10; + /* Checking the over/underflow. */ + if (n > INT_MAX / 10 || (n == INT_MAX / 10 && r > 7)) { + return 0; + } + if (n < INT_MIN / 10 || (n == INT_MIN / 10 && r < -8)) { + return 0; + } + n = n * 10 + r; x /= 10; } - return y; + return n; } static bool isPalindrome(int x) From 0b2f18d27aaf205515e3a546a6a6cc4f96718d47 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 19 Jul 2020 23:51:57 +0800 Subject: [PATCH 078/211] Refine Signed-off-by: begeekmyfriend --- .../regular_expression.c | 27 +++++++------------ 012_roman_numeral/roman_numeral.c | 6 ++--- 013_roman_to_integer/roman_to_integer.c | 13 ++++----- 014_longest_common_prefix/common_prefix.c | 14 +++++++--- 015_three_sum/three_sum.c | 2 +- .../letter_combinations.c | 27 +++---------------- .../remove_end.c | 5 +++- 7 files changed, 37 insertions(+), 57 deletions(-) diff --git a/010_regular_expression_matching/regular_expression.c b/010_regular_expression_matching/regular_expression.c index ccc78e5..c736041 100644 --- a/010_regular_expression_matching/regular_expression.c +++ b/010_regular_expression_matching/regular_expression.c @@ -1,30 +1,21 @@ #include #include #include -#include -static bool isMatch(char* s, char* p) + +static bool isMatch(char *s, char *p) { if (*p == '\0') { return *s == '\0'; } - /* p's length 1 is special case */ - if (*(p + 1) == '\0' || *(p + 1) != '*') { - if (*s == '\0' || ( *p != '.' && *s != *p)) { - return false; - } else { - return isMatch(s + 1, p + 1); - } - } - int len = strlen(s); - int i = -1; - while (i < len && (i < 0 || *p == '.' || *p == *(s + i))) { - if (isMatch(s + i + 1, p + 2)) { - return true; - } - i++; + + bool first_match = (*s != '\0') && (*s == *p || *p == '.'); + + if (p[1] == '*') { + return isMatch(s, p + 2) || (first_match && isMatch(s + 1, p)); + } else { + return first_match && isMatch(s + 1, p + 1); } - return false; } int main(int argc, char **argv) diff --git a/012_roman_numeral/roman_numeral.c b/012_roman_numeral/roman_numeral.c index f3ad517..4bdb8ec 100644 --- a/012_roman_numeral/roman_numeral.c +++ b/012_roman_numeral/roman_numeral.c @@ -60,18 +60,16 @@ static void num2char(char **num, int bit, int n) *num = p; } -static char roman_numeral[64]; +static char roman_numeral[64] = { '\0' }; static char *intToRoman(int num) { + int i; char *p = &roman_numeral[0]; int thousand_bit = num / 1000; int hundred_bit = (num % 1000) / 100; int ten_bit = (num % 100) / 10; int one_bit = num % 10; - int i; - - memset(roman_numeral, 0, sizeof(roman_numeral)); if (thousand_bit > 0) { if (thousand_bit < 4) { diff --git a/013_roman_to_integer/roman_to_integer.c b/013_roman_to_integer/roman_to_integer.c index 4469ae8..3432213 100644 --- a/013_roman_to_integer/roman_to_integer.c +++ b/013_roman_to_integer/roman_to_integer.c @@ -19,20 +19,21 @@ static int roman_to_integer(char c) case 'M': return 1000; default: - return; + return 0; } } int romanToInt (char *s) { - int i, result = roman_to_integer(s[0]); + int i, curr = roman_to_integer(s[0]); + int result = curr; for (i = 1; s[i] != '\0'; i++) { - int prev = roman_to_integer(s[i - 1]); - int curr = roman_to_integer(s[i]); - //if left #include + static char* longestCommonPrefix(char** strs, int strsSize) { + if (strsSize == 0) { + return ""; + } + int i, count = 0; char *result = malloc(1000); - while (strsSize > 0) { + while (strs[0][count] != '\0') { char c = strs[0][count]; for (i = 1; i < strsSize; i++) { - if (c != strs[i][count]) break; + if (c != strs[i][count]) { + break; + } } - if (i == strsSize && c != '\0') { + + if (i == strsSize) { result[count++] = c; } else { break; diff --git a/015_three_sum/three_sum.c b/015_three_sum/three_sum.c index 17ff41e..31bf395 100644 --- a/015_three_sum/three_sum.c +++ b/015_three_sum/three_sum.c @@ -41,7 +41,7 @@ static int** threeSum(int* nums, int numsSize, int* returnSize) *returnSize = 0; int i, j, capacity = 50000; int **results = malloc(capacity * sizeof(int *)); - for (i = 0; i < numsSize; i++) { + for (i = 0; i < numsSize - 2; i++) { if (i == 0 || i > 0 && nums[i] != nums[i - 1]) { two_sum(nums, i + 1, numsSize - 1, -nums[i], results, returnSize); } diff --git a/017_letter_combinations_of_a_phone_number/letter_combinations.c b/017_letter_combinations_of_a_phone_number/letter_combinations.c index 7a1382b..2104923 100644 --- a/017_letter_combinations_of_a_phone_number/letter_combinations.c +++ b/017_letter_combinations_of_a_phone_number/letter_combinations.c @@ -8,34 +8,13 @@ **/ static char** letterCombinations(char* digits, int* returnSize) { - char *letter_matrix[10]; - letter_matrix[0] = ""; - letter_matrix[1] = " "; - letter_matrix[2] = "abc"; - letter_matrix[3] = "def"; - letter_matrix[4] = "ghi"; - letter_matrix[5] = "jkl"; - letter_matrix[6] = "mno"; - letter_matrix[7] = "pqrs"; - letter_matrix[8] = "tuv"; - letter_matrix[9] = "wxyz"; - - int letter_length[10]; - letter_length[0] = 0; - letter_length[1] = 1; - letter_length[2] = 3; - letter_length[3] = 3; - letter_length[4] = 3; - letter_length[5] = 3; - letter_length[6] = 3; - letter_length[7] = 4; - letter_length[8] = 3; - letter_length[9] = 4; - int i, j, k; int empty = 1; int count = 1; int digit_len = strlen(digits); + char *letter_matrix[10] = {"", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz", }; + int letter_length[10] = {0, 1, 3, 3, 3, 3, 3, 4, 3, 4, }; + for (i = 0; i < digit_len; i++) { int index = digits[i] - '0'; if (letter_length[index] > 0) { diff --git a/019_remove_nth_node_from_end_of_list/remove_end.c b/019_remove_nth_node_from_end_of_list/remove_end.c index ce0743d..d9242db 100644 --- a/019_remove_nth_node_from_end_of_list/remove_end.c +++ b/019_remove_nth_node_from_end_of_list/remove_end.c @@ -8,7 +8,9 @@ struct ListNode { static struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { - if (n < 1) return NULL; + if (n == 0) { + return NULL; + } struct ListNode *p, *prev, dummy; dummy.next = head; @@ -27,6 +29,7 @@ static struct ListNode* removeNthFromEnd(struct ListNode* head, int n) if (tmp == head) { head = tmp->next; } + return head; } From 022a196e2e2fc234ee7b117b45addeca124a1e17 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 20 Jul 2020 21:12:48 +0800 Subject: [PATCH 079/211] Refine Signed-off-by: begeekmyfriend --- .../rm_dup.c | 10 ++--- 029_divide_two_integers/divide.c | 42 ++++++++++--------- 2 files changed, 27 insertions(+), 25 deletions(-) diff --git a/026_remove_duplicates_from_sorted_array/rm_dup.c b/026_remove_duplicates_from_sorted_array/rm_dup.c index 092b457..95b2e0b 100644 --- a/026_remove_duplicates_from_sorted_array/rm_dup.c +++ b/026_remove_duplicates_from_sorted_array/rm_dup.c @@ -7,13 +7,11 @@ static int removeDuplicates(int* nums, int numsSize) return numsSize; } - int i = 0, j, count = 1; - while (i < numsSize) { - for (j = i + 1; j < numsSize && nums[i] == nums[j]; j++) {} - if (j < numsSize) { - nums[count++] = nums[j]; + int i, count = 1; + for (i = 1; i < numsSize; i++) { + if (nums[i - 1] != nums[i]) { + nums[count++] = nums[i]; } - i = j; } return count; diff --git a/029_divide_two_integers/divide.c b/029_divide_two_integers/divide.c index 9c0250d..081ab72 100644 --- a/029_divide_two_integers/divide.c +++ b/029_divide_two_integers/divide.c @@ -4,34 +4,38 @@ int divide(int dividend, int divisor) { - int sign = (float) dividend / divisor > 0 ? 1 : -1; - unsigned int dvd = dividend > 0 ? dividend : -dividend; - unsigned int dvs = divisor > 0 ? divisor : -divisor; - unsigned int bit_num[33]; - unsigned int i = 0; - long long d = dvs; + int signal = 1; + unsigned int dvd = dividend; + if (dividend < 0) { + signal *= -1; + dvd = ~dvd + 1; + } + + unsigned int dvs = divisor; + if (divisor < 0) { + signal *= -1; + dvs = ~dvs + 1; + } - bit_num[i] = d; - while (d <= dvd) { - bit_num[++i] = d = d << 1; + int shift = 0; + while (dvd > dvs << shift) { + shift++; } - i--; - unsigned int result = 0; + unsigned int res = 0; while (dvd >= dvs) { - if (dvd >= bit_num[i]) { - dvd -= bit_num[i]; - result += (1< INT_MAX && sign > 0) { + if (signal == 1 && res >= INT_MAX) { return INT_MAX; + } else { + return res * signal; } - return (int) result * sign; } int main(int argc, char **argv) From 7054a89faa64fada76803b6aaf0a78eb92167e63 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 20 Jul 2020 22:27:51 +0800 Subject: [PATCH 080/211] Fix Signed-off-by: begeekmyfriend --- 030_substring_with_concatenation_of_all_words/concatenation.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/030_substring_with_concatenation_of_all_words/concatenation.c b/030_substring_with_concatenation_of_all_words/concatenation.c index a2419df..aefda09 100644 --- a/030_substring_with_concatenation_of_all_words/concatenation.c +++ b/030_substring_with_concatenation_of_all_words/concatenation.c @@ -118,7 +118,7 @@ static int *findSubstring(char *s, char **words, int wordsSize, int *returnSize) char *word = malloc(len + 1); word[len] = '\0'; int *indexes = malloc(cap * sizeof(int)); - for (i = 0; s[i] != '\0'; i++) { + for (i = 0; s[i + len - 1] != '\0'; i++) { memcpy(word, s + i, len); indexes[i] = find(word, heads, hash_size); } From d8fb0eb0785c25f3d5fde3dca57c52ee7da59632 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 21 Jul 2020 23:24:59 +0800 Subject: [PATCH 081/211] Refine Signed-off-by: begeekmyfriend --- .../valid_parentheses.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/032_longest_valid_parentheses/valid_parentheses.c b/032_longest_valid_parentheses/valid_parentheses.c index 4b68595..83c9f15 100644 --- a/032_longest_valid_parentheses/valid_parentheses.c +++ b/032_longest_valid_parentheses/valid_parentheses.c @@ -2,6 +2,11 @@ #include +static inline int max(int a, int b) +{ + return a > b ? a : b; +} + static int longestValidParentheses(char* s) { int i, cap = 18000, invalid = -1; @@ -16,17 +21,14 @@ static int longestValidParentheses(char* s) } else { if (top > stack) { if (--top == stack) { - /* distancd of the latest ')' */ - len = i - invalid; + /* locate the remote ')' */ + max_len = max(i - invalid, max_len); } else { - /* distance of the remote '(' */ - len = i - *(top - 1); - } - if (len > max_len) { - max_len = len; + /* locate the remote '(' */ + max_len = max(i - *(top - 1), max_len); } } else { - /* record the index of last ')' but no push */ + /* record the index of the remote ')' and no push */ invalid = i; } } From 86322becc2b7a2ff6ec23dba85f48ee4bd643d06 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 22 Jul 2020 16:55:16 +0800 Subject: [PATCH 082/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 001_two_sum/two_sum.cc | 22 +++++ 002_add_two_numbers/add_two_numbers.cc | 55 +++++++++++++ .../longest_substring_without_repeat.cc | 30 +++++++ .../median_of_two_sorted_array.cc | 30 +++++++ 006_zigzag_conversion/zigzag_conversion.cc | 29 +++++++ 007_reverse_integer/reverse_integer.cc | 24 ++++++ 008_atoi/atoi.cc | 55 +++++++++++++ 009_palindrome_number/palindrome_number.cc | 35 ++++++++ .../regular_expression.cc | 30 +++++++ 011_container_with_most_water/container.cc | 21 +++++ 012_roman_numeral/roman_numeral.cc | 82 +++++++++++++++++++ 013_roman_to_integer/roman_to_integer.cc | 46 +++++++++++ 014_longest_common_prefix/common_prefix.cc | 23 ++++++ 015_three_sum/three_sum.cc | 34 ++++++++ 016_three_sum_closest/three_sum_closest.cc | 37 +++++++++ 018_four_sum/four_sum.cc | 44 ++++++++++ .../remove_end.cc | 42 ++++++++++ 020_valid_parentheses/valid_parentheses.cc | 41 ++++++++++ 021_merge_two_sorted_lists/merge_lists.cc | 41 ++++++++++ 022_generate_parathesis/parenthesis.cc | 33 ++++++++ 023_merge_k_sorted_lists/merge_lists.cc | 42 ++++++++++ 024_swap_nodes_in_pairs/swap_nodes.cc | 33 ++++++++ 025_reverse_nodes_in_k_group/reverse_nodes.cc | 41 ++++++++++ .../rm_dup.cc | 20 +++++ 027_remove_element/rm_elem.cc | 16 ++++ 028_implement_strstr/strstr.cc | 10 +++ 029_divide_two_integers/divide.cc | 42 ++++++++++ .../concatenation.cc | 34 ++++++++ 031_next_permutation/next_permutation.cc | 27 ++++++ .../valid_parentheses.cc | 32 ++++++++ .../rotated_array.cc | 31 +++++++ 034_search_for_a_range/range_search.cc | 54 ++++++++++++ 035_search_insert_position/insert_position.cc | 20 +++++ 33 files changed, 1156 insertions(+) create mode 100644 001_two_sum/two_sum.cc create mode 100644 002_add_two_numbers/add_two_numbers.cc create mode 100644 003_longest_substring_without_repeat/longest_substring_without_repeat.cc create mode 100644 004_median_of_two_sorted_array/median_of_two_sorted_array.cc create mode 100644 006_zigzag_conversion/zigzag_conversion.cc create mode 100644 007_reverse_integer/reverse_integer.cc create mode 100644 008_atoi/atoi.cc create mode 100644 009_palindrome_number/palindrome_number.cc create mode 100644 010_regular_expression_matching/regular_expression.cc create mode 100644 011_container_with_most_water/container.cc create mode 100644 012_roman_numeral/roman_numeral.cc create mode 100644 013_roman_to_integer/roman_to_integer.cc create mode 100644 014_longest_common_prefix/common_prefix.cc create mode 100644 015_three_sum/three_sum.cc create mode 100644 016_three_sum_closest/three_sum_closest.cc create mode 100644 018_four_sum/four_sum.cc create mode 100644 019_remove_nth_node_from_end_of_list/remove_end.cc create mode 100644 020_valid_parentheses/valid_parentheses.cc create mode 100644 021_merge_two_sorted_lists/merge_lists.cc create mode 100644 022_generate_parathesis/parenthesis.cc create mode 100644 023_merge_k_sorted_lists/merge_lists.cc create mode 100644 024_swap_nodes_in_pairs/swap_nodes.cc create mode 100644 025_reverse_nodes_in_k_group/reverse_nodes.cc create mode 100644 026_remove_duplicates_from_sorted_array/rm_dup.cc create mode 100644 027_remove_element/rm_elem.cc create mode 100644 028_implement_strstr/strstr.cc create mode 100644 029_divide_two_integers/divide.cc create mode 100644 030_substring_with_concatenation_of_all_words/concatenation.cc create mode 100644 031_next_permutation/next_permutation.cc create mode 100644 032_longest_valid_parentheses/valid_parentheses.cc create mode 100644 033_search_in_rotated_sorted_array/rotated_array.cc create mode 100644 034_search_for_a_range/range_search.cc create mode 100644 035_search_insert_position/insert_position.cc diff --git a/001_two_sum/two_sum.cc b/001_two_sum/two_sum.cc new file mode 100644 index 0000000..c06f0b4 --- /dev/null +++ b/001_two_sum/two_sum.cc @@ -0,0 +1,22 @@ +#include + +using namespace std; + +class Solution { +public: + vector twoSum(vector& nums, int target) { + vector res; + unordered_map ht; + for (int i = 0; i < nums.size(); i++) { + int other = target - nums[i]; + if (ht.find(other) != ht.end()) { + /* Only one solution for purpose of this problem */ + res.append(ht[other]); + res.append(i); + return res; + } + ht[nums[i]] = i; + } + return res; + } +}; diff --git a/002_add_two_numbers/add_two_numbers.cc b/002_add_two_numbers/add_two_numbers.cc new file mode 100644 index 0000000..192e3e5 --- /dev/null +++ b/002_add_two_numbers/add_two_numbers.cc @@ -0,0 +1,55 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + int carry = 0; + struct ListNode dummy; + struct ListNode *p = l1, *prev = &dummy; + + dummy.next = p; + while (l1 != nullptr || l2 != nullptr) { + int sum = 0; + + if (l1 != nullptr) { + sum += l1->val; + l1 = l1->next; + } + + if (l2 != nullptr) { + if (p == nullptr) { + /* l2 longer than l1 */ + prev->next = l2; + p = l2; + } + sum += l2->val; + l2 = l2->next; + } + + sum += carry; + carry = sum / 10; + p->val = sum % 10; + prev = p; + p = p->next; + } + + if (carry) { + p = new ListNode(carry); + prev->next = p; + } + + return dummy.next; + } +}; diff --git a/003_longest_substring_without_repeat/longest_substring_without_repeat.cc b/003_longest_substring_without_repeat/longest_substring_without_repeat.cc new file mode 100644 index 0000000..08a12e2 --- /dev/null +++ b/003_longest_substring_without_repeat/longest_substring_without_repeat.cc @@ -0,0 +1,30 @@ +#include + +using namespace std; + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + vector indexes(128, -1); + int max_len = 0; + int len = 0; + + 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]]; + } + } + max_len = max(max_len, len); + indexes[s[i]] = i; + } + + return max_len; + } +}; diff --git a/004_median_of_two_sorted_array/median_of_two_sorted_array.cc b/004_median_of_two_sorted_array/median_of_two_sorted_array.cc new file mode 100644 index 0000000..a5b46f2 --- /dev/null +++ b/004_median_of_two_sorted_array/median_of_two_sorted_array.cc @@ -0,0 +1,30 @@ +#include + +using namespace std; + +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + int sum = nums1.size() + nums2.size(); + vector nums; + int i = 0, j = 0, k; + int half = sum / 2 + 1; + for (k = 0; k < half; k++) { + int n; + if (i < nums1.size() && j < nums2.size()) { + n = (nums1[i] < nums2[j]) ? nums1[i++] : nums2[j++]; + } else if (i < nums1.size()) { + n = nums1[i++]; + } else if (j < nums2.size()) { + n = nums2[j++]; + } + nums.push_back(n); + } + + if (sum % 2) { + return nums[k-1]; + } else { + return (nums[k-1] + nums[k-2]) / 2.0; + } + } +}; diff --git a/006_zigzag_conversion/zigzag_conversion.cc b/006_zigzag_conversion/zigzag_conversion.cc new file mode 100644 index 0000000..5ee1887 --- /dev/null +++ b/006_zigzag_conversion/zigzag_conversion.cc @@ -0,0 +1,29 @@ +#include + +using namespace std; + +class Solution { +public: + string convert(string s, int numRows) { + if (numRows <= 1) { + return s; + } + + string new_s; + for (int row = 0; row < numRows; row++) { + int delta; + int interval1 = numRows + (numRows - 2) - row * 2; + int interval2 = 2 * row; + bool flag = false; + for (int i = row; i < s.length(); i += delta) { + new_s.push_back(s[i]); + do { + delta = !flag ? interval1 : interval2; + flag = !flag; + } while (delta == 0); + } + } + + return new_str; + } +}; diff --git a/007_reverse_integer/reverse_integer.cc b/007_reverse_integer/reverse_integer.cc new file mode 100644 index 0000000..3ed2273 --- /dev/null +++ b/007_reverse_integer/reverse_integer.cc @@ -0,0 +1,24 @@ +#include + +using namespace std; + +class Solution { +public: + int reverse(int x) { + int n = 0; + while (x != 0) { + // Checking the over/underflow. + int r = x % 10; + if (n > INT_MAX / 10 || (n == INT_MAX / 10 && r > 7)) { + return 0; + } + if (n < INT_MIN / 10 || (n == INT_MIN / 10 && r < -8)) { + return 0; + } + + n = n * 10 + r; + x = x / 10; + } + return n; + } +}; diff --git a/008_atoi/atoi.cc b/008_atoi/atoi.cc new file mode 100644 index 0000000..002fab8 --- /dev/null +++ b/008_atoi/atoi.cc @@ -0,0 +1,55 @@ +#include + +using namespace std; + +class Solution { +public: + int myAtoi(string str) { + long n = 0; + int i, sign = 0; + + for (i = 0; i < str.length(); i++) { + if (str[i] != ' ' && str[i] != '\t') { + break; + } + } + + if (str[i] == '-') { + if (isdigit(str[++i])) { + sign = 1; + } else { + return 0; + } + } + + if (str[i] == '+') { + if (isdigit(str[++i])) { + sign = 0; + } else { + return 0; + } + } + + for (; i < str.length(); i++) { + if (isdigit(str[i])) { + int d = str[i] - '0'; + if (sign) { + if (-n < (INT_MIN + d) / 10) { + n = INT_MIN; + break; + } + } else { + if (n > (INT_MAX - d) / 10) { + n = INT_MAX; + break; + } + } + n = n * 10 + d; + } else { + break; + } + } + + return sign ? -n : n; + } +}; diff --git a/009_palindrome_number/palindrome_number.cc b/009_palindrome_number/palindrome_number.cc new file mode 100644 index 0000000..e6b77a5 --- /dev/null +++ b/009_palindrome_number/palindrome_number.cc @@ -0,0 +1,35 @@ +#include + +using namespace std; + +class Solution { +public: + bool isPalindrome(int x) { + if (x == 0) { + return true; + } + if (x < 0) { + return false; + } + return x == reverse(x); + } + +private: + int reverse(int x) { + int n = 0; + while (x != 0) { + // Checking the over/underflow. + int r = x % 10; + if (n > INT_MAX / 10 || (n == INT_MAX / 10 && r > 7)) { + return 0; + } + if (n < INT_MIN / 10 || (n == INT_MIN / 10 && r < -8)) { + return 0; + } + + n = n * 10 + r; + x = x / 10; + } + return n; + } +}; diff --git a/010_regular_expression_matching/regular_expression.cc b/010_regular_expression_matching/regular_expression.cc new file mode 100644 index 0000000..45ab1c0 --- /dev/null +++ b/010_regular_expression_matching/regular_expression.cc @@ -0,0 +1,30 @@ +#include + +using namespace std; + +class Solution { +public: + /* recursive version too slow thanks to substr() */ + bool isMatch(string s, string p) { + vector> dp(s.size() + 1, vector(p.size() + 1, false)); + dp[0][0] = true; + for (int i = 1; i <= p.length(); i++) { + dp[0][i] = p[0][i - 1] == '*' && i >= 2 && dp[0][i - 2]; + } + + for (int i = 1; i <= s.length(); i++) { + for (int j = 1; j <= p.length(); j++) { + bool match; + if (j >= 2 && p[j - 1] == '*') { + match = (s[i - 1] == p[j - 2] || p[j - 2] == '.'); + dp[i][j] = dp[i][j - 2] || (match && dp[i - 1][j]); + } else { + match = (s[i - 1] == p[j - 1] || p[j - 1] == '.'); + dp[i][j] = match && dp[i - 1][j - 1]; + } + } + } + + return dp[s.size()][p.size()]; + } +}; diff --git a/011_container_with_most_water/container.cc b/011_container_with_most_water/container.cc new file mode 100644 index 0000000..480e6df --- /dev/null +++ b/011_container_with_most_water/container.cc @@ -0,0 +1,21 @@ +#include + +using namespace std; + +class Solution { +public: + int maxArea(vector& height) { + int min = 0, max = height.size() - 1; + int area_max = 0; + while (min < max) { + int area = (max - min) * (height[min] < height[max] ? height[min] : height[max]); + area_max = area > area_max ? area : area_max; + if (height[min] < height[max]) { + min++; + } else { + max--; + } + } + return area_max; + } +}; diff --git a/012_roman_numeral/roman_numeral.cc b/012_roman_numeral/roman_numeral.cc new file mode 100644 index 0000000..8b97a6f --- /dev/null +++ b/012_roman_numeral/roman_numeral.cc @@ -0,0 +1,82 @@ +#include + +using namespace std; + +class Solution { +public: + string intToRoman(int num) { + int thousand_bit = num / 1000; + int hundred_bit = (num % 1000) / 100; + int ten_bit = (num % 100) / 10; + int one_bit = num % 10; + + if (thousand_bit > 0) { + if (thousand_bit < 4) { + for (int i = 0; i < thousand_bit; i++) { + roman_numeral.push_back('M'); + } + } + } + + num2char(hundred_bit, 2); + num2char(ten_bit, 1); + num2char(one_bit, 0); + + return roman_numeral; + } + +private: + string roman_numeral; + void num2char(int bit, int n) { + char low, mid, high; + + switch (n) { + case 2: + low = 'C'; + mid = 'D'; + high = 'M'; + break; + case 1: + low = 'X'; + mid = 'L'; + high = 'C'; + break; + case 0: + low = 'I'; + mid = 'V'; + high = 'X'; + break; + } + + if (bit > 0) { + switch (bit) { + case 1: + case 2: + case 3: + for (int i = 0; i < bit; i++) { + roman_numeral.push_back(low); + } + break; + case 4: + roman_numeral.push_back(low); + roman_numeral.push_back(mid); + break; + case 5: + roman_numeral.push_back(mid); + break; + case 6: + case 7: + case 8: + roman_numeral.push_back(mid); + for (int i = 5; i < bit; i++) { + roman_numeral.push_back(low); + } + break; + case 9: + roman_numeral.push_back(low); + roman_numeral.push_back(high); + break; + } + } + } +}; diff --git a/013_roman_to_integer/roman_to_integer.cc b/013_roman_to_integer/roman_to_integer.cc new file mode 100644 index 0000000..484ae28 --- /dev/null +++ b/013_roman_to_integer/roman_to_integer.cc @@ -0,0 +1,46 @@ +#include + +using namespace std; + +class Solution { +public: + int romanToInt(string s) { + int curr = roman_to_integer(s[0]); + int result = curr; + + for (int i = 1; i < s.length(); i++) { + int prev = curr; + curr = roman_to_integer(s[i]); + /* left < right : IV(4), XL(40), IX(9) ... */ + if (prev < curr) { + result -= prev - (curr - prev); + } else { + result += curr; + } + } + + return result; + } + +private: + int roman_to_integer(char c) { + switch(c) { + case 'I': + return 1; + case 'V': + return 5; + case 'X': + return 10; + case 'L': + return 50; + case 'C': + return 100; + case 'D': + return 500; + case 'M': + return 1000; + default: + return 0; + } + } +}; diff --git a/014_longest_common_prefix/common_prefix.cc b/014_longest_common_prefix/common_prefix.cc new file mode 100644 index 0000000..399c991 --- /dev/null +++ b/014_longest_common_prefix/common_prefix.cc @@ -0,0 +1,23 @@ +#include + +using namespace std; + +class Solution { +public: + string longestCommonPrefix(vector& strs) { + string lcp; + if (strs.empty()) { + return lcp; + } + for (int j = 0; j < strs[0].length(); j++) { + char c = strs[0][j]; + for (int i = 1; i < strs.size(); i++) { + if (c != strs[i][j]) { + return lcp; + } + } + lcp.push_back(c); + } + return lcp; + } +}; diff --git a/015_three_sum/three_sum.cc b/015_three_sum/three_sum.cc new file mode 100644 index 0000000..6cd5550 --- /dev/null +++ b/015_three_sum/three_sum.cc @@ -0,0 +1,34 @@ +#include + +using namespace std; + +class Solution { +public: + vector> threeSum(vector& nums) { + vector> res; + if (nums.size() >= 3) { + sort(nums.begin(), nums.end()); + for (int i = 0; i < nums.size() - 2; i++) { + if (i > 0 && nums[i - 1] == nums[i]) { continue; } + twoSum(nums.begin() + i + 1, nums.end() - 1, -nums[i], res); + } + } + return res; + } + +private: + void twoSum(vector::iterator lo, vector::iterator hi, int target, vector>& res) { + while (lo < hi) { + int sum = *lo + *hi; + if (sum < target) { + lo++; + } else if (sum > target) { + hi--; + } else { + res.push_back(vector {-target, *lo, *hi}); + while (++lo < hi && *lo == *(lo - 1)) {} + while (lo < hi-- && *hi == *(hi + 1)) {} + } + } + } +}; diff --git a/016_three_sum_closest/three_sum_closest.cc b/016_three_sum_closest/three_sum_closest.cc new file mode 100644 index 0000000..6f1299c --- /dev/null +++ b/016_three_sum_closest/three_sum_closest.cc @@ -0,0 +1,37 @@ +#include + +using namespace std; + +class Solution { +public: + int threeSumClosest(vector& nums, int target) { + if (nums.size() < 3) { + return INT_MAX; + } + + int min_diff = INT_MAX; + sort(nums.begin(), nums.end()); + + for (int i = 0; i < nums.size() - 2; i++) { + if (i > 0 && nums[i - 1] == nums[i]) { continue; } + + int lo = i + 1; + int hi = nums.size() - 1; + while (lo < hi) { + int diff = nums[i] + nums[lo] + nums[hi] - target; + if (abs(diff) < abs(min_diff)) { + min_diff = diff; + } + if (diff < 0) { + lo++; + } else if (diff > 0) { + hi--; + } else { + return target; + } + } + } + + return min_diff + target; + } +}; diff --git a/018_four_sum/four_sum.cc b/018_four_sum/four_sum.cc new file mode 100644 index 0000000..dd7a5e5 --- /dev/null +++ b/018_four_sum/four_sum.cc @@ -0,0 +1,44 @@ +#include + +using namespace std; + +class Solution { +public: + vector> fourSum(vector& nums, int target) { + vector> res; + if (nums.size() >= 4) { + vector stack; + sort(nums.begin(), nums.end()); + k_sum(nums.begin(), nums.end() - 1, target, 4, stack, res); + } + return res; + } + +private: + void k_sum(vector::iterator lo, vector::iterator hi, int target, + int k, vector& stack, vector>& res) { + if (k == 2) { + while (lo < hi) { + int sum = *lo + *hi; + if (sum < target) { + lo++; + } else if (sum > target) { + hi--; + } else { + stack.push_back(*lo); + stack.push_back(*hi); + res.push_back(stack); + while (++lo < hi && *lo == *(lo - 1)) {} + while (lo < hi-- && *hi == *(hi + 1)) {} + } + } + } else { + for (vector::iterator it = lo; it + k - 1 != hi + 1; it++) { + if (it > lo && *(it - 1) == *it) { continue; } + stack.push_back(*it); + k_sum(it + 1, hi, target - *it, k - 1, stack, res); + stack.pop_back(); + } + } + } +}; diff --git a/019_remove_nth_node_from_end_of_list/remove_end.cc b/019_remove_nth_node_from_end_of_list/remove_end.cc new file mode 100644 index 0000000..5857e92 --- /dev/null +++ b/019_remove_nth_node_from_end_of_list/remove_end.cc @@ -0,0 +1,42 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + if (n == 0) { + return nullptr; + } + + struct ListNode *p, *prev, dummy; + dummy.next = head; + p = prev = &dummy; + while (n-- > 0) { + p = p->next; + } + + while (p->next != nullptr) { + p = p->next; + prev = prev->next; + } + + struct ListNode *tmp = prev->next; + prev->next = tmp->next; + if (tmp == head) { + head = tmp->next; + } + + return head; + } +}; diff --git a/020_valid_parentheses/valid_parentheses.cc b/020_valid_parentheses/valid_parentheses.cc new file mode 100644 index 0000000..9593ec8 --- /dev/null +++ b/020_valid_parentheses/valid_parentheses.cc @@ -0,0 +1,41 @@ +#include + +using namespace std; + +class Solution { +public: + bool isValid(string s) { + stack stk; + for (int i = 0; i < s.length(); i++) { + switch(s[i]) { + case '(': + case '[': + case '{': + stk.push(s[i]); + break; + case ')': + if (stk.empty() || stk.top() != '(') { + return false; + } else { + stk.pop(); + break; + } + case ']': + if (stk.empty() || stk.top() != '[') { + return false; + } else { + stk.pop(); + break; + } + case '}': + if (stk.empty() || stk.top() != '{') { + return false; + } else { + stk.pop(); + break; + } + } + } + return stk.empty(); + } +}; diff --git a/021_merge_two_sorted_lists/merge_lists.cc b/021_merge_two_sorted_lists/merge_lists.cc new file mode 100644 index 0000000..a5d7a63 --- /dev/null +++ b/021_merge_two_sorted_lists/merge_lists.cc @@ -0,0 +1,41 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + struct ListNode *prev, dummy; + + prev = &dummy; + dummy.next = l1; + while (l1 != nullptr && l2 != nullptr) { + if (l1->val <= l2->val) { + prev = l1; + l1 = l1->next; + } else { + struct ListNode *tmp = l2; + l2 = l2->next; + tmp->next = l1; + prev->next = tmp; + prev = tmp; + } + } + + if (l2 != nullptr) { + prev->next = l2; + } + + return dummy.next; + } +}; diff --git a/022_generate_parathesis/parenthesis.cc b/022_generate_parathesis/parenthesis.cc new file mode 100644 index 0000000..ba7451e --- /dev/null +++ b/022_generate_parathesis/parenthesis.cc @@ -0,0 +1,33 @@ +#include + +using namespace std; + +class Solution { +public: + vector generateParenthesis(int n) { + vector res; + dfs(n, 0, 0, res); + return res; + } + +private: + string stack; + void dfs(int n, int l, int r, vector& res) { + if (stack.length() == 2 * n) { + res.push_back(stack); + return; + } + + if (l < n) { + stack.push_back('('); + dfs(n, l + 1, r, res); + stack.pop_back(); + } + + if (r < l) { + stack.push_back(')'); + dfs(n, l, r + 1, res); + stack.pop_back(); + } + } +}; diff --git a/023_merge_k_sorted_lists/merge_lists.cc b/023_merge_k_sorted_lists/merge_lists.cc new file mode 100644 index 0000000..f2e1556 --- /dev/null +++ b/023_merge_k_sorted_lists/merge_lists.cc @@ -0,0 +1,42 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + auto cmp = [](struct ListNode *n1, struct ListNode *n2) { + return n1->val > n2->val; + } + priority_queue, decltype(cmp)> queue(cmp); + + for (int i = 0; i < lists.size(); i++) { + if (lists[] != nullptr) { + queue.push(lists[i]); + } + } + + struct ListNode dummy, *p = &dummy;; + while (!queue.empty()) { + ListNode *node = queue.top(); + queue.pop(); + p->next = node; + p = node; + if (node->next != nullptr) { + queue.push(node->next); + } + } + + return dummy.next; + } +}; diff --git a/024_swap_nodes_in_pairs/swap_nodes.cc b/024_swap_nodes_in_pairs/swap_nodes.cc new file mode 100644 index 0000000..cca65b3 --- /dev/null +++ b/024_swap_nodes_in_pairs/swap_nodes.cc @@ -0,0 +1,33 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + struct ListNode dummy, *prev = &dummy, *p = head; + dummy.next = head; + while (p != nullptr && p->next != nullptr) { + struct ListNode *q = p->next; + /* deletion */ + p->next = q->next; + /* insertion */ + q->next = prev->next; + prev->next = q; + /* iteration */ + prev = p; + p = p->next; + } + return dummy.next; + } +}; diff --git a/025_reverse_nodes_in_k_group/reverse_nodes.cc b/025_reverse_nodes_in_k_group/reverse_nodes.cc new file mode 100644 index 0000000..73362b2 --- /dev/null +++ b/025_reverse_nodes_in_k_group/reverse_nodes.cc @@ -0,0 +1,41 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseGroup(ListNode* head, int k) { + int len = 0; + struct ListNode dummy, *prev = &dummy; + dummy.next = head; + + for (; head != nullptr; head = head->next) { + if (++len % k == 0) { + struct ListNode *p = prev->next; + while (prev->next != head) { + struct ListNode *q = p->next; + /* deletion */ + p->next = q->next; + /* insertion */ + q->next = prev->next; + prev->next = q; + } + /* iteration */ + prev = p; + head = p; + } + } + + return dummy.next; + } +}; diff --git a/026_remove_duplicates_from_sorted_array/rm_dup.cc b/026_remove_duplicates_from_sorted_array/rm_dup.cc new file mode 100644 index 0000000..2ceef80 --- /dev/null +++ b/026_remove_duplicates_from_sorted_array/rm_dup.cc @@ -0,0 +1,20 @@ +#include + +using namespace std; + +class Solution { +public: + int removeDuplicates(vector& nums) { + if (nums.size() == 0) { + return 0; + } + + int count = 1; + for (int i = 1; i < nums.size(); i++) { + if (nums[i - 1] != nums[i]) { + nums[count++] = nums[i]; + } + } + return count; + } +}; diff --git a/027_remove_element/rm_elem.cc b/027_remove_element/rm_elem.cc new file mode 100644 index 0000000..f6e25d1 --- /dev/null +++ b/027_remove_element/rm_elem.cc @@ -0,0 +1,16 @@ +#include + +using namespace std; + +class Solution { +public: + int removeElement(vector& nums, int val) { + int count = 0; + for (int i = 0; i < nums.size(); i++) { + if (nums[i] != val) { + nums[count++] = nums[i]; + } + } + return count; + } +}; diff --git a/028_implement_strstr/strstr.cc b/028_implement_strstr/strstr.cc new file mode 100644 index 0000000..08808ff --- /dev/null +++ b/028_implement_strstr/strstr.cc @@ -0,0 +1,10 @@ +#include + +using namespace std; + +class Solution { +public: + int strStr(string haystack, string needle) { + return haystack.find(needle); + } +}; diff --git a/029_divide_two_integers/divide.cc b/029_divide_two_integers/divide.cc new file mode 100644 index 0000000..204811e --- /dev/null +++ b/029_divide_two_integers/divide.cc @@ -0,0 +1,42 @@ +#include + +using namespace std; + +class Solution { +public: + int divide(int dividend, int divisor) { + int signal = 1; + unsigned int dvd = dividend; + if (dividend < 0) { + signal *= -1; + dvd = ~dvd + 1; + } + + unsigned int dvs = divisor; + if (divisor < 0) { + signal *= -1; + dvs = ~dvs + 1; + } + + int shift = 0; + while (dvd > dvs << shift) { + shift++; + } + + unsigned int res = 0; + while (dvd >= dvs) { + while (dvd < dvs << shift) { + shift--; + } + res |= (unsigned int) 1 << shift; + dvd -= dvs << shift; + } + + if (signal == 1 && res >= INT_MAX) { + return INT_MAX; + } else { + return res * signal; + } + } +}; + diff --git a/030_substring_with_concatenation_of_all_words/concatenation.cc b/030_substring_with_concatenation_of_all_words/concatenation.cc new file mode 100644 index 0000000..ac9d85c --- /dev/null +++ b/030_substring_with_concatenation_of_all_words/concatenation.cc @@ -0,0 +1,34 @@ +#include + +using namespace std; + +class Solution { +public: + vector findSubstring(string s, vector& words) { + vector res; + if (s.empty() || words.empty()) { + return res; + } + + unordered_map ht; + for (const auto& w : words) { + ht[w]++; + } + + int len = words[0].length(); + for (int i = 0, j = 0; i < s.length() - words.size() * len + 1; i++) { + unordered_map counting; + for (j = 0; j < words.size(); j++) { + string word = s.substr(i + j * len, len); + if (++counting[word] > ht[word]) { + break; + } + } + if (j == words.size()) { + res.push_back(i); + } + } + + return res; + } +}; diff --git a/031_next_permutation/next_permutation.cc b/031_next_permutation/next_permutation.cc new file mode 100644 index 0000000..d1c7f72 --- /dev/null +++ b/031_next_permutation/next_permutation.cc @@ -0,0 +1,27 @@ +#include + +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--; + } + + if (i >= 0) { + int j = nums.size() - 1; + while (j >= 0 && nums[j] >= nums[i]) { + j--; + } + swap(nums.begin() + i, nums.begin() + j); + } + + reverse(nums.begin() + i + 1, nums.end()); + } +}; diff --git a/032_longest_valid_parentheses/valid_parentheses.cc b/032_longest_valid_parentheses/valid_parentheses.cc new file mode 100644 index 0000000..37ae42f --- /dev/null +++ b/032_longest_valid_parentheses/valid_parentheses.cc @@ -0,0 +1,32 @@ +#include + +using namespace std; + +class Solution { +public: + int longestValidParentheses(string s) { + stack stk; + int invalid = -1; + int len = 0, max_len = 0; + for (int i = 0; i < s.length(); i++) { + if (s[i] == '(') { + stk.push(i); + } else { + if (stk.empty()) { + invalid = i; + } else { + stk.pop(); + if (stk.empty()) { + /* locate the remote ')' */ + max_len = max(i - invalid, max_len); + } else { + /* locate the remote '(' */ + max_len = max(i - stk.top(), max_len); + } + } + } + } + + return max_len; + } +}; diff --git a/033_search_in_rotated_sorted_array/rotated_array.cc b/033_search_in_rotated_sorted_array/rotated_array.cc new file mode 100644 index 0000000..6332d10 --- /dev/null +++ b/033_search_in_rotated_sorted_array/rotated_array.cc @@ -0,0 +1,31 @@ +#include + +using namespace std; + +class Solution { +public: + 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; + } + if (nums[lo] <= nums[mid]) { + if (nums[lo] <= target && target < nums[mid]) { + hi = mid - 1; + } else { + lo = mid + 1; + } + } else { + if (nums[mid] < target && target <= nums[hi]) { + lo = mid + 1; + } else { + hi = mid - 1; + } + } + } + return -1; + } +}; diff --git a/034_search_for_a_range/range_search.cc b/034_search_for_a_range/range_search.cc new file mode 100644 index 0000000..28565a3 --- /dev/null +++ b/034_search_for_a_range/range_search.cc @@ -0,0 +1,54 @@ +#include + +using namespace std; + +class Solution { +public: + vector searchRange(vector& nums, int target) { + vector res; + res.push_back(binary_search_begin(nums, target)); + res.push_back(binary_search_end(nums, target)); + return res; + } + +private: + int binary_search_begin(vector nums, int target) + { + int lo = -1; + int hi = nums.size(); + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; + if (target > nums[mid]) { + lo = mid; + } else { + hi = mid; + } + } + + if (hi == nums.size() || nums[hi] != target) { + return -1; + } else { + return hi; + } + } + + int binary_search_end(vector nums, int target) + { + int lo = -1; + int hi = nums.size(); + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; + if (target < nums[mid]) { + hi = mid; + } else { + lo = mid; + } + } + + if (lo == -1 || nums[lo] != target) { + return -1; + } else { + return lo; + } + } +}; diff --git a/035_search_insert_position/insert_position.cc b/035_search_insert_position/insert_position.cc new file mode 100644 index 0000000..947a0eb --- /dev/null +++ b/035_search_insert_position/insert_position.cc @@ -0,0 +1,20 @@ +#include + +using namespace std; + +class Solution { +public: + int searchInsert(vector& nums, int target) { + int lo = -1; + int hi = nums.size(); + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; + if (target > nums[mid]) { + lo = mid; + } else { + hi = mid; + } + } + return hi; + } +}; From 3c3d4863940a9bb17dee67a8d4ef6a70b7d907f2 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 23 Jul 2020 21:23:53 +0800 Subject: [PATCH 083/211] Fix Signed-off-by: begeekmyfriend --- 034_search_for_a_range/range_search.c | 42 +++---- 036_valid_sudoku/valid_sudoku.c | 129 ++++++-------------- 037_sudoku_solver/sudoku_solver.c | 164 +++++++++++--------------- 3 files changed, 126 insertions(+), 209 deletions(-) diff --git a/034_search_for_a_range/range_search.c b/034_search_for_a_range/range_search.c index 457ed51..ddc89d5 100644 --- a/034_search_for_a_range/range_search.c +++ b/034_search_for_a_range/range_search.c @@ -1,43 +1,43 @@ #include #include -static int binary_search_start(int *a, int size, int target) +static int binary_search_begin(int *a, int size, int target) { - int low = -1; - int high = size; - while (low + 1 < high) { - int mid = low + (high - low) / 2; + int lo = -1; + int hi = size; + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; if (target > a[mid]) { - low = mid; + lo = mid; } else { - high = mid; + hi = mid; } } - if (high == size || a[high] != target) { + if (hi == size || a[hi] != target) { return -1; } else { - return high; + return hi; } } static int binary_search_end(int *a, int size, int target) { - int low = -1; - int high = size; - while (low + 1 < high) { - int mid = low + (high - low) / 2; + int lo = -1; + int hi = size; + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; if (target < a[mid]) { - high = mid; + hi = mid; } else { - low = mid; + lo = mid; } } - if (low == -1 || a[low] != target) { + if (lo == -1 || a[lo] != target) { return -1; } else { - return low; + return lo; } } @@ -49,13 +49,7 @@ static int* searchRange(int* nums, int numsSize, int target, int* returnSize) { int *range = malloc(2 * sizeof(int)); *returnSize = 2; - - if (numsSize == 0) { - range[0] = range[1] = -1; - return range; - } - - range[0] = binary_search_start(nums, numsSize, target); + range[0] = binary_search_begin(nums, numsSize, target); range[1] = binary_search_end(nums, numsSize, target); return range; } diff --git a/036_valid_sudoku/valid_sudoku.c b/036_valid_sudoku/valid_sudoku.c index 7ee6b5b..aaf2962 100644 --- a/036_valid_sudoku/valid_sudoku.c +++ b/036_valid_sudoku/valid_sudoku.c @@ -3,113 +3,57 @@ #include #include -struct stack { - int row; - int col; - int value; -}; -static bool valid(char **board, int row, int col) +static bool valid(char **board, char *mark, int i, int j) { + if (board[i][j] != '.') { + int index = board[i][j] - '0'; + if (mark[index]) { + return false; + } else { + mark[index] = 1; + } + } + return true; +} + +bool isValidSudoku(char** board, int boardSize, int* boardColSize) { int i, j, k; - char mark[10]; - for (i = 0; i <= row; i++) { - memset(mark, 0, 10); - /* check row validity */ - for (j = 0; j < 9; j++) { - if (board[i][j] != '.') { - int index = board[i][j] - '0'; - if (mark[index]) { - return false; - } else { - mark[index] = 1; - } + /* check row validity */ + for (i = 0; i < boardSize; i++) { + char mark[10] = { '\0' }; + for (j = 0; j < boardColSize[i]; j++) { + if (!valid(board, mark, i, j)) { + return false; } } } /* check column validity */ - for (i = 0; i <= col; i++) { - memset(mark, 0, 10); - for (j = 0; j < 9; j++) { - if (board[j][i] != '.') { - int index = board[j][i] - '0'; - if (mark[index]) { - return false; - } else { - mark[index] = 1; - } + for (j = 0; j < boardColSize[0]; j++) { + char mark[10] = { '\0' }; + for (i = 0; i < boardSize; i++) { + if (!valid(board, mark, i, j)) { + return false; } } } /* check sub-box validity */ - int count = row / 3 * 3 + col / 3 + 1; - for (k = 0; k < count; k++) { + for (k = 0; k < boardSize; k++) { int sr = k / 3 * 3; int sc = (k % 3) * 3; - memset(mark, 0, 10); + char mark[10] = { '\0' }; for (i = sr; i < sr + 3; i++) { for (j = sc; j < sc + 3; j++) { - if (board[i][j] != '.') { - int index = board[i][j] - '0'; - if (mark[index]) { - return false; - } else { - mark[index] = 1; - } - } - } - } - } - - return true; -} - -static bool isValidSudoku(char** board, int boardRowSize, int boardColSize) -{ - if (boardRowSize != 9 || boardColSize != 9) { - return false; - } - - int i = 0, j = 0, k = 1, num = 0; - struct stack stack[81]; - - while (i < boardRowSize) { - if (board[i][j] == '.') { - while (k <= 9) { - board[i][j] = k + '0'; - if (valid(board, i, j)) { - stack[num].row = i; - stack[num].col = j; - stack[num].value = k; - num++; - k = 1; - break; - } - k++; - } - if (k == 10) { - if (num == 0) { + if (!valid(board, mark, i, j)) { return false; } - board[i][j] = '.'; - --num; - i = stack[num].row; - j = stack[num].col; - k = stack[num].value + 1; - board[i][j] = '.'; - continue; } } - /* next row */ - if (++j == boardColSize) { - j = 0; - i++; - } } - + return true; } @@ -117,24 +61,25 @@ int main(int argc, char **argv) { int i, j; char *str = argv[1]; + int *col_sizes = malloc(9 * sizeof(int)); char **board = malloc(9 * sizeof(char *)); for (i = 0; i < 9; i++) { board[i] = malloc(10); - memcpy(board[i], str + i * 9, 9); - board[9] = '\0'; - char *row = board[i]; + strcpy(board[i], str + i * 9); for (j = 0; j < 9; j++) { - printf("%c ", row[j]); + printf("%c ", board[i][j]); } + col_sizes[i] = 9; printf("\n"); } - printf("%s\n", isValidSudoku(board, 9, 9) ? "true" : "false"); + + printf("%s\n", isValidSudoku(board, 9, col_sizes) ? "true" : "false"); for (i = 0; i < 9; i++) { - char *row = board[i]; for (j = 0; j < 9; j++) { - printf("%c ", row[j]); + printf("%c ", board[i][j]); } printf("\n"); } - return; + + return 0; } diff --git a/037_sudoku_solver/sudoku_solver.c b/037_sudoku_solver/sudoku_solver.c index c942bea..1c4aae9 100644 --- a/037_sudoku_solver/sudoku_solver.c +++ b/037_sudoku_solver/sudoku_solver.c @@ -3,118 +3,85 @@ #include #include -struct stack { - int row; - int col; - int value; -}; - -static bool valid(char **board, int row, int col) +static bool valid(int num, int row, int col, int index, + bool **rows, bool **cols, bool **boxes) { - int i, j, k; - char mark[10]; - - for (i = 0; i <= row; i++) { - memset(mark, 0, 10); - /* check row validity */ - for (j = 0; j < 9; j++) { - if (board[i][j] != '.') { - int index = board[i][j] - '0'; - if (mark[index]) { - return false; - } else { - mark[index] = 1; - } - } - } - } - - /* check column validity */ - for (i = 0; i <= col; i++) { - memset(mark, 0, 10); - for (j = 0; j < 9; j++) { - if (board[j][i] != '.') { - int index = board[j][i] - '0'; - if (mark[index]) { - return false; - } else { - mark[index] = 1; - } - } - } - } + return !rows[row][num] && !cols[col][num] && !boxes[index][num]; +} - /* check sub-box validity */ - int count = row / 3 * 3 + col / 3 + 1; - for (k = 0; k < count; k++) { - int sr = k / 3 * 3; - int sc = (k % 3) * 3; - memset(mark, 0, 10); - for (i = sr; i < sr + 3; i++) { - for (j = sc; j < sc + 3; j++) { - if (board[i][j] != '.') { - int index = board[i][j] - '0'; - if (mark[index]) { - return false; - } else { - mark[index] = 1; +static bool dfs(char** board, int size, bool **rows, bool **cols, bool **boxes) +{ + if (size == 9 * 9) { + return true; + } else { + int i; + bool ok = false; + int row = size / 9; + int col = size % 9; + int index = row / 3 * 3 + col / 3; + if (board[row][col] == '.') { + for (i = 1; i <= 9; i++) { + if (valid(i, row, col, index, rows, cols, boxes)) { + /* lock this grid as well as the number */ + board[row][col] = i + '0'; + rows[row][i] = true; + cols[col][i] = true; + boxes[index][i] = true; + ok = dfs(board, size + 1, rows, cols, boxes); + if (!ok) { + /* release this grid as well as the number */ + rows[row][i] = false; + cols[col][i] = false; + boxes[index][i] = false; + board[row][col] = '.'; } } } + } else { + ok = dfs(board, size + 1, rows, cols, boxes); } + return ok; } - - return true; } -static void solveSudoku(char** board, int boardRowSize, int boardColSize) +void solveSudoku(char** board, int boardSize, int *boardColSize) { - if (boardRowSize != 9 || boardColSize != 9) { - return; + int i, j; + bool **rows = malloc(boardSize * sizeof(bool *)); + bool **cols = malloc(boardSize * sizeof(bool *)); + bool **boxes = malloc(boardSize * sizeof(bool *)); + + for (i = 0; i < boardSize; i++) { + rows[i] = malloc(10 * sizeof(bool)); + cols[i] = malloc(10 * sizeof(bool)); + boxes[i] = malloc(10 * sizeof(bool)); + memset(rows[i], false, 10 * sizeof(bool)); + memset(cols[i], false, 10 * sizeof(bool)); + memset(boxes[i], false, 10 * sizeof(bool)); } - int i = 0, j = 0, k = 1, num = 0; - struct stack stack[81]; - - while (i < boardRowSize) { - if (board[i][j] == '.') { - while (k <= 9) { - board[i][j] = k + '0'; - if (valid(board, i, j)) { - stack[num].row = i; - stack[num].col = j; - stack[num].value = k; - num++; - k = 1; - break; - } - k++; - } - if (k == 10) { - if (num == 0) { - return; - } - board[i][j] = '.'; - --num; - i = stack[num].row; - j = stack[num].col; - k = stack[num].value + 1; - board[i][j] = '.'; - continue; + /* Mark whether the grid is available for the number */ + for (i = 0; i < boardSize; i++) { + for (j = 0; j < boardColSize[i]; j++) { + if (board[i][j] != '.') { + int num = board[i][j] - '0'; + int index = i / 3 * 3 + j / 3; + rows[i][num] = true; + cols[j][num] = true; + boxes[index][num] = true; } } - /* next row */ - if (++j == boardColSize) { - j = 0; - i++; - } } + + dfs(board, 0, rows, cols, boxes); } int main(void) { int i, j; char **board = malloc(9 * sizeof(char *)); + int *col_sizes = malloc(9 * sizeof(int)); + board[0] = malloc(10); board[0][0] = '5'; board[0][1] = '3'; @@ -126,6 +93,7 @@ int main(void) board[0][7] = '.'; board[0][8] = '.'; board[0][9] = '\0'; + col_sizes[0] = 9; board[1] = malloc(10); board[1][0] = '6'; @@ -138,6 +106,7 @@ int main(void) board[1][7] = '.'; board[1][8] = '.'; board[1][9] = '\0'; + col_sizes[1] = 9; board[2] = malloc(10); board[2][0] = '.'; @@ -150,6 +119,7 @@ int main(void) board[2][7] = '6'; board[2][8] = '.'; board[2][9] = '\0'; + col_sizes[2] = 9; board[3] = malloc(10); board[3][0] = '8'; @@ -162,6 +132,7 @@ int main(void) board[3][7] = '.'; board[3][8] = '3'; board[3][9] = '\0'; + col_sizes[3] = 9; board[4] = malloc(10); board[4][0] = '4'; @@ -174,6 +145,7 @@ int main(void) board[4][7] = '.'; board[4][8] = '1'; board[4][9] = '\0'; + col_sizes[4] = 9; board[5] = malloc(10); board[5][0] = '7'; @@ -186,6 +158,7 @@ int main(void) board[5][7] = '.'; board[5][8] = '6'; board[5][9] = '\0'; + col_sizes[5] = 9; board[6] = malloc(10); board[6][0] = '.'; @@ -198,6 +171,7 @@ int main(void) board[6][7] = '8'; board[6][8] = '.'; board[6][9] = '\0'; + col_sizes[6] = 9; board[7] = malloc(10); board[7][0] = '.'; @@ -210,6 +184,7 @@ int main(void) board[7][7] = '.'; board[7][8] = '5'; board[7][9] = '\0'; + col_sizes[7] = 9; board[8] = malloc(10); board[8][0] = '.'; @@ -222,6 +197,7 @@ int main(void) board[8][7] = '7'; board[8][8] = '9'; board[8][9] = '\0'; + col_sizes[8] = 9; for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { @@ -230,12 +206,14 @@ int main(void) printf("\n"); } printf("\n"); - solveSudoku(board, 9, 9); + + solveSudoku(board, 9, col_sizes); for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { printf("%c ", board[i][j]); } printf("\n"); } - return; + + return 0; } From 7c2d3dbe864be969a80f7a44b6807f1901067615 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 27 Jul 2020 17:26:19 +0800 Subject: [PATCH 084/211] Refine Signed-off-by: begeekmyfriend --- 039_combination_sum/combination_sum.c | 7 ++++-- 040_combination_sum_ii/combination_sum.c | 30 ++++++++++-------------- 046_permutations/permutations.c | 23 ++++++++++++++++++ 047_permutations_ii/permutations.c | 4 ++-- 051_n_queens/n_queens.c | 1 - 077_combinations/combinations.c | 1 - 090_subsets_ii/subsets.c | 30 ++++++++++-------------- 7 files changed, 55 insertions(+), 41 deletions(-) diff --git a/039_combination_sum/combination_sum.c b/039_combination_sum/combination_sum.c index c360117..590c3f0 100644 --- a/039_combination_sum/combination_sum.c +++ b/039_combination_sum/combination_sum.c @@ -6,14 +6,17 @@ static void dfs(int *nums, int size, int start, int target, int *stack, int len, int **results, int *count, int *column_sizes) { int i; - if (target == 0) { + if (target < 0) { + return; + } else if (target == 0) { results[*count] = malloc(len * sizeof(int)); memcpy(results[*count], stack, len * sizeof(int)); column_sizes[*count] = len; (*count)++; - } else if (target > 0) { + } else { for (i = start; i < size; i++) { stack[len] = nums[i]; + /* The elements in solution can be duplicate for the purpose of the problem */ dfs(nums, size, i, target - nums[i], stack, len + 1, results, column_sizes, count); } } diff --git a/040_combination_sum_ii/combination_sum.c b/040_combination_sum_ii/combination_sum.c index a46d3ab..01d6965 100644 --- a/040_combination_sum_ii/combination_sum.c +++ b/040_combination_sum_ii/combination_sum.c @@ -8,29 +8,27 @@ static int compare(const void *a, const void *b) return *(int *) a - *(int *) b; } -static void dfs(int *nums, int size, int start, int target, int *solution, int len, - bool *used, int **results, int *count, int *column_sizes) +static void dfs(int *nums, int size, int start, int target, int *solution, + int len, int **results, int *count, int *column_sizes) { int i; - if (target == 0) { + if (target < 0) { + return; + } else if (target == 0) { results[*count] = malloc(len * sizeof(int)); memcpy(results[*count], solution, len * sizeof(int)); column_sizes[*count] = len; (*count)++; - } else if (target > 0) { + } else { + int last = -1; for (i = start; i < size; i++) { - if (!used[i]) { - if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { - /* Forbid same elements in same level */ - /* Used marks allow same elements in different levels */ - continue; - } - used[i] = true; + if (last != nums[i]) { + /* No duplicate combinations in different order */ solution[len] = nums[i]; - /* i + 1 limits the selecting range in following levels */ - dfs(nums, size, i + 1, target - nums[i], solution, len + 1, used, results, count, column_sizes); - used[i] = false; + /* i + 1 limits the candidate range in next levels */ + dfs(nums, size, i + 1, target - nums[i], solution, len + 1, results, count, column_sizes); } + last = nums[i]; } } } @@ -46,11 +44,9 @@ static int** combinationSum(int* candidates, int candidatesSize, int target, int int *solution = malloc(target * sizeof(int)); int **results = malloc(100 * sizeof(int *)); - bool *used = malloc(candidatesSize); - memset(used, false, candidatesSize); *returnColumnSizes = malloc(100 * sizeof(int)); *returnSize = 0; - dfs(candidates, candidatesSize, 0, target, solution, 0, used, results, returnSize, *returnColumnSizes); + dfs(candidates, candidatesSize, 0, target, solution, 0, results, returnSize, *returnColumnSizes); return results; } diff --git a/046_permutations/permutations.c b/046_permutations/permutations.c index 009669c..5176834 100644 --- a/046_permutations/permutations.c +++ b/046_permutations/permutations.c @@ -3,6 +3,7 @@ #include #include +#if 0 static void swap(int *a, int *b) { int tmp = *a; @@ -10,6 +11,27 @@ static void swap(int *a, int *b) *b = tmp; } +static void dfs(int *nums, int size, int start, + int **results, int *count, int *col_size) +{ + int i; + if (start == size) { + results[*count] = malloc(size * sizeof(int)); + memcpy(results[*count], nums, size * sizeof(int)); + col_size[*count] = size; + (*count)++; + } else { + for (i = start; i < size; i++) { + /* A swap can make a new permutation but not be listed in order */ + swap(nums + start, nums + i); + dfs(nums, size, start + 1, results, count, col_size); + /* restore the array in backtrace */ + swap(nums + start, nums + i); + } + } +} +#endif + static void dfs(int *nums, int size, bool *used, int *stack, int len, int **results, int *count, int *col_size) { @@ -22,6 +44,7 @@ static void dfs(int *nums, int size, bool *used, int *stack, } else { for (i = 0; i < size; i++) { if (!used[i]) { + /* */ used[i] = true; stack[len] = nums[i]; dfs(nums, size, used, stack, len + 1, results, count, col_size); diff --git a/047_permutations_ii/permutations.c b/047_permutations_ii/permutations.c index 1ba93e2..51e0339 100644 --- a/047_permutations_ii/permutations.c +++ b/047_permutations_ii/permutations.c @@ -21,8 +21,8 @@ static void dfs(int *nums, int size, bool *used, int *stack, for (i = 0; i < size; i++) { if (!used[i]) { if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) { - /* Forbid same elements on same level */ - /* Used marks allow same elements in different levels */ + /* In case that duplicate permutation with same elemements */ + /* Used marks allow same elements in different DFS levels */ continue; } used[i] = true; diff --git a/051_n_queens/n_queens.c b/051_n_queens/n_queens.c index 0b2a1c5..e2ba9a3 100644 --- a/051_n_queens/n_queens.c +++ b/051_n_queens/n_queens.c @@ -65,7 +65,6 @@ static void dfs(int n, int row, int *stack, char ***solutions, int *count, int * if (row == 0 || !conflict(stack, row, col)) { stack[row] = col; dfs(n, row + 1, stack, solutions, count, col_sizes); - continue; } } } diff --git a/077_combinations/combinations.c b/077_combinations/combinations.c index 7625498..d184521 100644 --- a/077_combinations/combinations.c +++ b/077_combinations/combinations.c @@ -14,7 +14,6 @@ static void dfs(int n, int k, int start, int *stack, int len, (*count)++; } else { for (i = start; i <= n; i++) { - /* No used marks since the order does not matter */ stack[len] = i; dfs(n, k, i + 1, stack, len + 1, results, count, col_sizes); } diff --git a/090_subsets_ii/subsets.c b/090_subsets_ii/subsets.c index e2f40db..4c3897d 100644 --- a/090_subsets_ii/subsets.c +++ b/090_subsets_ii/subsets.c @@ -1,3 +1,4 @@ +#include #include #include #include @@ -8,46 +9,39 @@ static inline int compare(const void *a, const void *b) return *(int *) a - *(int *) b; } -static void dfs(int *nums, int size, int start, int *buf, int level, - bool *used, int **sets, int *count, int *sizes) +static void dfs(int *nums, int size, int start, int *buf, + int level, int **sets, int *count, int *sizes) { - int i; + int i, last = INT_MIN; sets[*count] = malloc(level * sizeof(int)); memcpy(sets[*count], buf, level * sizeof(int)); sizes[*count] = level; (*count)++; for (i = start; i < size; i++) { - if (!used[i]) { - if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { - /* Forbid same elements on same level */ - /* Used marks allow same elements in different levels */ - continue; - } - used[i] = true; + if (last != nums[i]) { + /* No duplicate candidate elements at same level position */ buf[level] = nums[i]; - /* i + 1 limits the selecting range in following levels */ - dfs(nums, size, i + 1, buf, level + 1, used, sets, count, sizes); - used[i] = false; + /* i + 1 limits the selecting range in next levels */ + dfs(nums, size, i + 1, buf, level + 1, sets, count, sizes); } + last = nums[i]; } } /** ** Return an array of arrays of size *returnSize. ** The sizes of the arrays are returned as *returnColumnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) +static int** subsetsWithNoDup(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { qsort(nums, numsSize, sizeof(int), compare); int capacity = 5000; int **sets = malloc(capacity * sizeof(int *)); int *buf = malloc(numsSize * sizeof(int)); - bool *used = malloc(numsSize); - memset(used, false, numsSize); *returnColumnSizes = malloc(capacity * sizeof(int)); *returnSize = 0; - dfs(nums, numsSize, 0, buf, 0, used, sets, returnSize, *returnColumnSizes); + dfs(nums, numsSize, 0, buf, 0, sets, returnSize, *returnColumnSizes); return sets; } From 0b01a3d78b9f779efa0cc74af22782512c786997 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 28 Jul 2020 17:00:06 +0800 Subject: [PATCH 085/211] Refine Signed-off-by: begeekmyfriend --- 041_first_missing_positive/missing_positive.c | 9 ++- 042_trapping_rain_water/trap_water.c | 57 ++++++++----------- 043_multiply_strings/multiply_strings.c | 48 +++++----------- 3 files changed, 43 insertions(+), 71 deletions(-) diff --git a/041_first_missing_positive/missing_positive.c b/041_first_missing_positive/missing_positive.c index c047ef0..974263d 100644 --- a/041_first_missing_positive/missing_positive.c +++ b/041_first_missing_positive/missing_positive.c @@ -10,7 +10,7 @@ static inline void swap(int *a, int *b) static int firstMissingPositive(int* nums, int numsSize) { - if (numsSize < 1) { + if (numsSize == 0) { return 1; } @@ -18,7 +18,7 @@ static int firstMissingPositive(int* nums, int numsSize) while (i < numsSize) { /* nums[i] should be i+1 and nums[nums[i] - 1] should be nums[i] */ if (nums[i] != i + 1 && nums[i] > 0 && nums[i] <= numsSize && nums[nums[i] - 1] != nums[i]) { - /* nums[nums[i] - 1] <- nums[i] */ + /* let nums[nums[i] - 1] = nums[i] */ swap(nums + i, nums + nums[i] - 1); } else { i++; @@ -26,8 +26,11 @@ static int firstMissingPositive(int* nums, int numsSize) } for (i = 0; i < numsSize; i++) { - if (nums[i] != i + 1) break; + if (nums[i] != i + 1) { + break; + } } + return i + 1; } diff --git a/042_trapping_rain_water/trap_water.c b/042_trapping_rain_water/trap_water.c index 343b8b3..5f184e4 100644 --- a/042_trapping_rain_water/trap_water.c +++ b/042_trapping_rain_water/trap_water.c @@ -2,44 +2,33 @@ #include -static inline int max(int a, int b) -{ - return a > b ? a : b; -} - -static inline int min(int a, int b) -{ - return a < b ? a : b; -} - static int trap(int* height, int heightSize) { - if (heightSize < 1) { - return 0; - } - - int i; - int *lh = malloc(heightSize * sizeof(int)); - int *rh = malloc(heightSize * sizeof(int)); - - /* restore the max height in the left side of [i] (included) */ - lh[0] = height[0]; - for (i = 1; i < heightSize; i++) { - lh[i] = max(height[i], lh[i - 1]); - } - - /* restore the max height in the right side of [i] (included) */ - rh[heightSize - 1] = height[heightSize - 1]; - for (i = heightSize - 2; i >= 0; i--) { - rh[i] = max(height[i], rh[i + 1]); - } - - int capacity = 0; - for (i = 0; i < heightSize; i++) { - capacity += min(lh[i], rh[i]) - height[i]; + /* In fact if we find the relative higher bar position and then the + * water level of the position would be determined by the opposite side. + */ + int res = 0; + int l = 0, lmax = 0; + int r = heightSize - 1, rmax = 0; + while (l < r) { + if (height[l] < height[r]) { + if (height[l] > lmax) { + lmax = height[l]; + } else { + res += lmax - height[l]; + } + l++; + } else { + if (height[r] > rmax) { + rmax = height[r]; + } else { + res += rmax - height[r]; + } + r--; + } } - return capacity; + return res; } int main(int argc, char **argv) diff --git a/043_multiply_strings/multiply_strings.c b/043_multiply_strings/multiply_strings.c index 469014f..9143d10 100644 --- a/043_multiply_strings/multiply_strings.c +++ b/043_multiply_strings/multiply_strings.c @@ -2,58 +2,38 @@ #include #include -static void reverse(char *s, int len) -{ - int low = 0; - int high = len - 1; - while (low < high) { - char c = s[low]; - s[low] = s[high]; - s[high] = c; - low++; - high--; - } -} static char* multiply(char* num1, char* num2) { if (*num1 == '\0') { return num1; } + if (*num2 == '\0') { return num2; } int i, j; - char *result = malloc(110 + 110); - memset(result, '0', 220); int len1 = strlen(num1); int len2 = strlen(num2); - reverse(num1, len1); - reverse(num2, len2); - for (i = 0; i < len1; i++) { + char *result = malloc(len1 + len2 + 1); + memset(result, '0', len1 + len2 + 1); + result[len1 + len2] = '\0'; + + for (i = len2 - 1; i >= 0; i--) { int carry = 0; - for (j = 0; j < len2; j++) { - carry += (num1[i] - '0') * (num2[j] - '0') + (result[i + j] - '0'); - result[i + j] = carry % 10 + '0'; + for (j = len1 - 1; j >= 0; j--) { + carry += (num2[i] - '0') * (num1[j] - '0') + (result[i + j + 1] - '0'); + result[i + j + 1] = carry % 10 + '0'; carry /= 10; } - if (carry != 0) { - result[len2 + i] = carry + '0'; - } - } - int len = 220; - while (--len >= 0) { - if (result[len] > '0') { - result[++len] = '\0'; - break; - } + result[i + j + 1] = carry + '0'; } - if (len == -1) { - len = 1; - result[len] = '\0'; + + while (result[0] == '0' && result[1] != '\0') { + result++; } - reverse(result, len); + return result; } From c9882f6b1dafbd0ae8d60375f6cc230b13eec5e7 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 1 Aug 2020 22:02:51 +0800 Subject: [PATCH 086/211] Refine Signed-off-by: begeekmyfriend --- 044_wildcard_matching/wildcard_matching.c | 34 +++++++++++---------- 045_jump_game_ii/jump_game.c | 2 +- 048_rotate_image/rotate.c | 36 +++++++++++------------ 049_group_anagrams/anagrams.c | 11 +++---- 239_sliding_window_maximum/slide_window.c | 23 ++++++++------- 5 files changed, 56 insertions(+), 50 deletions(-) diff --git a/044_wildcard_matching/wildcard_matching.c b/044_wildcard_matching/wildcard_matching.c index c543e93..34dd54b 100644 --- a/044_wildcard_matching/wildcard_matching.c +++ b/044_wildcard_matching/wildcard_matching.c @@ -3,36 +3,40 @@ #include #include + static bool isMatch(char* s, char* p) { char *last_s = NULL; char *last_p = NULL; - while(*s != '\0') { - if (*p=='*'){ - //skip the "*", and mark a flag - p++; - //edge case - if (*p=='\0') return true; - //use last_s and last_p to store where the "*" match starts. + while (*s != '\0') { + if (*p == '*') { + /* skip the '*', and mark a flag */ + if (*++p == '\0') { + return true; + } + /* use last_s and last_p to store where the "*" match starts. */ last_s = s; last_p = p; - } else if (*p=='?' || *s == *p) { + } else if (*p == '?' || *s == *p) { s++; p++; } else if (last_s != NULL) { - // check "last_s" to know whether meet "*" before - // if meet "*" previously, and the *s != *p - // reset the p, using '*' to match this situation + /* check "last_s" to know whether meet "*" before + * if meet "*" previously, and the *s != *p + * reset the p, using '*' to match this situation + */ p = last_p; s = ++last_s; } else { - // *p is not wildcard char, - // doesn't match *s, - // there are no '*' wildcard matched before + /* *p is not wildcard char, + * doesn't match *s, + * there are no '*' wildcard matched before + */ return false; } } - //edge case: "s" is done, but "p" still have chars. + + /* s is done, but "p" still have chars. */ while (*p == '*') { p++; } diff --git a/045_jump_game_ii/jump_game.c b/045_jump_game_ii/jump_game.c index b6d2ed3..d315766 100644 --- a/045_jump_game_ii/jump_game.c +++ b/045_jump_game_ii/jump_game.c @@ -12,11 +12,11 @@ static int jump(int* nums, int numsSize) int steps = 0; while (hi < numsSize - 1) { int right = 0; - /* [lo, hi] is the next location range, find the farest jump */ for (i = lo; i <= hi; i++) { /* Assume right > hi for the purpose of the problem */ right = max(i + nums[i], right); } + /* [lo, hi] is the next location range */ lo = hi + 1; hi = right; steps++; diff --git a/048_rotate_image/rotate.c b/048_rotate_image/rotate.c index f5e6c79..b519ad9 100644 --- a/048_rotate_image/rotate.c +++ b/048_rotate_image/rotate.c @@ -1,47 +1,45 @@ #include #include -static void rotate(int** matrix, int matrixRowSize, int matrixColSize) +static void rotate(int** matrix, int matrixSize, int *matrixColSize) { int i, j; - if (matrixRowSize != matrixColSize) { - return; - } - - for (i = 0; i < matrixRowSize / 2; i++) { - int low = i, high = matrixColSize - i - 1; + for (i = 0; i < matrixSize / 2; i++) { + int col_size = matrixColSize[i]; + int low = i, high = col_size - i - 1; for (j = low; j < high; j++) { int tmp = matrix[i][j]; - matrix[i][j] = matrix[matrixColSize - 1 - j][i]; - matrix[matrixColSize - 1 - j][i] = matrix[matrixRowSize - 1 - i][matrixColSize - 1 - j]; - matrix[matrixRowSize - 1 - i][matrixColSize - 1 - j] = matrix[j][matrixRowSize - 1 - i]; - matrix[j][matrixRowSize - 1 - i] = tmp; + matrix[i][j] = matrix[col_size - 1 - j][i]; + matrix[col_size - 1 - j][i] = matrix[matrixSize - 1 - i][col_size - 1 - j]; + matrix[matrixSize - 1 - i][col_size - 1 - j] = matrix[j][matrixSize - 1 - i]; + matrix[j][matrixSize - 1 - i] = tmp; } } } int main(int argc, char **argv) { - if (argc != 3) { - fprintf(stderr, "Usage: ./test 3 3\n"); + if (argc != 2) { + fprintf(stderr, "Usage: ./test 3\n"); } int i, j, count = 0; int row_size = atoi(argv[1]); - int col_size = atoi(argv[2]); + int *col_sizes = malloc(row_size * sizeof(int)); int **matrix = malloc(row_size * sizeof(int *)); for (i = 0; i < row_size; i++) { - matrix[i] = malloc(col_size * sizeof(int)); - for (j = 0; j < col_size; j++) { + col_sizes[i] = row_size; + matrix[i] = malloc(col_sizes[i] * sizeof(int)); + for (j = 0; j < col_sizes[i]; j++) { matrix[i][j] = ++count; printf("%d ", matrix[i][j]); } printf("\n"); } - rotate(matrix, row_size, col_size); - for (i = 0; i < col_size; i++) { - for (j = 0; j < row_size; j++) { + rotate(matrix, row_size, col_sizes); + for (i = 0; i < row_size; i++) { + for (j = 0; j < col_sizes[i]; j++) { printf("%02d ", matrix[i][j]); } putchar('\n'); diff --git a/049_group_anagrams/anagrams.c b/049_group_anagrams/anagrams.c index 710b4d6..7838798 100644 --- a/049_group_anagrams/anagrams.c +++ b/049_group_anagrams/anagrams.c @@ -2,6 +2,7 @@ #include #include + struct word_hash { char *word; int num; @@ -25,10 +26,10 @@ static inline int BKDRHash(char *s, size_t size) /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** The sizes of the arrays are returned as *returnColumnSizes array. + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static char*** groupAnagrams(char** strs, int strsSize, int** columnSizes, int* returnSize) +static char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** returnColumnSizes) { int i, j, count = 0; int hash_size = strsSize; @@ -53,10 +54,10 @@ static char*** groupAnagrams(char** strs, int strsSize, int** columnSizes, int* int k = 0; struct hlist_node *p; char ***lists = malloc(count * sizeof(char **)); - *columnSizes = malloc(count * sizeof(int)); + *returnColumnSizes = malloc(count * sizeof(int)); for (i = 0; i < hash_size; i++) { if (ht[i].num > 0) { - (*columnSizes)[k] = ht[i].num; + (*returnColumnSizes)[k] = ht[i].num; lists[k] = malloc(ht[i].num * sizeof(char *)); for (j = 0; j < ht[i].num; j++) { int index = ht[i].indexes[j]; diff --git a/239_sliding_window_maximum/slide_window.c b/239_sliding_window_maximum/slide_window.c index 5f5011b..8fa5cbf 100644 --- a/239_sliding_window_maximum/slide_window.c +++ b/239_sliding_window_maximum/slide_window.c @@ -7,27 +7,30 @@ */ int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) { - int i, head = 0, tail = 0; + int i, left = 0, right = 0; int count = 0; int *indexes = malloc(numsSize * sizeof(int)); int *results = malloc((numsSize - k + 1) * sizeof(int)); for (i = 0; i < numsSize; i++) { /* keep the elements in slide window monotonous decreasing */ - while (tail > head && nums[i] >= nums[indexes[tail - 1]]) { + while (right > left && nums[i] >= nums[indexes[right - 1]]) { /* squeeze out the previous smaller ones */ - tail--; + right--; } - /* Pipe: first in last out */ - indexes[tail++] = i; - if (indexes[head] <= i - k) { - head++; - } + /* In order to measure the moving size of the sliding window, we + * need to store the index instead of element into the window. + */ + indexes[right++] = i; - /* k - 1 is the end of the first sliding window */ + /* let k = 1 to verify the corner case */ if (i >= k - 1) { - results[count++] = nums[indexes[head]]; + results[count++] = nums[indexes[left]]; + } + + if (i - indexes[left] + 1 >= k) { + left++; } } From bb658c39dd873065c740dd173aa7506613fc00c3 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 2 Aug 2020 07:34:25 +0800 Subject: [PATCH 087/211] Refine Signed-off-by: begeekmyfriend --- .../bst_preorder.c | 25 +++++----- .../bst_postorder.c | 49 ++++++++----------- 2 files changed, 32 insertions(+), 42 deletions(-) diff --git a/144_binary_tree_preorder_traversal/bst_preorder.c b/144_binary_tree_preorder_traversal/bst_preorder.c index a639003..a5372fa 100644 --- a/144_binary_tree_preorder_traversal/bst_preorder.c +++ b/144_binary_tree_preorder_traversal/bst_preorder.c @@ -21,24 +21,21 @@ static int* preorderTraversal(struct TreeNode* root, int* returnSize) int *results = malloc(cap * sizeof(int)); struct TreeNode **stack = malloc(cap / 16 * sizeof(*stack)); struct TreeNode **top = stack; - struct TreeNode *node = root; - /* node != NULL condition is just for the first iteration and + /* root != NULL condition is just for the first iteration and * never push NULL into the stack */ - while (node != NULL || top != stack) { - if (node == NULL) { - /* pop up */ - node = *--top; + while (root != NULL || top != stack) { + if (root != NULL) { + results[count++] = root->val; + /* store the parent node */ + *top++ = root; + root = root->left; + } else { + /* pop up the parent node */ + root = *--top; + root = root->right; } - - results[count++] = node->val; - - if (node->right != NULL) { - *top++ = node->right; - } - - node = node->left; } *returnSize = count; diff --git a/145_binary_tree_postorder_traversal/bst_postorder.c b/145_binary_tree_postorder_traversal/bst_postorder.c index e54d3a8..47f49d8 100644 --- a/145_binary_tree_postorder_traversal/bst_postorder.c +++ b/145_binary_tree_postorder_traversal/bst_postorder.c @@ -12,50 +12,43 @@ struct node_backlog { struct TreeNode *right; }; -static int counting(struct TreeNode* node) -{ - if (node == NULL) { - return 0; - } - return 1 + counting(node->left) + counting(node->right); -} - /** ** Return an array of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ static int* postorderTraversal(struct TreeNode* root, int* returnSize) { - if (root == NULL) { - return NULL; - } - - *returnSize = counting(root); - int count = 0; - int *results = malloc(*returnSize * sizeof(int)); - struct node_backlog *stack = malloc(*returnSize * sizeof(*stack)); + int *results = malloc(100 * sizeof(int)); + struct node_backlog *stack = malloc(100 * sizeof(*stack)); struct node_backlog *top = stack; - struct TreeNode *node = root; - while (node != NULL || top != stack) { - if (node == NULL) { + /* root != NULL condition is just for the first iteration and + * never push NULL into the stack + */ + while (root != NULL || top != stack) { + if (root != NULL) { + /* push both parent and its right child */ + top->parent = root; + top->right = root->right; + top++; + root = root->left; + } else { if ((top - 1)->right != NULL) { - node = (top - 1)->right; + /* switch to right child but not pop up the parent */ + root = (top - 1)->right; + /* avoid infinite loop */ (top - 1)->right = NULL; } else { - node = (--top)->parent; - results[count++] = node->val; - node = NULL; - continue; + root = (--top)->parent; + results[count++] = root->val; + /* we need to backtrace */ + root = NULL; } } - top->parent = node; - top->right = node->right; - top++; - node = node->left; } + *returnSize = count; return results; } From 84b500ea9ce673491b11e50be61fe262a38313ad Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 3 Aug 2020 23:21:02 +0800 Subject: [PATCH 088/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 036_valid_sudoku/valid_sudoku.cc | 58 ++++++++++++++++ 037_sudoku_solver/sudoku_solver.cc | 67 +++++++++++++++++++ 039_combination_sum/combination_sum.cc | 29 ++++++++ 040_combination_sum_ii/combination_sum.cc | 35 ++++++++++ .../missing_positive.cc | 31 +++++++++ 042_trapping_rain_water/trap_water.cc | 34 ++++++++++ 043_multiply_strings/multiply_strings.cc | 27 ++++++++ 045_jump_game_ii/jump_game.cc | 24 +++++++ 046_permutations/permutations.cc | 31 +++++++++ 047_permutations_ii/permutations.cc | 37 ++++++++++ 048_rotate_image/rotate.cc | 20 ++++++ 049_group_anagrams/anagrams.cc | 30 +++++++++ 050_pow/pow.cc | 27 ++++++++ 072_edit_distance/edit_distance.cc | 29 ++++++++ 077_combinations/combinations.cc | 26 +++++++ 078_subsets/subsets.cc | 23 +++++++ 090_subsets_ii/subsets.cc | 29 ++++++++ 230_kth_smallest_element_in_a_bst/kth_bst.cc | 38 +++++++++++ 239_sliding_window_maximum/slide_window.cc | 29 ++++++++ 19 files changed, 624 insertions(+) create mode 100644 036_valid_sudoku/valid_sudoku.cc create mode 100644 037_sudoku_solver/sudoku_solver.cc create mode 100644 039_combination_sum/combination_sum.cc create mode 100644 040_combination_sum_ii/combination_sum.cc create mode 100644 041_first_missing_positive/missing_positive.cc create mode 100644 042_trapping_rain_water/trap_water.cc create mode 100644 043_multiply_strings/multiply_strings.cc create mode 100644 045_jump_game_ii/jump_game.cc create mode 100644 046_permutations/permutations.cc create mode 100644 047_permutations_ii/permutations.cc create mode 100644 048_rotate_image/rotate.cc create mode 100644 049_group_anagrams/anagrams.cc create mode 100644 050_pow/pow.cc create mode 100644 072_edit_distance/edit_distance.cc create mode 100644 077_combinations/combinations.cc create mode 100644 078_subsets/subsets.cc create mode 100644 090_subsets_ii/subsets.cc create mode 100644 230_kth_smallest_element_in_a_bst/kth_bst.cc create mode 100644 239_sliding_window_maximum/slide_window.cc diff --git a/036_valid_sudoku/valid_sudoku.cc b/036_valid_sudoku/valid_sudoku.cc new file mode 100644 index 0000000..02fb8e6 --- /dev/null +++ b/036_valid_sudoku/valid_sudoku.cc @@ -0,0 +1,58 @@ +#include + +using namespace std; + +class Solution { +public: + bool isValidSudoku(vector>& board) { + /* check row validity */ + for (int i = 0; i < board.size(); i++) { + vector mark(10); + /* check row validity */ + for (int j = 0; j < board.size(); j++) { + if (!valid(board, mark, i, j)) { + return false; + } + } + } + + /* check column validity */ + for (int j = 0; j < board.size(); j++) { + vector mark(10); + for (int i = 0; i < board.size(); i++) { + if (!valid(board, mark, i, j)) { + return false; + } + } + } + + /* check sub-box validity */ + for (int k = 0; k < board.size(); k++) { + int sr = k / 3 * 3; + int sc = (k % 3) * 3; + vector mark(10); + for (int i = sr; i < sr + 3; i++) { + for (int j = sc; j < sc + 3; j++) { + if (!valid(board, mark, i, j)) { + return false; + } + } + } + } + + return true; + } + +private: + bool valid(vector>& board, vector& mark, int i, int j) { + if (board[i][j] != '.') { + int index = board[i][j] - '0'; + if (mark[index]) { + return false; + } else { + mark[index] = 1; + } + } + return true; + } +}; diff --git a/037_sudoku_solver/sudoku_solver.cc b/037_sudoku_solver/sudoku_solver.cc new file mode 100644 index 0000000..1f6503e --- /dev/null +++ b/037_sudoku_solver/sudoku_solver.cc @@ -0,0 +1,67 @@ +#include + +using namespace std; + +class Solution { +public: + void solveSudoku(vector>& board) { + int size = board.size(); + vector> rows(size, vector(10)); + vector> cols(size, vector(10)); + vector> boxes(size, vector(10)); + + for (int i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + if (board[i][j] != '.') { + int num = board[i][j] - '0'; + int idx = i / 3 * 3 + j / 3; + rows[i][num] = true; + cols[j][num] = true; + boxes[idx][num] = true; + } + } + } + + dfs(board, 0, rows, cols, boxes); + } + +private: + bool valid(int num, int row, int col, int idx, vector>& rows, + vector>& cols, vector>& boxes) { + return !rows[row][num] && !cols[col][num] && !boxes[idx][num]; + } + + bool dfs(vector>& board, int size, vector>& rows, + vector>& cols, vector>& boxes) { + if (size == 9 * 9) { + return true; + } else { + bool ok = false; + int row = size / 9; + int col = size % 9; + int idx = row / 3 * 3 + col / 3; + if (board[row][col] == '.') { + for (int i = 1; i <= 9; i++) { + if (valid(i, row, col, idx, rows, cols, boxes)) { + /* lock this grid as well as the number */ + board[row][col] = i + '0'; + rows[row][i] = true; + cols[col][i] = true; + boxes[idx][i] = true; + ok = dfs(board, size + 1, rows, cols, boxes); + if (!ok) { + /* release this grid as well as the number */ + rows[row][i] = false; + cols[col][i] = false; + boxes[idx][i] = false; + board[row][col] = '.'; + } + } + } + } else { + ok = dfs(board, size + 1, rows, cols, boxes); + } + return ok; + } + } +}; diff --git a/039_combination_sum/combination_sum.cc b/039_combination_sum/combination_sum.cc new file mode 100644 index 0000000..11afede --- /dev/null +++ b/039_combination_sum/combination_sum.cc @@ -0,0 +1,29 @@ +#include + +using namespace std; + +class Solution { +public: + vector> combinationSum(vector& candidates, int target) { + vector stack; + vector> res; + dfs(candidates, 0, target, stack, res); + return res; + } + +private: + void dfs(vector& candidates, int start, int target, vector& stack, vector>& res) { + if (target < 0) { + return; + } else if (target == 0) { + res.push_back(stack); + } 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 */ + dfs(candidates, i, target - candidates[i], stack, res); + stack.pop_back(); + } + } + } +}; diff --git a/040_combination_sum_ii/combination_sum.cc b/040_combination_sum_ii/combination_sum.cc new file mode 100644 index 0000000..548c782 --- /dev/null +++ b/040_combination_sum_ii/combination_sum.cc @@ -0,0 +1,35 @@ +#include + +using namespace std; + +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + vector stack; + vector> res; + sort(candidates.begin(), candidates.end()); + dfs(candidates, 0, target, stack, res); + return res; + } + +private: + void dfs(vector& candidates, int start, int target, vector& stack, vector>& res) { + if (target < 0) { + return; + } else if (target == 0) { + res.push_back(stack); + } else { + int last = -1; + for (int i = start; i < candidates.size(); i++) { + if (last != candidates[i]) { + /* No duplicate combinations in different order */ + stack.push_back(candidates[i]); + /* i + 1 limits the candidate range in next levels */ + dfs(candidates, i + 1, target - candidates[i], stack, res); + stack.pop_back(); + } + last = candidates[i]; + } + } + } +}; diff --git a/041_first_missing_positive/missing_positive.cc b/041_first_missing_positive/missing_positive.cc new file mode 100644 index 0000000..4058980 --- /dev/null +++ b/041_first_missing_positive/missing_positive.cc @@ -0,0 +1,31 @@ +#include + +using namespace std; + +class Solution { +public: + int firstMissingPositive(vector& nums) { + if (nums.size() == 0) { + return 1; + } + + int i = 0; + while (i < nums.size()) { + /* nums[i] should be i+1 and nums[nums[i] - 1] should be nums[i] */ + if (nums[i] > 0 && nums[i] != i + 1 && nums[i] - 1 < nums.size() && nums[nums[i] - 1] != nums[i]) { + // Let nums[nums[i] - 1] = nums[i] + swap(nums[i], nums[nums[i] - 1]); + } else { + i++; + } + } + + for (i = 0; i < nums.size(); i++) { + if (nums[i] != i + 1) { + break; + } + } + + return i + 1; + } +}; diff --git a/042_trapping_rain_water/trap_water.cc b/042_trapping_rain_water/trap_water.cc new file mode 100644 index 0000000..42be139 --- /dev/null +++ b/042_trapping_rain_water/trap_water.cc @@ -0,0 +1,34 @@ +#include + +using namespace std; + +class Solution { +public: + int trap(vector& height) { + /* In fact if we find the relative higher bar position and then the + * 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]) { + if (height[left] > left_max) { + left_max = height[left]; + } else { + res += left_max - height[left]; + } + left++; + } else { + if (height[right] > right_max) { + right_max = height[right]; + } else { + res += right_max - height[right]; + } + right--; + } + } + + return res; + } +}; diff --git a/043_multiply_strings/multiply_strings.cc b/043_multiply_strings/multiply_strings.cc new file mode 100644 index 0000000..77436e4 --- /dev/null +++ b/043_multiply_strings/multiply_strings.cc @@ -0,0 +1,27 @@ +#include + +using namespace std; + +class Solution { +public: + string multiply(string num1, string num2) { + string res(num1.length() + num2.length(), '0'); + for (int i = num2.length() - 1; i >= 0; i--) { + int j, carry = 0; + for (j = num1.length() - 1; j >= 0; j--) { + carry += (num1[j] - '0') * (num2[i] - '0') + (res[i + j + 1] - '0'); + res[i + j + 1] = carry % 10 + '0'; + carry /= 10; + } + res[i + j + 1] = carry + '0'; + } + + int i; + for (i = 0; i < res.length() - 1; i++) { + if (res[i] != '0') { + break; + } + } + return res.substr(i); + } +}; diff --git a/045_jump_game_ii/jump_game.cc b/045_jump_game_ii/jump_game.cc new file mode 100644 index 0000000..77e6f2f --- /dev/null +++ b/045_jump_game_ii/jump_game.cc @@ -0,0 +1,24 @@ +#include + +using namespace std; + +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); + } + // [lo, hi] is the next location range + lo = hi + 1; + hi = right; + steps++; + } + + return steps; + } +}; diff --git a/046_permutations/permutations.cc b/046_permutations/permutations.cc new file mode 100644 index 0000000..48038c0 --- /dev/null +++ b/046_permutations/permutations.cc @@ -0,0 +1,31 @@ +#include + +using namespace std; + +class Solution { +public: + vector> permute(vector& nums) { + vector> res; + vector stack; + vector used(nums.size()); + dfs(nums, used, stack, res); + return res; + } + +private: + void dfs(vector& nums, vector& used, vector& stack, vector>& res) { + if (stack.size() == nums.size()) { + res.push_back(stack); + } else { + for (int i = 0; i < nums.size(); i++) { + if (!used[i]) { + used[i] = true; + stack.push_back(nums[i]); + dfs(nums, used, stack, res); + stack.pop_back(); + used[i] = false; + } + } + } + } +}; diff --git a/047_permutations_ii/permutations.cc b/047_permutations_ii/permutations.cc new file mode 100644 index 0000000..23eca7c --- /dev/null +++ b/047_permutations_ii/permutations.cc @@ -0,0 +1,37 @@ +#include + +using namespace std; + +class Solution { +public: + vector> permuteUnique(vector& nums) { + vector> res; + vector stack; + vector used(nums.size()); + sort(nums.begin(), nums.end()); + dfs(nums, used, stack, res); + return res; + } + +private: + void dfs(vector& nums, vector& used, vector& stack, vector>& res) { + if (stack.size() == nums.size()) { + res.push_back(stack); + } else { + for (int i = 0; i < nums.size(); i++) { + if (!used[i]) { + if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { + /* In case that duplicate permutation with same elemements */ + /* Used marks allow same elements in different DFS levels */ + continue; + } + used[i] = true; + stack.push_back(nums[i]); + dfs(nums, used, stack, res); + stack.pop_back(); + used[i] = false; + } + } + } + } +}; diff --git a/048_rotate_image/rotate.cc b/048_rotate_image/rotate.cc new file mode 100644 index 0000000..e1e9950 --- /dev/null +++ b/048_rotate_image/rotate.cc @@ -0,0 +1,20 @@ +#include + +using namespace std; + +class Solution { +public: + void rotate(vector>& matrix) { + int size = matrix.size(); + for (int i = 0; i < size / 2; i++) { + int low = i, high = size - i - 1; + for (int j = low; j < high; j++) { + int tmp = matrix[i][j]; + matrix[i][j] = matrix[size - 1 - j][i]; + matrix[size - 1 - j][i] = matrix[size - 1 - i][size - 1 - j]; + matrix[size - 1 - i][size - 1 - j] = matrix[j][size - 1 - i]; + matrix[j][size - 1 - i] = tmp; + } + } + } +}; diff --git a/049_group_anagrams/anagrams.cc b/049_group_anagrams/anagrams.cc new file mode 100644 index 0000000..c90a7f6 --- /dev/null +++ b/049_group_anagrams/anagrams.cc @@ -0,0 +1,30 @@ +#include + +using namespace std; + +class Solution { +public: + vector> groupAnagrams(vector& strs) { + vector> res; + unordered_map> ht; + for (const auto& str : strs) { + int counts[26] = { 0 }; + for (const auto& s : str) { + counts[s - 'a']++; + } + + string key; + for (const auto& c : counts) { + key.push_back('#'); + key.push_back(c + '0'); + } + + ht[key].push_back(str); + } + + for (const auto& t : ht) { + res.push_back(t.second); + } + return res; + } +}; diff --git a/050_pow/pow.cc b/050_pow/pow.cc new file mode 100644 index 0000000..1b925cb --- /dev/null +++ b/050_pow/pow.cc @@ -0,0 +1,27 @@ +#include + +using namespace std; + +class Solution { +public: + double myPow(double x, int n) { + if (n == INT_MIN) { + double t = dfs(x, -(n / 2)); + return 1 / t * 1 / t; + } else { + return n < 0 ? 1 / dfs(x, -n) : dfs(x, n); + } + } + +private: + double dfs(double x, int n) { + if (n == 0) { + return 1; + } else if (n == 1) { + return x; + } else { + double t = dfs(x, n / 2); + return (n % 2) ? (x * t * t) : (t * t); + } + } +}; diff --git a/072_edit_distance/edit_distance.cc b/072_edit_distance/edit_distance.cc new file mode 100644 index 0000000..b7c6bb5 --- /dev/null +++ b/072_edit_distance/edit_distance.cc @@ -0,0 +1,29 @@ +#include + +using namespace std; + +class Solution { +public: + int minDistance(string word1, string word2) { + vector> dp; + for (int i = 0; i <= word1.length(); i++) { + dp.push_back(vector(word2.length() + 1)); + dp[i][0] = i; + } + for (int i = 0; i <= word2.length(); i++) { + dp[0][i] = i; + } + + for (int i = 1; i <= word1.length(); i++) { + for (int j = 1; j <= word2.length(); j++) { + if (word1[i - 1] == word2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])); + } + } + } + + return dp[word1.length()][word2.length()]; + } +}; diff --git a/077_combinations/combinations.cc b/077_combinations/combinations.cc new file mode 100644 index 0000000..7687061 --- /dev/null +++ b/077_combinations/combinations.cc @@ -0,0 +1,26 @@ +#include + +using namespace std; + +class Solution { +public: + vector> combine(int n, int k) { + vector> res; + vector stack; + dfs(n, k, 1, stack, res); + return res; + } + +private: + void dfs(int n, int k, int start, vector& stack, vector>& res) { + if (stack.size() == k) { + res.push_back(stack); + } else { + for (int i = start; i <= n; i++) { + stack.push_back(i); + dfs(n, k, i + 1, stack, res); + stack.pop_back(); + } + } + } +}; diff --git a/078_subsets/subsets.cc b/078_subsets/subsets.cc new file mode 100644 index 0000000..5d10d7e --- /dev/null +++ b/078_subsets/subsets.cc @@ -0,0 +1,23 @@ +#include + +using namespace std; + +class Solution { +public: + vector> subsets(vector& nums) { + vector> res; + vector stack; + dfs(nums, 0, stack, res); + return res; + } + +private: + void dfs(vector& nums, int start, vector& stack, vector>& res) { + res.push_back(stack); + for (int i = start; i < nums.size(); i++) { + stack.push_back(nums[i]); + dfs(nums, i + 1, stack, res); + stack.pop_back(); + } + } +}; diff --git a/090_subsets_ii/subsets.cc b/090_subsets_ii/subsets.cc new file mode 100644 index 0000000..f5ae3e9 --- /dev/null +++ b/090_subsets_ii/subsets.cc @@ -0,0 +1,29 @@ +#include + +using namespace std; + +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + vector> res; + vector stack; + sort(nums.begin(), nums.end()); + dfs(nums, 0, stack, res); + return res; + } + +private: + void dfs(vector& nums, int start, vector& stack, vector>& res) { + res.push_back(stack); + int last = INT_MIN; + for (int i = start; i < nums.size(); i++) { + if (last != nums[i]) { + /* No duplicate candidate elements at same level position */ + stack.push_back(nums[i]); + dfs(nums, i + 1, stack, res); + stack.pop_back(); + } + last = nums[i]; + } + } +}; diff --git a/230_kth_smallest_element_in_a_bst/kth_bst.cc b/230_kth_smallest_element_in_a_bst/kth_bst.cc new file mode 100644 index 0000000..ac6587f --- /dev/null +++ b/230_kth_smallest_element_in_a_bst/kth_bst.cc @@ -0,0 +1,38 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + stack stk; + while (!stk.empty() || root != NULL) { + if (root != NULL) { + /* Store the parent node */ + stk.push(root); + root = root->left; + } else { + /* Pop up the parent node */ + root = stk.top(); + if (--k == 0) { + break; + } + stk.pop(); + root = root->right; + } + } + + return root->val; + } +}; diff --git a/239_sliding_window_maximum/slide_window.cc b/239_sliding_window_maximum/slide_window.cc new file mode 100644 index 0000000..35b3aad --- /dev/null +++ b/239_sliding_window_maximum/slide_window.cc @@ -0,0 +1,29 @@ +#include + +using namespace std; + +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + vector res; + // In order to measure the moving size of the sliding window, we + // need to store the index instead of element into the window. + vector indexes(nums.size()); + int left = 0, right = 0; + for (int i = 0; i < nums.size(); i++) { + while (right > left && nums[i] >= nums[indexes[right - 1]]) { + right--; + } + indexes[right++] = i; + + if (i >= k - 1) { + res.push_back(nums[indexes[left]]); + } + + if (i - indexes[left] + 1 >= k) { + left++; + } + } + return res; + } +}; From e9af0396ab50d4dd978a0e204477255bf9b4b8a3 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 4 Aug 2020 16:27:52 +0800 Subject: [PATCH 089/211] Refine Signed-off-by: begeekmyfriend --- .../kth_elem.c | 49 +++++++++++++++++-- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/215_kth_largest_element_in_an_array/kth_elem.c b/215_kth_largest_element_in_an_array/kth_elem.c index 208050f..730fc86 100644 --- a/215_kth_largest_element_in_an_array/kth_elem.c +++ b/215_kth_largest_element_in_an_array/kth_elem.c @@ -1,14 +1,53 @@ #include #include -static int compare(const void *a, const void *b) +static inline void swap(int *a, int *b) { - return *(int *) a - *(int *) b; + int t = *a; + *a = *b; + *b = t; } -int findKthLargest(int* nums, int numsSize, int k) { - qsort(nums, numsSize, sizeof(int), compare); - return nums[numsSize - k]; +static int partition(int *nums, int lo, int hi) +{ + if (lo >= hi) { + return hi; + } + + int i = lo; + int j = hi - 1; + int pivot = nums[hi]; + while (i <= j) { + while (i <= j && nums[i] <= pivot) { i++; } + while (i <= j && nums[j] > pivot) { j--; } + if (i < j) { + swap(nums + i, nums + j); + } + } + /* Loop invariant: j + 1 == i && nums[j] <= pivot && nums[i] > pivot + * Besides, j could be -1 or i could be hi, so we swap [i] and [hi] + */ + swap(nums + i, nums + hi); + return i; +} + +int findKthLargest(int* nums, int numsSize, int k) +{ + int lo = 0, hi = numsSize - 1; + for (; ;) { + printf("A:%d %d\n", lo, hi); + int p = partition(nums, lo, hi); + printf("B:%d %d\n", p, numsSize - k); + if (p < numsSize - k) { + lo = p + 1; + } else if (p > numsSize - k) { + hi = p - 1; + } else { + lo = p; + break; + } + } + return nums[lo]; } From 6d3f3c57c6eef9b6f79cc5100465f4d755a77559 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 5 Aug 2020 08:20:35 +0800 Subject: [PATCH 090/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 179_largest_number/largest_number.c | 6 ++--- 179_largest_number/largest_number.cc | 26 +++++++++++++++++++ .../kth_elem.cc | 19 ++++++++++++++ 3 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 179_largest_number/largest_number.cc create mode 100644 215_kth_largest_element_in_an_array/kth_elem.cc diff --git a/179_largest_number/largest_number.c b/179_largest_number/largest_number.c index 6eb31f3..3dba0a8 100644 --- a/179_largest_number/largest_number.c +++ b/179_largest_number/largest_number.c @@ -8,10 +8,8 @@ struct object { static int compare(const void *o1, const void *o2) { - char p1[32]; - char p2[32]; - p1[0] = '\0'; - p2[0] = '\0'; + char p1[32] = { '\0' }; + char p2[32] = { '\0' }; strcat(p1, ((struct object *) o1)->buf); strcat(p1, ((struct object *) o2)->buf); strcat(p2, ((struct object *) o2)->buf); diff --git a/179_largest_number/largest_number.cc b/179_largest_number/largest_number.cc new file mode 100644 index 0000000..7b8a5aa --- /dev/null +++ b/179_largest_number/largest_number.cc @@ -0,0 +1,26 @@ +#include + +using namespace std; + +class Solution { +public: + string largestNumber(vector& nums) { + vector strs; + for (const auto i : nums) { + strs.push_back(to_string(i)); + } + + auto cmp = [](string s1, string s2) { return s1 + s2 > s2 + s1; }; + sort(strs.begin(), strs.end(), cmp); + + if (strs[0] == "0") { + return "0"; + } + + string res; + for (const auto& s : strs) { + res += s; + } + return res; + } +}; diff --git a/215_kth_largest_element_in_an_array/kth_elem.cc b/215_kth_largest_element_in_an_array/kth_elem.cc new file mode 100644 index 0000000..135114e --- /dev/null +++ b/215_kth_largest_element_in_an_array/kth_elem.cc @@ -0,0 +1,19 @@ +#include + +using namespace std; + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + priority_queue, greater> queue; + for (const auto i : nums) { + if (queue.size() < k) { + queue.push(i); + } else if (i > queue.top()) { + queue.pop(); + queue.push(i); + } + } + return queue.top(); + } +}; From f1d04274d79ea4ce13079137e68642dd2581a1b4 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 6 Aug 2020 23:49:02 +0800 Subject: [PATCH 091/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 146_lru_cache/lru_cache.cc | 50 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 146_lru_cache/lru_cache.cc diff --git a/146_lru_cache/lru_cache.cc b/146_lru_cache/lru_cache.cc new file mode 100644 index 0000000..1f8230a --- /dev/null +++ b/146_lru_cache/lru_cache.cc @@ -0,0 +1,50 @@ +#include + +using namespace std; + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache* obj = new LRUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); + */ +class LRUCache { +public: + LRUCache(int capacity) { + capacity_ = capacity; + } + + int get(int key) { + if (ht_.find(key) == ht_.end()) { + return -1; + } + + int value = ht_[key]->second; + if (li_.front().second != value) { + li_.erase(ht_[key]); + li_.push_front(make_pair(key, value)); + ht_[key] = li_.begin(); // iterator failure + } + + return value; + } + + void put(int key, int value) { + if (ht_.find(key) != ht_.end()) { + li_.erase(ht_[key]); + } else { + if (li_.size() == capacity_) { + auto lru = li_.back(); + li_.pop_back(); + ht_.erase(lru.first); + } + } + li_.push_front(make_pair(key, value)); + ht_[key] = li_.begin(); // iterator failure + } + +private: + int capacity_; + list> li_; + unordered_map::iterator> ht_; +}; From 82f53c39c0a606aaad2e526398861ab7732485e5 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 7 Aug 2020 16:22:40 +0800 Subject: [PATCH 092/211] Refine Signed-off-by: begeekmyfriend --- 226_invert_binary_tree/invert_binary_tree.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/226_invert_binary_tree/invert_binary_tree.c b/226_invert_binary_tree/invert_binary_tree.c index 36b0cad..7efae0d 100644 --- a/226_invert_binary_tree/invert_binary_tree.c +++ b/226_invert_binary_tree/invert_binary_tree.c @@ -10,13 +10,14 @@ struct TreeNode { static struct TreeNode *invertTree(struct TreeNode* root) { - if (root != NULL) { - struct TreeNode *node = root->left; - root->left = root->right; - root->right = node; - invertTree(root->left); - invertTree(root->right); + if (root == NULL) { + return NULL; } + + struct TreeNode *l = invertTree(root->left); + struct TreeNode *r = invertTree(root->right); + root->left = r; + root->right = l; return root; } From a209eaa78ed4b10baf633219633809b49d1e2c6a Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 8 Aug 2020 16:57:15 +0800 Subject: [PATCH 093/211] Refine Signed-off-by: begeekmyfriend --- 069_sqrt/sqrt.c | 57 +++++++++++++++++++++++++++++++++++++-- 100_same_tree/same_tree.c | 2 +- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/069_sqrt/sqrt.c b/069_sqrt/sqrt.c index 1d3a5c3..5d35df4 100644 --- a/069_sqrt/sqrt.c +++ b/069_sqrt/sqrt.c @@ -1,6 +1,55 @@ +#include #include #include +#if 0 +static double mySqrt(double x) +{ + double lo = 0; + double hi = x; + double diff = 1e-8; + double mid = (lo + hi) / 2; + while (fabs(mid * mid - x) > diff) { + if (mid < x / mid) { + lo = mid; + } else if (mid > x / mid) { + hi = mid; + } else { + break; + } + mid = (lo + hi) / 2; + } + + return mid; +} + +static double mySqrt(double n) +{ + /* Solute the zero point of f(x) = 0 => x ^ 2 - n = 0 */ + /* f(x) = (x - x0)f'(x0) - f(x0) = 0 First order of Tylor series */ + double x = 1.0; + while (fabs(x * x - n) > 1e-8) { + x = x - (x * x - n) / (2 * x); + } + return x; +} + +static double mySqrt(double n) +{ + /* Gradient descent + * MSE Loss = (x * x - n) ^ 2 + * G = 4 * x ^ 3 - 4 * n * x + * x = x - a * G + */ + double a = 1e-4; + double x = 1.0; + while (fabs(x * x - n) > 1e-8) { + x = x - a * 4 * x * (x * x - n); + } + return x; +} +#endif + static int mySqrt(int x) { if (x == 0) { @@ -9,18 +58,21 @@ static int mySqrt(int x) unsigned int left = 1; unsigned int right = (unsigned int) x; + unsigned int mid = left + (right - left) / 2; for (; ;) { - unsigned int mid = left + (right - left) / 2; if (mid > x/mid) { right = mid; } else { if (mid + 1 > x/(mid + 1)) { - return mid; + break; } else { left = mid; } } + mid = left + (right - left) / 2; } + + return mid; } int main(int argc, char **argv) @@ -30,6 +82,7 @@ int main(int argc, char **argv) exit(-1); } + //printf("%f\n", mySqrt(1.5));//atoi(argv[1]))); printf("%d\n", mySqrt(atoi(argv[1]))); return 0; } diff --git a/100_same_tree/same_tree.c b/100_same_tree/same_tree.c index 36bc7bb..3786053 100644 --- a/100_same_tree/same_tree.c +++ b/100_same_tree/same_tree.c @@ -19,7 +19,7 @@ static bool isSameTree(struct TreeNode* p, struct TreeNode* q) } if (!isSameTree(p->right, q->right)) { return false; - } + } } else { return p == q; } From 10dee49908718bb8cfce2484b57621c03801d774 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 8 Aug 2020 17:02:37 +0800 Subject: [PATCH 094/211] Refine Signed-off-by: begeekmyfriend --- 069_sqrt/sqrt.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/069_sqrt/sqrt.c b/069_sqrt/sqrt.c index 5d35df4..cb9a70f 100644 --- a/069_sqrt/sqrt.c +++ b/069_sqrt/sqrt.c @@ -29,7 +29,8 @@ static double mySqrt(double n) /* f(x) = (x - x0)f'(x0) - f(x0) = 0 First order of Tylor series */ double x = 1.0; while (fabs(x * x - n) > 1e-8) { - x = x - (x * x - n) / (2 * x); + // x = x - (x * x - n) / (2 * x); + x = (x - n / x) / 2; } return x; } From 486b52f609bf8a39a6d13fc82ccdf21760da1fd1 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 15 Aug 2020 17:03:08 +0800 Subject: [PATCH 095/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../kth_elem.c | 27 +++++++------------ 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/215_kth_largest_element_in_an_array/kth_elem.c b/215_kth_largest_element_in_an_array/kth_elem.c index 730fc86..c82ef02 100644 --- a/215_kth_largest_element_in_an_array/kth_elem.c +++ b/215_kth_largest_element_in_an_array/kth_elem.c @@ -1,12 +1,6 @@ #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) { @@ -15,19 +9,18 @@ static int partition(int *nums, int lo, int hi) } int i = lo; - int j = hi - 1; + int j = hi; int pivot = nums[hi]; - while (i <= j) { - while (i <= j && nums[i] <= pivot) { i++; } - while (i <= j && nums[j] > pivot) { j--; } - if (i < j) { - swap(nums + i, nums + j); - } + 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]; } - /* Loop invariant: j + 1 == i && nums[j] <= pivot && nums[i] > pivot - * Besides, j could be -1 or i could be hi, so we swap [i] and [hi] - */ - swap(nums + i, nums + hi); + /* Loop invariant: i == j */ + nums[i] = pivot; return i; } From ff9b73407e67efcff06f0ed9e756e4b18c805cd1 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 17 Aug 2020 17:12:21 +0800 Subject: [PATCH 096/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 141_linked_list_cycle/list_cycle.c | 15 ++++----- 141_linked_list_cycle/list_cycle.cc | 27 +++++++++++++++++ 142_linked_list_cycle_ii/list_cycle.c | 25 +++++++-------- 142_linked_list_cycle_ii/list_cycle.cc | 32 ++++++++++++++++++++ 226_invert_binary_tree/invert_binary_tree.cc | 29 ++++++++++++++++++ 5 files changed, 105 insertions(+), 23 deletions(-) create mode 100644 141_linked_list_cycle/list_cycle.cc create mode 100644 142_linked_list_cycle_ii/list_cycle.cc create mode 100644 226_invert_binary_tree/invert_binary_tree.cc diff --git a/141_linked_list_cycle/list_cycle.c b/141_linked_list_cycle/list_cycle.c index 1b16d87..d1a283c 100644 --- a/141_linked_list_cycle/list_cycle.c +++ b/141_linked_list_cycle/list_cycle.c @@ -9,17 +9,14 @@ struct ListNode { static bool hasCycle(struct ListNode *head) { - if (head == NULL || head->next == NULL) { - return false; - } - - bool first = true; - struct ListNode *p0, *p1; - for (p0 = head, p1 = head; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) { - if (p0 == p1 && !first) { + struct ListNode *fast = head; + struct ListNode *slow = head; + while (fast != NULL && fast->next != NULL) { + slow = slow->next; + fast = fast->next->next; + if (fast == slow) { return true; } - first = false; } return false; diff --git a/141_linked_list_cycle/list_cycle.cc b/141_linked_list_cycle/list_cycle.cc new file mode 100644 index 0000000..e44cf0e --- /dev/null +++ b/141_linked_list_cycle/list_cycle.cc @@ -0,0 +1,27 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + struct ListNode *fast = head; + struct ListNode *slow = head; + while (fast != nullptr && fast->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + if (fast == slow) { + return true; + } + } + return false; + } +}; diff --git a/142_linked_list_cycle_ii/list_cycle.c b/142_linked_list_cycle_ii/list_cycle.c index d8f55bc..9840230 100644 --- a/142_linked_list_cycle_ii/list_cycle.c +++ b/142_linked_list_cycle_ii/list_cycle.c @@ -9,22 +9,19 @@ struct ListNode { static struct ListNode *detectCycle(struct ListNode *head) { - if (head == NULL || head->next == NULL) { - return false; - } - - bool first = true; - struct ListNode *p0, *p1; - for (p0 = head, p1 = head; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) { - if (p0 == p1 && !first) { - p0 = head; - while (p0 != p1) { - p0 = p0->next; - p1 = p1->next; + struct ListNode *fast = head; + struct ListNode *slow = head; + while (fast != NULL && fast->next != NULL) { + slow = slow->next; + fast = fast->next->next; + if (fast == slow) { + fast = head; + while (fast != slow) { + fast = fast->next; + slow = slow->next; } - return p0; + return fast; } - first = false; } return NULL; diff --git a/142_linked_list_cycle_ii/list_cycle.cc b/142_linked_list_cycle_ii/list_cycle.cc new file mode 100644 index 0000000..da1e86d --- /dev/null +++ b/142_linked_list_cycle_ii/list_cycle.cc @@ -0,0 +1,32 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* detectCycle(ListNode *head) { + ListNode *fast = head; + ListNode *slow = head; + while (fast != nullptr && fast->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + if (fast == slow) { + fast = head; + while (fast != slow) { + fast = fast->next; + slow = slow->next; + } + return fast; + } + } + return nullptr; + } +}; diff --git a/226_invert_binary_tree/invert_binary_tree.cc b/226_invert_binary_tree/invert_binary_tree.cc new file mode 100644 index 0000000..dd3539e --- /dev/null +++ b/226_invert_binary_tree/invert_binary_tree.cc @@ -0,0 +1,29 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if (root == NULL) { + return NULL; + } + + TreeNode* l = invertTree(root->left); + TreeNode* r = invertTree(root->right); + root->left = r; + root->right = l; + return root; + } +}; From c4372d3b0375ed679dbf83375ca145c760e305f3 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 18 Aug 2020 12:24:04 +0800 Subject: [PATCH 097/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 051_n_queens/n_queens.cc | 40 ++++++++++++++++++++++++++++ 052_n_queens_ii/n_queens.cc | 37 +++++++++++++++++++++++++ 053_maximum_subarray/max_subarray.cc | 19 +++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 051_n_queens/n_queens.cc create mode 100644 052_n_queens_ii/n_queens.cc create mode 100644 053_maximum_subarray/max_subarray.cc diff --git a/051_n_queens/n_queens.cc b/051_n_queens/n_queens.cc new file mode 100644 index 0000000..7b44b99 --- /dev/null +++ b/051_n_queens/n_queens.cc @@ -0,0 +1,40 @@ +#include + +using namespace std; + +class Solution { +public: + vector> solveNQueens(int n) { + vector> res; + vector stack(n); + vector solution(n, string(n, '.')); + dfs(n, 0, stack, solution, res); + return res; + } + +private: + void dfs(int n, int row, vector& stack, vector& solution, vector>& res) { + if (row == n) { + res.push_back(solution); + } else { + for (int i = 0; i < n; i++) { + if (row == 0 || !conflict(stack, row, i)) { + solution[row][i] = 'Q'; + stack[row] = i; + dfs(n, row + 1, stack, solution, res); + solution[row][i] = '.'; + } + } + } + } + + bool conflict(vector& stack, int row, int col) { + for (int i = 0; i < row; i++) { + /* If occupied or in one line */ + if (col == stack[i] || abs(row - i) == abs(col - stack[i])) { + return true; + } + } + return false; + } +} diff --git a/052_n_queens_ii/n_queens.cc b/052_n_queens_ii/n_queens.cc new file mode 100644 index 0000000..ace2dc6 --- /dev/null +++ b/052_n_queens_ii/n_queens.cc @@ -0,0 +1,37 @@ +#include + +using namespace std; + +class Solution { +public: + int totalNQueens(int n) { + vector stack(n); + return dfs(n, 0, stack); + } + +private: + int dfs(int n, int row, vector& stack) { + int count = 0; + if (row == n) { + return count + 1; + } else { + for (int i = 0; i < n; i++) { + if (row == 0 || !conflict(stack, row, i)) { + stack[row] = i; + count += dfs(n, row + 1, stack); + } + } + return count; + } + } + + bool conflict(vector& stack, int row, int col) { + for (int i = 0; i < row; i++) { + /* If occupied or in one line */ + if (col == stack[i] || abs(row - i) == abs(col - stack[i])) { + return true; + } + } + return false; + } +} diff --git a/053_maximum_subarray/max_subarray.cc b/053_maximum_subarray/max_subarray.cc new file mode 100644 index 0000000..834c1e8 --- /dev/null +++ b/053_maximum_subarray/max_subarray.cc @@ -0,0 +1,19 @@ +#include + +using namespace std; + +class Solution { +public: + int maxSubArray(vector& nums) { + int sum = 0, max_sum = INT_MIN; + for (int i = 0; i < nums.size(); i++) { + if (sum < 0) { + sum = nums[i]; + } else { + sum += nums[i]; + } + max_sum = max(sum, max_sum); + } + return max_sum; + } +}; From 8354b9a7978fee1f5db341daafbaa2f34ea699a4 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 20 Aug 2020 21:11:02 +0800 Subject: [PATCH 098/211] Refine Signed-off-by: begeekmyfriend --- 138_copy_list_with_random_pointer/copy_list.c | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/138_copy_list_with_random_pointer/copy_list.c b/138_copy_list_with_random_pointer/copy_list.c index 5fe458f..48a7bbf 100644 --- a/138_copy_list_with_random_pointer/copy_list.c +++ b/138_copy_list_with_random_pointer/copy_list.c @@ -9,35 +9,31 @@ struct Node { static struct Node *copyRandomList(struct Node *head) { - if (head == NULL) { - return NULL; - } - - /* copy and redirect next pointer */ - struct Node *p, *new; - for (p = head; p != NULL; p = p->next->next) { - new = malloc(sizeof(*new)); - new->val = p->val; - new->next = p->next; - p->next = new; + struct Node *p, *q; + /* insert interleavingly */ + for (p = head; p != NULL; p = q->next) { + q = malloc(sizeof(*q)); + q->val = p->val; + q->next = p->next; + p->next = q; } /* clone random pointer */ - for (p = head; p != NULL; p = p->next->next) { - new = p->next; - new->random = p->random != NULL ? p->random->next : NULL; + for (p = head; p != NULL; p = q->next) { + q = p->next; + q->random = p->random != NULL ? p->random->next : NULL; } struct Node dummy; struct Node *prev = &dummy; - for (p = head; p != NULL; p = p->next) { - new = p->next; - p->next = new->next; - /* correct the actual next pointer of the new list */ - prev->next = new; - prev = new; - new->next = NULL; + prev->next = head; + for (p = head; p != NULL; p = q->next) { + q = p->next; + /* separate q list */ + prev->next = q; + prev = q; } + /* q->next = NULL */ return dummy.next; } From 468a05fb1fe524c6e4e05e5210be727f0e9ea8b7 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 20 Aug 2020 21:53:41 +0800 Subject: [PATCH 099/211] Refine Signed-off-by: begeekmyfriend --- 054_spiral_matrix/spiral_matrix.c | 27 ++++++---- 054_spiral_matrix/spiral_matrix.cc | 54 +++++++++++++++++++ 138_copy_list_with_random_pointer/copy_list.c | 4 +- 3 files changed, 75 insertions(+), 10 deletions(-) create mode 100644 054_spiral_matrix/spiral_matrix.cc diff --git a/054_spiral_matrix/spiral_matrix.c b/054_spiral_matrix/spiral_matrix.c index 54114ea..be53988 100644 --- a/054_spiral_matrix/spiral_matrix.c +++ b/054_spiral_matrix/spiral_matrix.c @@ -4,13 +4,18 @@ /** ** Note: The returned array must be malloced, assume caller calls free(). **/ -static int* spiralOrder(int** matrix, int matrixRowSize, int matrixColSize) +static int* spiralOrder(int** matrix, int matrixSize, int *matrixColSize, int *returnSize) { + if (matrixSize == 0) { + *returnSize = 0; + return NULL; + } + int hor_top = 0; - int hor_bottom = matrixRowSize - 1; + int hor_bottom = matrixSize - 1; int ver_left = 0; - int ver_right = matrixColSize - 1; - int *nums = malloc(matrixRowSize * matrixColSize * sizeof(int)); + int ver_right = matrixColSize[0] - 1; + int *nums = malloc(matrixSize * matrixColSize[0] * sizeof(int)); int count = 0; int i, direction = 0; @@ -47,6 +52,7 @@ static int* spiralOrder(int** matrix, int matrixRowSize, int matrixColSize) direction %= 4; } + *returnSize = count; return nums; } @@ -54,20 +60,23 @@ int main(int argc, char **argv) { int i, j, count = 0; int row = 3; - int col = 3; + int *cols = malloc(row * sizeof(int)); int **mat = malloc(row * sizeof(int *)); for (i = 0; i < row; i++) { - mat[i] = malloc(col * sizeof(int)); - for (j = 0; j < col; j++) { + cols[i] = row; + mat[i] = malloc(cols[i] * sizeof(int)); + for (j = 0; j < cols[i]; j++) { mat[i][j] = ++count; printf("%d ", mat[i][j]); } printf("\n"); } - int *nums = spiralOrder(mat, row, col); - for (i = 0; i < row * col; i++) { + + int *nums = spiralOrder(mat, row, cols, &count); + for (i = 0; i < count; i++) { printf("%d ", nums[i]); } printf("\n"); + return 0; } diff --git a/054_spiral_matrix/spiral_matrix.cc b/054_spiral_matrix/spiral_matrix.cc new file mode 100644 index 0000000..f155dc3 --- /dev/null +++ b/054_spiral_matrix/spiral_matrix.cc @@ -0,0 +1,54 @@ +#include + +using namespace std; + +class Solution { +public: + vector spiralOrder(vector>& matrix) { + if (matrix.empty()) { + return vector(); + } + + int hor_top = 0; + int hor_bottom = matrix.size(); + int ver_left = 0; + int ver_right = matrix[0].size(); + int direction = 0; + vector res; + + while (hor_top <= hor_bottom && ver_left <= ver_right) { + switch (direction) { + case 0: + for (int i = ver_left; i <= ver_right; i++) { + res.push_back(matrix[hor_top][i]); + } + hor_top++; + break; + case 1: + for (int i = hor_top; i <= hor_bottom; i++) { + res.push_back(matrix[i][ver_right]); + } + ver_right--; + break; + case 2: + for (int i = ver_right; i >= ver_left; i--) { + res.push_back(matrix[hor_bottom][i]); + } + hor_bottom--; + break; + case 3: + for (int i = hor_bottom; i >= hor_top; i--) { + res.push_back(matrix[i][ver_left]); + } + ver_left++; + break; + default: + break; + } + direction++; + direction %= 4; + } + + return res; + } +}; diff --git a/138_copy_list_with_random_pointer/copy_list.c b/138_copy_list_with_random_pointer/copy_list.c index 48a7bbf..39c762d 100644 --- a/138_copy_list_with_random_pointer/copy_list.c +++ b/138_copy_list_with_random_pointer/copy_list.c @@ -27,9 +27,11 @@ static struct Node *copyRandomList(struct Node *head) struct Node dummy; struct Node *prev = &dummy; prev->next = head; + /* separate q list */ for (p = head; p != NULL; p = q->next) { q = p->next; - /* separate q list */ + /* restore p->next */ + p->next = q->next; prev->next = q; prev = q; } From d2741d5bdc5a4d7fc393087ab52b48afed250269 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 21 Aug 2020 08:29:21 +0800 Subject: [PATCH 100/211] Refine Signed-off-by: begeekmyfriend --- 098_validate_binary_search_tree/valid_bst.c | 32 +++++++++++------ 099_recover_binary_search_tree/recover_bst.c | 36 ++++++++++---------- 100_same_tree/same_tree.c | 23 +++++-------- 198_house_robber/robber.c | 1 + 213_house_robber_ii/robber.c | 1 + 5 files changed, 50 insertions(+), 43 deletions(-) diff --git a/098_validate_binary_search_tree/valid_bst.c b/098_validate_binary_search_tree/valid_bst.c index 06e972e..e03289e 100644 --- a/098_validate_binary_search_tree/valid_bst.c +++ b/098_validate_binary_search_tree/valid_bst.c @@ -3,24 +3,34 @@ #include #include + struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; -static bool dfs(struct TreeNode* node, int min, int max) -{ - if (node == NULL) return true; - if (node->val < min || node->val > max) return false; - if (node->left != NULL && node->val == INT_MIN) return false; - if (node->right != NULL && node->val == INT_MAX) return false; - return dfs(node->left, min, node->val - 1) && dfs(node->right, node->val + 1, max); -} - -static bool isValidBST(struct TreeNode* root) +bool isValidBST(struct TreeNode* root) { - return dfs(root, INT_MIN, INT_MAX); + int top = 0; + int prev = INT_MIN; + bool first = true; + struct TreeNode *stack[1000]; + while (top > 0 || root != NULL) { + if (root != NULL) { + stack[top++] = root; + root = root->left; + } else { + root = stack[--top]; + if (!first && prev >= root->val) { + return false; + } + first = false; + prev = root->val; + root = root->right; + } + } + return true; } int main(int argc, char **argv) diff --git a/099_recover_binary_search_tree/recover_bst.c b/099_recover_binary_search_tree/recover_bst.c index 8636472..6fb720b 100644 --- a/099_recover_binary_search_tree/recover_bst.c +++ b/099_recover_binary_search_tree/recover_bst.c @@ -2,48 +2,48 @@ #include #include + struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; -static void traverse(struct TreeNode *node, struct TreeNode **prev, - struct TreeNode **p1, struct TreeNode **p2, int *wrong) +static void dfs(struct TreeNode *node, struct TreeNode **prev, + struct TreeNode **p1, struct TreeNode **p2, int *wrong) { - if (node->left != NULL) { - traverse(node->left, prev, p1, p2, wrong); + if (node == NULL || *wrong == 2) { + return; } + dfs(node->left, prev, p1, p2, wrong); + + /* We must use pointer to pointer for previous object in recursion */ if (*prev != NULL && node->val < (*prev)->val) { (*wrong)++; if (*wrong == 1) { *p1 = *prev; + /* p2 should be recorded here in some cases */ *p2 = node; } else if (*wrong == 2) { *p2 = node; - return; } } *prev = node; - if (node->right != NULL) { - traverse(node->right, prev, p1, p2, wrong); - } + dfs(node->right, prev, p1, p2, wrong); } static void recoverTree(struct TreeNode* root) { - if (root != NULL) { - struct TreeNode *prev = NULL; - struct TreeNode *p1 = NULL; - struct TreeNode *p2 = NULL; - int wrong = 0; - traverse(root, &prev, &p1, &p2, &wrong); - int tmp = p1->val; - p1->val = p2->val; - p2->val = tmp; - } + int wrong = 0; + struct TreeNode *prev = NULL; + struct TreeNode *p1 = NULL; + struct TreeNode *p2 = NULL; + dfs(root, &prev, &p1, &p2, &wrong); + int tmp = p1->val; + p1->val = p2->val; + p2->val = tmp; } int main(int argc, char **argv) diff --git a/100_same_tree/same_tree.c b/100_same_tree/same_tree.c index 3786053..205c237 100644 --- a/100_same_tree/same_tree.c +++ b/100_same_tree/same_tree.c @@ -10,21 +10,16 @@ struct TreeNode { static bool isSameTree(struct TreeNode* p, struct TreeNode* q) { - if (p != NULL && q != NULL) { - if (p->val != q->val) { - return false; - } - if (!isSameTree(p->left, q->left)) { - return false; - } - if (!isSameTree(p->right, q->right)) { - return false; - } - } else { - return p == q; + if (p == NULL && q == NULL) { + return true; } - - return true; + if (p == NULL || q == NULL) { + return false; + } + if (p->val != q->val) { + return false; + } + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } int main(void) diff --git a/198_house_robber/robber.c b/198_house_robber/robber.c index 35d7f22..e255487 100644 --- a/198_house_robber/robber.c +++ b/198_house_robber/robber.c @@ -20,6 +20,7 @@ static int rob(int* nums, int numsSize) for (i = 1; i < numsSize; i++) { int tmp_taken = taken; int tmp_untaken = untaken; + /* Taken or untaken nums[i] */ taken = untaken + nums[i]; untaken = max(tmp_taken, tmp_untaken); } diff --git a/213_house_robber_ii/robber.c b/213_house_robber_ii/robber.c index 21ae639..391bb83 100644 --- a/213_house_robber_ii/robber.c +++ b/213_house_robber_ii/robber.c @@ -16,6 +16,7 @@ static int _rob(int* nums, int numsSize) for (i = 1; i < numsSize; i++) { int tmp_taken = taken; int tmp_untaken = untaken; + /* Taken or untaken nums[i] */ taken = tmp_untaken + nums[i]; untaken = max(tmp_taken, tmp_untaken); } From 513693588c35a1401acf497b3f10dd5d26aae527 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 23 Aug 2020 11:59:11 +0800 Subject: [PATCH 101/211] Refine Signed-off-by: begeekmyfriend --- 039_combination_sum/combination_sum.c | 3 ++- 040_combination_sum_ii/combination_sum.c | 4 +++- 046_permutations/permutations.c | 3 ++- 047_permutations_ii/permutations.c | 11 ++++++----- 055_jump_game/jump_game.c | 1 + 056_merge_intervals/merge_intervals.c | 1 + 057_insert_interval/insert_interval.c | 1 + 059_spiral_matrix_ii/spiral_matrix.c | 19 +++++++++++++------ 8 files changed, 29 insertions(+), 14 deletions(-) diff --git a/039_combination_sum/combination_sum.c b/039_combination_sum/combination_sum.c index 590c3f0..9bda0fc 100644 --- a/039_combination_sum/combination_sum.c +++ b/039_combination_sum/combination_sum.c @@ -2,6 +2,7 @@ #include #include + static void dfs(int *nums, int size, int start, int target, int *stack, int len, int **results, int *count, int *column_sizes) { @@ -17,7 +18,7 @@ static void dfs(int *nums, int size, int start, int target, int *stack, for (i = start; i < size; i++) { stack[len] = nums[i]; /* The elements in solution can be duplicate for the purpose of the problem */ - dfs(nums, size, i, target - nums[i], stack, len + 1, results, column_sizes, count); + dfs(nums, size, i, target - nums[i], stack, len + 1, results, count, column_sizes); } } } diff --git a/040_combination_sum_ii/combination_sum.c b/040_combination_sum_ii/combination_sum.c index 01d6965..b49ea54 100644 --- a/040_combination_sum_ii/combination_sum.c +++ b/040_combination_sum_ii/combination_sum.c @@ -1,8 +1,10 @@ +#include #include #include #include #include + static int compare(const void *a, const void *b) { return *(int *) a - *(int *) b; @@ -20,7 +22,7 @@ static void dfs(int *nums, int size, int start, int target, int *solution, column_sizes[*count] = len; (*count)++; } else { - int last = -1; + int last = INT_MIN; for (i = start; i < size; i++) { if (last != nums[i]) { /* No duplicate combinations in different order */ diff --git a/046_permutations/permutations.c b/046_permutations/permutations.c index 5176834..38968d4 100644 --- a/046_permutations/permutations.c +++ b/046_permutations/permutations.c @@ -42,9 +42,10 @@ static void dfs(int *nums, int size, bool *used, int *stack, 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); diff --git a/047_permutations_ii/permutations.c b/047_permutations_ii/permutations.c index 51e0339..a666bdc 100644 --- a/047_permutations_ii/permutations.c +++ b/047_permutations_ii/permutations.c @@ -18,11 +18,12 @@ static void dfs(int *nums, int size, bool *used, int *stack, 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 && nums[i] == nums[i - 1] && !used[i - 1]) { - /* In case that duplicate permutation with same elemements */ - /* Used marks allow same elements in different DFS levels */ + if (i > 0 && !used[i - 1] && nums[i - 1] == nums[i]) { + /* In case that duplicate permutation with same elemements but in different postions */ continue; } used[i] = true; @@ -46,8 +47,8 @@ static int **permute(int* nums, int numsSize, int* returnSize, int **returnColum int count = 0, cap = 10000; int *stack = malloc(numsSize * sizeof(int)); int **results = malloc(cap * sizeof(int *)); - bool *used = malloc(numsSize); - memset(used, false, numsSize); + bool *used = malloc(numsSize * sizeof(bool)); + memset(used, false, numsSize * sizeof(bool)); *returnSize = 0; *returnColumnSize = malloc(cap * sizeof(int)); dfs(nums, numsSize, used, stack, 0, results, returnSize, *returnColumnSize); diff --git a/055_jump_game/jump_game.c b/055_jump_game/jump_game.c index 7dd5825..66e454b 100644 --- a/055_jump_game/jump_game.c +++ b/055_jump_game/jump_game.c @@ -12,6 +12,7 @@ static bool canJump(int* nums, int numsSize) int i, pos = 0; for (i = 0; i < numsSize - 1; i++) { if (pos < i || pos >= numsSize - 1) { + /* pos < i means nums[pos] == 0 */ break; } /* if all positive number it always can arrive. */ diff --git a/056_merge_intervals/merge_intervals.c b/056_merge_intervals/merge_intervals.c index c9ca555..e9570d5 100644 --- a/056_merge_intervals/merge_intervals.c +++ b/056_merge_intervals/merge_intervals.c @@ -36,6 +36,7 @@ int** merge(int** intervals, int intervalsSize, int* intervalsColSize, int* retu intervals[len][0] = tmp[i * 2]; intervals[len][1] = tmp[i * 2 + 1]; } else if (tmp[i * 2 + 1] > intervals[len][1]) { + /* merge this interval */ intervals[len][1] = tmp[i * 2 + 1]; } } diff --git a/057_insert_interval/insert_interval.c b/057_insert_interval/insert_interval.c index 02cb9a3..c0f7c9d 100644 --- a/057_insert_interval/insert_interval.c +++ b/057_insert_interval/insert_interval.c @@ -35,6 +35,7 @@ int** insert(int** intervals, int intervalsSize, int* intervalsColSize, int* new results[len][0] = tmp[i * 2]; results[len][1] = tmp[i * 2 + 1]; } else if (tmp[i * 2 + 1] > results[len][1]) { + /* merge this interval */ results[len][1] = tmp[i * 2 + 1]; } } diff --git a/059_spiral_matrix_ii/spiral_matrix.c b/059_spiral_matrix_ii/spiral_matrix.c index a224c50..18da9e0 100644 --- a/059_spiral_matrix_ii/spiral_matrix.c +++ b/059_spiral_matrix_ii/spiral_matrix.c @@ -1,16 +1,22 @@ #include #include + /** - ** Return an array of arrays. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static int** generateMatrix(int n) { + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ +static int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) +{ int i; int **matrix = malloc(n * sizeof(int *)); int *nums = malloc(n * n * sizeof(int)); + *returnSize = n; + *returnColumnSizes = malloc(n * sizeof(int)); for (i = 0; i < n; i++) { matrix[i] = &nums[i * n]; + (*returnColumnSizes)[i] = n; } int direction = 0; @@ -60,9 +66,10 @@ int main(int argc, char **argv) exit(-1); } - int i, j; + int i, j, count; int n = atoi(argv[1]); - int **matrix = generateMatrix(n); + int *col_sizes; + int **matrix = generateMatrix(n, &count, &col_sizes); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%d ", matrix[i][j]); From 0facc38f9b5c059b4a15322cabde35844059f9fb Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 24 Aug 2020 15:48:29 +0800 Subject: [PATCH 102/211] Refine Signed-off-by: begeekmyfriend --- 091_decode_ways/decode_ways.c | 24 ++++++------ 120_triangle/triangle.c | 14 +++---- 207_course_schedule/course_schedule.c | 39 +++++++++++-------- 210_course_schedule_ii/course_schedule.c | 34 ++++++++-------- .../bst_lca.c | 15 +++---- 5 files changed, 63 insertions(+), 63 deletions(-) diff --git a/091_decode_ways/decode_ways.c b/091_decode_ways/decode_ways.c index a096361..05fc39d 100644 --- a/091_decode_ways/decode_ways.c +++ b/091_decode_ways/decode_ways.c @@ -2,29 +2,29 @@ #include #include -static int numDecodings(char* s) { + +static int numDecodings(char* s) +{ int len = strlen(s); if (len == 0) { return 0; } - int dp[len + 1]; - memset(dp, 0, (len + 1) * sizeof(int)); - - dp[0] = 1; - dp[1] = s[0] == '0' ? 0 : 1; + int a = 1; + int b = s[0] == '0' ? 0 : a; + int c = b; + /* DP: How many counts in sequence c = f(a, b) and c counts s[i - 1] */ for (int i = 2; i <= len; i++) { - if (s[i - 1] != '0') { - dp[i] = dp[i - 1]; - } - + c = s[i - 1] == '0' ? 0 : b; int num = (s[i - 2] - '0') * 10 + (s[i - 1] - '0'); if (num >= 10 && num <= 26) { - dp[i] += dp[i - 2]; + c += a; } + a = b; + b = c; } - return dp[len]; + return c; } int main(int argc, char **argv) diff --git a/120_triangle/triangle.c b/120_triangle/triangle.c index 2221137..7df14cc 100644 --- a/120_triangle/triangle.c +++ b/120_triangle/triangle.c @@ -3,6 +3,7 @@ #include #include + static int dfs(int** triangle, int row_size, int *col_sizes, int row, int col, int **sums, bool **passes) { @@ -14,24 +15,23 @@ static int dfs(int** triangle, int row_size, int *col_sizes, int s1 = dfs(triangle, row_size, col_sizes, row + 1, col, sums, passes); int s2 = dfs(triangle, row_size, col_sizes, row + 1, col + 1, sums, passes); sums[row][col] = triangle[row][col] + (s1 < s2 ? s1 : s2); + /* Set pass marks in backtracing as the paths are overlapped */ passes[row][col] = true; return sums[row][col]; } } -static int minimumTotal(int** triangle, int triangleRowSize, int *triangleColSizes) +static int minimumTotal(int** triangle, int triangleSize, int *triangleColSizes) { int i; - bool **passes = malloc(triangleRowSize * sizeof(bool *)); - for (i = 0; i < triangleRowSize; i++) { + int **sums = malloc(triangleSize * sizeof(int *)); + bool **passes = malloc(triangleSize * sizeof(bool *)); + for (i = 0; i < triangleSize; i++) { passes[i] = malloc(triangleColSizes[i]); memset(passes[i], false, triangleColSizes[i]); - } - int **sums = malloc(triangleRowSize * sizeof(int *)); - for (i = 0; i < triangleRowSize; i++) { sums[i] = malloc(triangleColSizes[i] * sizeof(int)); } - return dfs(triangle, triangleRowSize, triangleColSizes, 0, 0, sums, passes); + return dfs(triangle, triangleSize, triangleColSizes, 0, 0, sums, passes); } int main(void) diff --git a/207_course_schedule/course_schedule.c b/207_course_schedule/course_schedule.c index 7a7c325..cfd1727 100644 --- a/207_course_schedule/course_schedule.c +++ b/207_course_schedule/course_schedule.c @@ -3,51 +3,49 @@ #include #include + struct graph_node { int req_num; int reqs[15]; + bool touched; + bool taken; }; -static bool dfs(struct graph_node *courses, int id, bool *takens, bool *touched) +static bool dfs(struct graph_node *courses, int id) { int i; - if (touched[id]) { + if (courses[id].touched) { return true; - } else if (takens[id]) { + } else if (courses[id].taken) { return false; } else { - takens[id] = true; + courses[id].taken = true; for (i = 0; i < courses[id].req_num; i++) { - if (!dfs(courses, courses[id].reqs[i], takens, touched)) { + if (!dfs(courses, courses[id].reqs[i])) { return false; } } - /* marked as available and no need to traverse next time */ - touched[id] = true; - takens[id] = false; + /* If paths overlapped, mark in backtracing for no need to traverse next time */ + courses[id].touched = true; + courses[id].taken = false; return true; } } -static bool canFinish(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize) +static bool canFinish(int numCourses, int** prerequisites, int prerequisitesSize, int *prerequisitesColSize) { int i; - bool *takens = malloc(numCourses); - bool *touched = malloc(numCourses); struct graph_node *courses = malloc(numCourses * sizeof(*courses)); memset(courses, 0, numCourses * sizeof(*courses)); - memset(takens, false, numCourses * sizeof(bool)); - memset(touched, false, numCourses * sizeof(bool)); - - for (i = 0; i < prerequisitesRowSize; i++) { + for (i = 0; i < prerequisitesSize; i++) { int id = prerequisites[i][0]; int req = prerequisites[i][1]; courses[id].reqs[courses[id].req_num++] = req; } for (i = 0; i < numCourses; i++) { - if (!dfs(courses, i, takens, touched)) { + if (!dfs(courses, i)) { return false; } } @@ -59,24 +57,31 @@ int main(void) { int i, course_num = 6, pair_num = 6; int **pairs = malloc(pair_num * sizeof(int *)); + int *col_sizes = malloc(pair_num * sizeof(int)); pairs[0] = malloc(2 * sizeof(int)); pairs[0][0] = 1; pairs[0][1] = 0; + col_sizes[0] = 2; pairs[1] = malloc(2 * sizeof(int)); pairs[1][0] = 2; pairs[1][1] = 1; + col_sizes[1] = 2; pairs[2] = malloc(2 * sizeof(int)); pairs[2][0] = 3; pairs[2][1] = 2; + col_sizes[2] = 2; pairs[3] = malloc(2 * sizeof(int)); pairs[3][0] = 1; pairs[3][1] = 3; + col_sizes[3] = 2; pairs[4] = malloc(2 * sizeof(int)); pairs[4][0] = 4; pairs[4][1] = 0; + col_sizes[4] = 2; pairs[5] = malloc(2 * sizeof(int)); pairs[5][0] = 0; pairs[5][1] = 5; - printf("%s\n", canFinish(course_num, pairs, pair_num, 2) ? "true" : "false"); + col_sizes[5] = 2; + printf("%s\n", canFinish(course_num, pairs, pair_num, col_sizes) ? "true" : "false"); return 0; } diff --git a/210_course_schedule_ii/course_schedule.c b/210_course_schedule_ii/course_schedule.c index 5ecd140..d2d33b4 100644 --- a/210_course_schedule_ii/course_schedule.c +++ b/210_course_schedule_ii/course_schedule.c @@ -3,29 +3,33 @@ #include #include + struct graph_node { int req_num; int reqs[15]; + bool touched; + bool taken; }; -static bool dfs(struct graph_node *courses, int id, bool *takens, bool *touched, int *order, int *count) +static bool dfs(struct graph_node *courses, int id, int *order, int *count) { int i; - if (touched[id]) { + if (courses[id].touched) { return true; - } else if (takens[id]) { + } else if (courses[id].taken) { return false; } else { - takens[id] = true; + courses[id].taken = true; for (i = 0; i < courses[id].req_num; i++) { - if (!dfs(courses, courses[id].reqs[i], takens, touched, order, count)) { + if (!dfs(courses, courses[id].reqs[i], order, count)) { return false; } } - /* marked as available and no need to traverse next time */ + /* Record path in backtrace before DFS return */ order[(*count)++] = id; - touched[id] = true; - takens[id] = false; + /* If paths overlapped, mark in backtracing for no need to traverse next time */ + courses[id].touched = true; + courses[id].taken = false; return true; } } @@ -34,19 +38,14 @@ static bool dfs(struct graph_node *courses, int id, bool *takens, bool *touched, * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ -static int *findOrder(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize, int *returnSize) +static int *findOrder(int numCourses, int** prerequisites, int prerequisitesSize, int *prerequisitesColSize, int *returnSize) { int i; int *order = malloc(numCourses * sizeof(int)); - bool *takens = malloc(numCourses); - bool *touched = malloc(numCourses); struct graph_node *courses = malloc(numCourses * sizeof(*courses)); memset(courses, 0, numCourses * sizeof(*courses)); - memset(takens, false, numCourses * sizeof(bool)); - memset(touched, false, numCourses * sizeof(bool)); - - for (i = 0; i < prerequisitesRowSize; i++) { + for (i = 0; i < prerequisitesSize; i++) { int id = prerequisites[i][0]; int req = prerequisites[i][1]; courses[id].reqs[courses[id].req_num++] = req; @@ -54,7 +53,7 @@ static int *findOrder(int numCourses, int** prerequisites, int prerequisitesRowS *returnSize = 0; for (i = 0; i < numCourses; i++) { - if (!dfs(courses, i, takens, touched, order, returnSize)) { + if (!dfs(courses, i, order, returnSize)) { *returnSize = 0; return order; } @@ -67,6 +66,7 @@ int main(void) { int i, course_num = 3, pair_num = 1; int **pairs = malloc(pair_num * sizeof(int *)); + int *col_sizes = malloc(pair_num * sizeof(int)); pairs[0] = malloc(2 * sizeof(int)); pairs[0][0] = 1; pairs[0][1] = 0; @@ -84,7 +84,7 @@ int main(void) //pairs[4][1] = 5; int count = 0; - int *ids = findOrder(course_num, pairs, pair_num, 2, &count); + int *ids = findOrder(course_num, pairs, pair_num, col_sizes, &count); for (i = 0; i < count; i++) { printf("%d ", ids[i]); } diff --git a/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c b/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c index 2b83bef..30afec2 100644 --- a/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c +++ b/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c @@ -2,6 +2,7 @@ #include #include + struct TreeNode { int val; struct TreeNode *left; @@ -11,24 +12,18 @@ struct TreeNode { static struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { if (root == NULL || root == p || root == q) { + /* edge cases: if return NULL then no p or q node in this path */ return root; } + /* l is the LCA in the left branch but not root->left */ struct TreeNode *l = lowestCommonAncestor(root->left, p, q); - if (l != NULL && l != p && l != q) { - /* both p and q in left subtree: l->left != NULL && l->right != NULL */ - return l; - } - + /* r is the LCA in the right branch but not root->right */ struct TreeNode *r = lowestCommonAncestor(root->right, p, q); - if (r != NULL && r != p && r != q) { - /* both p and q in right subtree: r->left != NULL && r->right != NULL */ - return r; - } - if (l != NULL && r != NULL) { return root; } else { + /* if not return root node, the return value is fixed */ return l != NULL ? l : r; } } From b9dc8acd06ceedad067a3c4f543dd3c842583c5a Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 8 Sep 2020 16:00:17 +0800 Subject: [PATCH 103/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 040_combination_sum_ii/combination_sum.cc | 2 +- 046_permutations/permutations.cc | 2 + 047_permutations_ii/permutations.cc | 4 +- 098_validate_binary_search_tree/valid_bst.cc | 39 ++++++++++++++ 100_same_tree/same_tree.cc | 30 +++++++++++ 101_symmetric_tree/symmetric_tree.cc | 38 ++++++++++++++ .../bst_bfs.cc | 45 ++++++++++++++++ 104_maximum_depth_of_binary_tree/bst_depth.cc | 24 +++++++++ .../bst_bfs.cc | 46 ++++++++++++++++ .../copy_list.cc | 52 +++++++++++++++++++ 141_linked_list_cycle/list_cycle.cc | 2 +- 142_linked_list_cycle_ii/list_cycle.cc | 2 +- 146_lru_cache/lru_cache.cc | 4 +- 226_invert_binary_tree/invert_binary_tree.cc | 4 +- 230_kth_smallest_element_in_a_bst/kth_bst.cc | 4 +- 15 files changed, 287 insertions(+), 11 deletions(-) create mode 100644 098_validate_binary_search_tree/valid_bst.cc create mode 100644 100_same_tree/same_tree.cc create mode 100644 101_symmetric_tree/symmetric_tree.cc create mode 100644 102_binary_tree_level_order_traversal/bst_bfs.cc create mode 100644 104_maximum_depth_of_binary_tree/bst_depth.cc create mode 100644 107_binary_tree_level_order_traversal_ii/bst_bfs.cc create mode 100644 138_copy_list_with_random_pointer/copy_list.cc diff --git a/040_combination_sum_ii/combination_sum.cc b/040_combination_sum_ii/combination_sum.cc index 548c782..c74461f 100644 --- a/040_combination_sum_ii/combination_sum.cc +++ b/040_combination_sum_ii/combination_sum.cc @@ -19,7 +19,7 @@ class Solution { } else if (target == 0) { res.push_back(stack); } else { - int last = -1; + int last = INT_MIN; for (int i = start; i < candidates.size(); i++) { if (last != candidates[i]) { /* No duplicate combinations in different order */ diff --git a/046_permutations/permutations.cc b/046_permutations/permutations.cc index 48038c0..2f33cab 100644 --- a/046_permutations/permutations.cc +++ b/046_permutations/permutations.cc @@ -17,8 +17,10 @@ class Solution { 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, stack, res); diff --git a/047_permutations_ii/permutations.cc b/047_permutations_ii/permutations.cc index 23eca7c..389df2b 100644 --- a/047_permutations_ii/permutations.cc +++ b/047_permutations_ii/permutations.cc @@ -19,10 +19,10 @@ class Solution { res.push_back(stack); } else { for (int i = 0; i < nums.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 that duplicate permutation with same elemements */ - /* Used marks allow same elements in different DFS levels */ + // In case that duplicate permutation with same elemements but in different postions continue; } used[i] = true; diff --git a/098_validate_binary_search_tree/valid_bst.cc b/098_validate_binary_search_tree/valid_bst.cc new file mode 100644 index 0000000..c80f236 --- /dev/null +++ b/098_validate_binary_search_tree/valid_bst.cc @@ -0,0 +1,39 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isValidBST(TreeNode* root) { + stack stk; + int prev = INT_MIN; + bool first = true; + while (!stk.empty() || root != nullptr) { + if (root != nullptr) { + stk.push(root); + root = root->left; + } else { + root = stk.top(); + stk.pop(); + if (!first && prev >= root->val) { + return false; + } + first = false; + prev = root->val; + root = root->right; + } + } + return true; + } +}; diff --git a/100_same_tree/same_tree.cc b/100_same_tree/same_tree.cc new file mode 100644 index 0000000..be894b1 --- /dev/null +++ b/100_same_tree/same_tree.cc @@ -0,0 +1,30 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == nullptr && q == nullptr) { + return true; + } + if (p == nullptr || q == nullptr) { + return false; + } + if (p->val != q->val) { + return false; + } + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; diff --git a/101_symmetric_tree/symmetric_tree.cc b/101_symmetric_tree/symmetric_tree.cc new file mode 100644 index 0000000..27fd4bb --- /dev/null +++ b/101_symmetric_tree/symmetric_tree.cc @@ -0,0 +1,38 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if (root == nullptr) { + return true; + } + return dfs(root->left, root->right); + } + +private: + bool dfs(TreeNode *l, TreeNode *r) { + if (l == nullptr && r == nullptr) { + return true; + } + if (l == nullptr || r == nullptr) { + return false; + } + if (l->val != r->val) { + return false; + } + return dfs(l->left, r->right) && dfs(l->right, r->left); + } +}; diff --git a/102_binary_tree_level_order_traversal/bst_bfs.cc b/102_binary_tree_level_order_traversal/bst_bfs.cc new file mode 100644 index 0000000..bf83b55 --- /dev/null +++ b/102_binary_tree_level_order_traversal/bst_bfs.cc @@ -0,0 +1,45 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> res; + if (root == nullptr) { + return res; + } + + queue q; + q.push(root); + while (!q.empty()) { + vector level; + int size = q.size(); + for (int i = 0; i < size; i++) { + TreeNode *node = q.front(); + q.pop(); + level.push_back(node->val); + if (node->left != nullptr) { + q.push(node->left); + } + if (node->right != nullptr) { + q.push(node->right); + } + } + res.push_back(level); + } + + return res; + } +}; diff --git a/104_maximum_depth_of_binary_tree/bst_depth.cc b/104_maximum_depth_of_binary_tree/bst_depth.cc new file mode 100644 index 0000000..fc69b01 --- /dev/null +++ b/104_maximum_depth_of_binary_tree/bst_depth.cc @@ -0,0 +1,24 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxDepth(TreeNode* root) { + if (root == nullptr) { + return 0; + } + return 1 + max(maxDepth(root->left), maxDepth(root->right)); + } +}; diff --git a/107_binary_tree_level_order_traversal_ii/bst_bfs.cc b/107_binary_tree_level_order_traversal_ii/bst_bfs.cc new file mode 100644 index 0000000..fbd3c0a --- /dev/null +++ b/107_binary_tree_level_order_traversal_ii/bst_bfs.cc @@ -0,0 +1,46 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrderBottom(TreeNode* root) { + vector> res; + if (root == nullptr) { + return res; + } + + queue q; + q.push(root); + while (!q.empty()) { + int size = q.size(); + vector level; + for (int i = 0; i < size; i++) { + TreeNode *node = q.front(); + q.pop(); + level.push_back(node->val); + if (node->left != nullptr) { + q.push(node->left); + } + if (node->right != nullptr) { + q.push(node->right); + } + } + res.push_back(level); + } + + reverse(res.begin(), res.end()); + return res; + } +}; diff --git a/138_copy_list_with_random_pointer/copy_list.cc b/138_copy_list_with_random_pointer/copy_list.cc new file mode 100644 index 0000000..90d0c8e --- /dev/null +++ b/138_copy_list_with_random_pointer/copy_list.cc @@ -0,0 +1,52 @@ +#include + +using namespace std; + +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = nullptr; + random = nullptr; + } +}; +*/ + +class Solution { +public: + Node* copyRandomList(Node* head) { + Node *p, *q; + // Insert interleavingly + for (p = head; p != nullptr; p = q->next) { + q = Node(p->val); + q->next = p->next; + p->next = q; + } + + // Clone random pointers + for (p = head; p != nullptr; p = q->next) { + q = p->next; + q->random = p->random != nullptr ? p->random->next : nullptr; + } + + // Separate q list + Node dummy; + Node *prev = &dummy; + prev->next = head; + for (p = head; p != nullptr; p = q->next) { + q = p->next; + p->next = q->next; // restore p->next + prev->next = q; + prev = q; + } + /* q->next == nullptr */ + + return dummy.next; + } +}; diff --git a/141_linked_list_cycle/list_cycle.cc b/141_linked_list_cycle/list_cycle.cc index e44cf0e..323d5c8 100644 --- a/141_linked_list_cycle/list_cycle.cc +++ b/141_linked_list_cycle/list_cycle.cc @@ -7,7 +7,7 @@ using namespace std; * struct ListNode { * int val; * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} + * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { diff --git a/142_linked_list_cycle_ii/list_cycle.cc b/142_linked_list_cycle_ii/list_cycle.cc index da1e86d..6b404b1 100644 --- a/142_linked_list_cycle_ii/list_cycle.cc +++ b/142_linked_list_cycle_ii/list_cycle.cc @@ -7,7 +7,7 @@ using namespace std; * struct ListNode { * int val; * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} + * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { diff --git a/146_lru_cache/lru_cache.cc b/146_lru_cache/lru_cache.cc index 1f8230a..123806e 100644 --- a/146_lru_cache/lru_cache.cc +++ b/146_lru_cache/lru_cache.cc @@ -20,7 +20,7 @@ class LRUCache { } int value = ht_[key]->second; - if (li_.front().second != value) { + if (li_.front().first != key) { li_.erase(ht_[key]); li_.push_front(make_pair(key, value)); ht_[key] = li_.begin(); // iterator failure @@ -46,5 +46,5 @@ class LRUCache { private: int capacity_; list> li_; - unordered_map::iterator> ht_; + unordered_map>::iterator> ht_; }; diff --git a/226_invert_binary_tree/invert_binary_tree.cc b/226_invert_binary_tree/invert_binary_tree.cc index dd3539e..cc9bdb7 100644 --- a/226_invert_binary_tree/invert_binary_tree.cc +++ b/226_invert_binary_tree/invert_binary_tree.cc @@ -16,8 +16,8 @@ using namespace std; class Solution { public: TreeNode* invertTree(TreeNode* root) { - if (root == NULL) { - return NULL; + if (root == nullptr) { + return nullptr; } TreeNode* l = invertTree(root->left); diff --git a/230_kth_smallest_element_in_a_bst/kth_bst.cc b/230_kth_smallest_element_in_a_bst/kth_bst.cc index ac6587f..854808a 100644 --- a/230_kth_smallest_element_in_a_bst/kth_bst.cc +++ b/230_kth_smallest_element_in_a_bst/kth_bst.cc @@ -17,8 +17,8 @@ class Solution { public: int kthSmallest(TreeNode* root, int k) { stack stk; - while (!stk.empty() || root != NULL) { - if (root != NULL) { + while (!stk.empty() || root != nullptr) { + if (root != nullptr) { /* Store the parent node */ stk.push(root); root = root->left; From c9ba0251662fcc1c925b6ce415df9302c1c6db0d Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 9 Sep 2020 00:00:41 +0800 Subject: [PATCH 104/211] Refine Signed-off-by: begeekmyfriend --- 069_sqrt/sqrt.c | 4 ++-- 088_merge_sorted_array/merge_array.c | 9 ++++----- .../bst_convert.c | 10 +++++----- 112_path_sum/path_sum.c | 3 +++ 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/069_sqrt/sqrt.c b/069_sqrt/sqrt.c index cb9a70f..08cc5bd 100644 --- a/069_sqrt/sqrt.c +++ b/069_sqrt/sqrt.c @@ -25,8 +25,8 @@ static double mySqrt(double x) static double mySqrt(double n) { - /* Solute the zero point of f(x) = 0 => x ^ 2 - n = 0 */ - /* f(x) = (x - x0)f'(x0) - f(x0) = 0 First order of Tylor series */ + /* Solute the zero point of f(x). Let F(x) = f(x) - n = 0 */ + /* then (x - x0)F'(x0) + F(x0) = 0 which is the first order of Tylor series */ double x = 1.0; while (fabs(x * x - n) > 1e-8) { // x = x - (x * x - n) / (2 * x); diff --git a/088_merge_sorted_array/merge_array.c b/088_merge_sorted_array/merge_array.c index 7f65d98..ddfbc20 100644 --- a/088_merge_sorted_array/merge_array.c +++ b/088_merge_sorted_array/merge_array.c @@ -1,10 +1,11 @@ #include #include + static void merge(int* nums1, int m, int* nums2, int n) { int i = m - 1, j = n - 1, k = nums1Size - 1; - while (i >= 0 && j >= 0 && k >= 0) { + while (i >= 0 && j >= 0) { if (nums1[i] >= nums2[j]) { nums1[k--] = nums1[i--]; } else { @@ -12,10 +13,8 @@ static void merge(int* nums1, int m, int* nums2, int n) } } - if (i == -1) { - while (j >= 0) { - nums1[k--] = nums2[j--]; - } + while (j >= 0) { + nums1[k--] = nums2[j--]; } } diff --git a/108_convert_sorted_array_to_binary_search_tree/bst_convert.c b/108_convert_sorted_array_to_binary_search_tree/bst_convert.c index b38e13b..1399058 100644 --- a/108_convert_sorted_array_to_binary_search_tree/bst_convert.c +++ b/108_convert_sorted_array_to_binary_search_tree/bst_convert.c @@ -10,19 +10,19 @@ struct TreeNode { static struct TreeNode *partition(int *nums, 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 ? partition(nums, lo, mid - 1) : NULL; - node->right = mid < hi ? partition(nums, mid + 1, hi) : NULL; + node->left = partition(nums, lo, mid - 1); + node->right = partition(nums, mid + 1, hi); return node; } static struct TreeNode* sortedArrayToBST(int* nums, int numsSize) { - if (numsSize == 0) { - return NULL; - } return partition(nums, 0, numsSize - 1); } diff --git a/112_path_sum/path_sum.c b/112_path_sum/path_sum.c index 6cc3e6b..612f482 100644 --- a/112_path_sum/path_sum.c +++ b/112_path_sum/path_sum.c @@ -2,6 +2,7 @@ #include #include + struct TreeNode { int val; struct TreeNode *left; @@ -11,8 +12,10 @@ struct TreeNode { static bool hasPathSum(struct TreeNode *root, int sum) { if (root == NULL) { + /* Here is non leaf */ return false; } else if (root->left == NULL && root->right == NULL && root->val == sum) { + /* Here must be leaf */ return true; } else { return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); From 834904d84a39641837bebaacf20efe17061f62df Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 9 Sep 2020 09:51:55 +0800 Subject: [PATCH 105/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 023_merge_k_sorted_lists/merge_lists.cc | 4 +- 066_plus_one/plus_one.cc | 23 ++++++ 067_add_binary/add_binary.cc | 74 +++++++++++++++++++ 070_climbing_stairs/climb_stairs.cc | 18 +++++ .../rm_dup.cc | 34 +++++++++ 088_merge_sorted_array/merge_array.cc | 23 ++++++ .../bst_convert.cc | 33 +++++++++ 110_balanced_binary_tree/balanced_bst.cc | 36 +++++++++ 111_minimum_depth_of_binary_tree/bst_depth.cc | 26 +++++++ 112_path_sum/path_sum.cc | 29 ++++++++ 121_best_time_to_buy_and_sell_stock/stock.cc | 24 ++++++ .../stock.cc | 17 +++++ 136_single_number/single_number.cc | 14 ++++ 169_majority_element/majority.cc | 21 ++++++ 172_factorial_trailing_zeros/zeroes.cc | 10 +++ 189_rotate_array/rotate_array.cc | 13 ++++ 16 files changed, 397 insertions(+), 2 deletions(-) create mode 100644 066_plus_one/plus_one.cc create mode 100644 067_add_binary/add_binary.cc create mode 100644 070_climbing_stairs/climb_stairs.cc create mode 100644 083_remove_duplicates_from_sorted_list/rm_dup.cc create mode 100644 088_merge_sorted_array/merge_array.cc create mode 100644 108_convert_sorted_array_to_binary_search_tree/bst_convert.cc create mode 100644 110_balanced_binary_tree/balanced_bst.cc create mode 100644 111_minimum_depth_of_binary_tree/bst_depth.cc create mode 100644 112_path_sum/path_sum.cc create mode 100644 121_best_time_to_buy_and_sell_stock/stock.cc create mode 100644 122_best_time_to_buy_and_sell_stock_ii/stock.cc create mode 100644 136_single_number/single_number.cc create mode 100644 169_majority_element/majority.cc create mode 100644 172_factorial_trailing_zeros/zeroes.cc create mode 100644 189_rotate_array/rotate_array.cc diff --git a/023_merge_k_sorted_lists/merge_lists.cc b/023_merge_k_sorted_lists/merge_lists.cc index f2e1556..0e9d8d4 100644 --- a/023_merge_k_sorted_lists/merge_lists.cc +++ b/023_merge_k_sorted_lists/merge_lists.cc @@ -18,10 +18,10 @@ class Solution { auto cmp = [](struct ListNode *n1, struct ListNode *n2) { return n1->val > n2->val; } - priority_queue, decltype(cmp)> queue(cmp); + priority_queue, decltype(cmp)> queue(cmp); for (int i = 0; i < lists.size(); i++) { - if (lists[] != nullptr) { + if (lists[i] != nullptr) { queue.push(lists[i]); } } diff --git a/066_plus_one/plus_one.cc b/066_plus_one/plus_one.cc new file mode 100644 index 0000000..902f431 --- /dev/null +++ b/066_plus_one/plus_one.cc @@ -0,0 +1,23 @@ +#include + +using namespace std; + +class Solution { +public: + vector plusOne(vector& digits) { + int carry = 1; + vector res; + for (int i = digits.size() - 1; i >= 0; i--) { + int d = digits[i] + carry; + res.push_back(d % 10); + carry = d / 10; + } + + if (carry > 0) { + res.push_back(carry); + } + + reverse(res.begin(), res.end()); + return res; + } +}; diff --git a/067_add_binary/add_binary.cc b/067_add_binary/add_binary.cc new file mode 100644 index 0000000..aa44444 --- /dev/null +++ b/067_add_binary/add_binary.cc @@ -0,0 +1,74 @@ +#include + +using namespace std; + +class Solution { +public: + string addBinary(string a, string b) { + string res; + int carry = 0; + int i = a.length() - 1; + int j = b.length() - 1; + for (; i >= 0 && j >= 0; i--, j--) { + if (a[i] == '1' && b[j] == '1') { + if (carry > 0) { + res.push_back('1'); + } else { + res.push_back('0'); + } + carry = 1; + } else if (a[i] == '0' && b[j] == '0') { + if (carry > 0) { + res.push_back('1'); + } else { + res.push_back('0'); + } + carry = 0; + } else { + if (carry > 0) { + res.push_back('0'); + carry = 1; + } else { + res.push_back('1'); + carry = 0; + } + } + } + + while (i >= 0) { + if (a[i--] == '1') { + if (carry > 0) { + res.push_back('0'); + carry = 1; + } else { + res.push_back('1'); + carry = 0; + } + } else { + res.push_back(carry + '0'); + carry = 0; + } + } + + while (j >= 0) { + if (b[j--] == '1') { + if (carry > 0) { + res.push_back('0'); + carry = 1; + } else { + res.push_back('1'); + carry = 0; + } + } else { + res.push_back(carry + '0'); + carry = 0; + } + } + + if (carry > 0) { + res.push_back('1'); + } + reverse(res.begin(), res.end()); + return res; + } +}; diff --git a/070_climbing_stairs/climb_stairs.cc b/070_climbing_stairs/climb_stairs.cc new file mode 100644 index 0000000..c4b4490 --- /dev/null +++ b/070_climbing_stairs/climb_stairs.cc @@ -0,0 +1,18 @@ +#include + +using namespace std; + +class Solution { +public: + int climbStairs(int n) { + int a = 1; + int b = 2; + int c = 0; + for (int i = 3; i <= n; i++) { + c = a + b; + a = b; + b = c; + } + return n == 1 ? a : (n == 2 ? b : c); + } +}; diff --git a/083_remove_duplicates_from_sorted_list/rm_dup.cc b/083_remove_duplicates_from_sorted_list/rm_dup.cc new file mode 100644 index 0000000..3ee3dbf --- /dev/null +++ b/083_remove_duplicates_from_sorted_list/rm_dup.cc @@ -0,0 +1,34 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if (head == nullptr) { + return nullptr; + } + + ListNode* prev = head; + ListNode *p = prev->next; + while (p != nullptr) { + if (p->val != prev->val) { + prev->next = p; + prev = p; + } + p = p->next; + } + prev->next = p; + return head; + } +}; diff --git a/088_merge_sorted_array/merge_array.cc b/088_merge_sorted_array/merge_array.cc new file mode 100644 index 0000000..e08025a --- /dev/null +++ b/088_merge_sorted_array/merge_array.cc @@ -0,0 +1,23 @@ +#include + +using namespace std; + +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int i = m - 1; + int j = n - 1; + int k = nums1.size() - 1; + while (i >= 0 && j >= 0) { + if (nums1[i] < nums2[j]) { + nums1[k--] = nums2[j--]; + } else { + nums1[k--] = nums1[i--]; + } + } + + while (j >= 0) { + nums1[k--] = nums2[j--]; + } + } +}; diff --git a/108_convert_sorted_array_to_binary_search_tree/bst_convert.cc b/108_convert_sorted_array_to_binary_search_tree/bst_convert.cc new file mode 100644 index 0000000..2a9bc4f --- /dev/null +++ b/108_convert_sorted_array_to_binary_search_tree/bst_convert.cc @@ -0,0 +1,33 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* sortedArrayToBST(vector& nums) { + return partition(nums, 0, nums.size() - 1); + } + +private: + TreeNode *partition(vector& nums, int lo, int hi) { + if (lo > hi) { + return nullptr; + } + int mid = lo + (hi - lo) / 2; + TreeNode *root = new TreeNode(nums[mid]); + root->left = partition(nums, lo, mid - 1); + root->right = partition(nums, mid + 1, hi); + return root; + } +}; diff --git a/110_balanced_binary_tree/balanced_bst.cc b/110_balanced_binary_tree/balanced_bst.cc new file mode 100644 index 0000000..b36765b --- /dev/null +++ b/110_balanced_binary_tree/balanced_bst.cc @@ -0,0 +1,36 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isBalanced(TreeNode* root) { + bool balance = true; + depth(root, balance); + return balance; + } + +private: + int depth(TreeNode *root, bool& balance) { + if (!balance || root == nullptr) { + return 0; + } + int ld = depth(root->left, balance) + 1; + int rd = depth(root->right, balance) + 1; + if (balance) { + balance = abs(ld - rd) <= 1; + } + return max(ld, rd); + } +}; diff --git a/111_minimum_depth_of_binary_tree/bst_depth.cc b/111_minimum_depth_of_binary_tree/bst_depth.cc new file mode 100644 index 0000000..2d0a0f0 --- /dev/null +++ b/111_minimum_depth_of_binary_tree/bst_depth.cc @@ -0,0 +1,26 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minDepth(TreeNode* root) { + if (root == nullptr) { + return 0; + } + int ld = minDepth(root->left) + 1; + int rd = minDepth(root->right) + 1; + return ld < rd ? (ld > 1 ? ld : rd) : (rd > 1 ? rd : ld); + } +}; diff --git a/112_path_sum/path_sum.cc b/112_path_sum/path_sum.cc new file mode 100644 index 0000000..5bc36ca --- /dev/null +++ b/112_path_sum/path_sum.cc @@ -0,0 +1,29 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool hasPathSum(TreeNode* root, int sum) { + if (root == nullptr) { + // Here is non leaf + return false; + } else if (root->left == nullptr && root->right == nullptr && root->val == sum) { + // Here must be leaf + return true; + } else { + return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); + } + } +}; diff --git a/121_best_time_to_buy_and_sell_stock/stock.cc b/121_best_time_to_buy_and_sell_stock/stock.cc new file mode 100644 index 0000000..428a6c7 --- /dev/null +++ b/121_best_time_to_buy_and_sell_stock/stock.cc @@ -0,0 +1,24 @@ +#include + +using namespace std; + +class Solution { +public: + int maxProfit(vector& prices) { + if (prices.size() == 0) { + return 0; + } + + int diff = 0; + int minimum = prices[0]; + for (int i = 1; i < prices.size(); i++) { + if (prices[i] < minimum) { + minimum = prices[i]; + } else { + diff = prices[i] - minimum > diff ? prices[i] - minimum : diff; + } + } + + return diff; + } +}; diff --git a/122_best_time_to_buy_and_sell_stock_ii/stock.cc b/122_best_time_to_buy_and_sell_stock_ii/stock.cc new file mode 100644 index 0000000..eea9433 --- /dev/null +++ b/122_best_time_to_buy_and_sell_stock_ii/stock.cc @@ -0,0 +1,17 @@ +#include + +using namespace std; + +class Solution { +public: + int maxProfit(vector& prices) { + int diff, sum = 0; + for (int i = 1; i < prices.size(); i++) { + diff = prices[i] - prices[i - 1]; + if (diff > 0) { + sum += diff; + } + } + return sum; + } +}; diff --git a/136_single_number/single_number.cc b/136_single_number/single_number.cc new file mode 100644 index 0000000..a0652f8 --- /dev/null +++ b/136_single_number/single_number.cc @@ -0,0 +1,14 @@ +#include + +using namespace std; + +class Solution { +public: + int singleNumber(vector& nums) { + int res = nums[0]; + for (int i = 1; i < nums.size(); i++) { + res ^= nums[i]; + } + return res; + } +}; diff --git a/169_majority_element/majority.cc b/169_majority_element/majority.cc new file mode 100644 index 0000000..88b333a --- /dev/null +++ b/169_majority_element/majority.cc @@ -0,0 +1,21 @@ +#include + +using namespace std; + +class Solution { +public: + int majorityElement(vector& nums) { + int major, count = 0; + for (int i = 0; i < nums.size(); i++) { + if (count == 0) { + major = nums[i]; + count++; + } else if (nums[i] != major) { + count--; + } else { + count++; + } + } + return major; + } +}; diff --git a/172_factorial_trailing_zeros/zeroes.cc b/172_factorial_trailing_zeros/zeroes.cc new file mode 100644 index 0000000..94599e6 --- /dev/null +++ b/172_factorial_trailing_zeros/zeroes.cc @@ -0,0 +1,10 @@ +#include + +using namespace std; + +class Solution { +public: + int trailingZeroes(int n) { + return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5); + } +}; diff --git a/189_rotate_array/rotate_array.cc b/189_rotate_array/rotate_array.cc new file mode 100644 index 0000000..8fc0d3c --- /dev/null +++ b/189_rotate_array/rotate_array.cc @@ -0,0 +1,13 @@ +#include + +using namespace std; + +class Solution { +public: + void rotate(vector& nums, int k) { + k %= nums.size(); + reverse(nums.begin(), nums.end() - k); + reverse(nums.end() - k, nums.end()); + reverse(nums.begin(), nums.end()); + } +}; From bf4bda1415cde11b1c57f45f87ca04e009b4d0c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=8A=9B?= Date: Tue, 17 Nov 2020 10:29:34 +0800 Subject: [PATCH 106/211] Add C++ implementation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马力 --- 239_sliding_window_maximum/slide_window.cc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/239_sliding_window_maximum/slide_window.cc b/239_sliding_window_maximum/slide_window.cc index 35b3aad..ceac2b6 100644 --- a/239_sliding_window_maximum/slide_window.cc +++ b/239_sliding_window_maximum/slide_window.cc @@ -15,11 +15,13 @@ class Solution { right--; } indexes[right++] = i; - + + // The last position of sliding window if (i >= k - 1) { res.push_back(nums[indexes[left]]); } - + + // The length of sliding window if (i - indexes[left] + 1 >= k) { left++; } From 0879d90a8ca7e30e86136851d0d3de2a6112d2ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=8A=9B?= Date: Tue, 17 Nov 2020 11:01:57 +0800 Subject: [PATCH 107/211] Refine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马力 --- 146_lru_cache/lru_cache.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/146_lru_cache/lru_cache.c b/146_lru_cache/lru_cache.c index 9d45326..3618501 100644 --- a/146_lru_cache/lru_cache.c +++ b/146_lru_cache/lru_cache.c @@ -189,22 +189,22 @@ void lRUCachePut(LRUCache *obj, int key, int value) if (c->key == key) { list_move(&c->link, &obj->dhead); cache = c; + break; } } if (cache == NULL) { if (obj->count == obj->capacity) { cache = list_last_entry(&obj->dhead, LRUNode, link); - list_move(&cache->link, &obj->dhead); + list_del(&cache->link); hlist_del(&cache->node); - hlist_add_head(&cache->node, &obj->hhead[hash]); } else { cache = malloc(sizeof(LRUNode)); - hlist_add_head(&cache->node, &obj->hhead[hash]); - list_add(&cache->link, &obj->dhead); obj->count++; } cache->key = key; + list_add(&cache->link, &obj->dhead); + hlist_add_head(&cache->node, &obj->hhead[hash]); } cache->value = value; } From 1fd508d6c01fadd32ec7371ad4f79af66d826378 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=8A=9B?= Date: Tue, 17 Nov 2020 15:02:06 +0800 Subject: [PATCH 108/211] Add C++ implementation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马力 --- 164_maximum_gap/max_gap.cc | 38 ++++++++++++++++++++++++++++++++++++++ 167_two_sum_ii/two_sum.c | 10 +++++----- 167_two_sum_ii/two_sum.cc | 25 +++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 5 deletions(-) create mode 100644 164_maximum_gap/max_gap.cc create mode 100644 167_two_sum_ii/two_sum.cc diff --git a/164_maximum_gap/max_gap.cc b/164_maximum_gap/max_gap.cc new file mode 100644 index 0000000..f802915 --- /dev/null +++ b/164_maximum_gap/max_gap.cc @@ -0,0 +1,38 @@ +#include + +using namespace std; + +class Solution { +public: + int maximumGap(vector& nums) { + if (nums.size() < 2) { + return 0; + } + + int min_elem = *min_element(nums.begin(), nums.end()); + int max_elem = *max_element(nums.begin(), nums.end()); + double bucket_size = 1.0 * (max_elem - min_elem) / (nums.size() - 1); + if (bucket_size == 0) { + return 0; + } + + int bucket_cnt = (max_elem - min_elem) / bucket_size + 1; + vector min_bucket(bucket_cnt, INT_MAX); + vector max_bucket(bucket_cnt, INT_MIN); + for (int i = 0; i < nums.size(); i++) { + int id = (nums[i] - min_elem) / bucket_size; + min_bucket[id] = min(nums[i], min_bucket[id]); + max_bucket[id] = max(nums[i], max_bucket[id]); + } + + int max_gap = 0; + int last_max = max_bucket[0]; + for (int i = 1; i < bucket_cnt; i++) { + if (min_bucket[i] != INT_MAX) { + max_gap = max(min_bucket[i] - last_max, max_gap); + last_max = max_bucket[i]; + } + } + return max_gap; + } +}; diff --git a/167_two_sum_ii/two_sum.c b/167_two_sum_ii/two_sum.c index 38eb52d..86d4c4d 100644 --- a/167_two_sum_ii/two_sum.c +++ b/167_two_sum_ii/two_sum.c @@ -9,11 +9,11 @@ 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]; - if (diff < numbers[j]) { - while (i < --j && numbers[j + 1] == numbers[j]) {} - } else if (diff > numbers[j]) { - while (++i < j && numbers[i - 1] == numbers[i]) {} + int diff = target - numbers[i] - numbers[j]; + if (diff > 0) { + i++; + } else if (diff < 0) { + j--; } else { *returnSize = 2; int *indexes = malloc(*returnSize * sizeof(int)); diff --git a/167_two_sum_ii/two_sum.cc b/167_two_sum_ii/two_sum.cc new file mode 100644 index 0000000..4ba80b8 --- /dev/null +++ b/167_two_sum_ii/two_sum.cc @@ -0,0 +1,25 @@ +#include + +using namespace std; + +class Solution { +public: + vector twoSum(vector& numbers, int target) { + vector res; + int i = 0; + int j = numbers.size() - 1; + while (i < j) { + int diff = target - numbers[i] - numbers[j]; + if (diff > 0) { + i++; + } else if (diff < 0) { + j--; + } else { + res.push_back(i + 1); + res.push_back(j + 1); + break; + } + } + return res; + } +}; From eb736e293e1afc39bfca5fb775f8df80ffc196c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=8A=9B?= Date: Tue, 17 Nov 2020 16:14:47 +0800 Subject: [PATCH 109/211] Refine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马力 --- 215_kth_largest_element_in_an_array/kth_elem.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/215_kth_largest_element_in_an_array/kth_elem.c b/215_kth_largest_element_in_an_array/kth_elem.c index c82ef02..c4f6294 100644 --- a/215_kth_largest_element_in_an_array/kth_elem.c +++ b/215_kth_largest_element_in_an_array/kth_elem.c @@ -28,9 +28,7 @@ int findKthLargest(int* nums, int numsSize, int k) { int lo = 0, hi = numsSize - 1; for (; ;) { - printf("A:%d %d\n", lo, hi); int p = partition(nums, lo, hi); - printf("B:%d %d\n", p, numsSize - k); if (p < numsSize - k) { lo = p + 1; } else if (p > numsSize - k) { From 14b6e53fb3d6e2a2f048798054402a5acf57e9ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=8A=9B?= Date: Tue, 17 Nov 2020 16:19:27 +0800 Subject: [PATCH 110/211] Add C++ implementation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马力 --- .../bst_preorder.cc | 34 ++++++++++++++++ .../bst_postorder.cc | 40 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 144_binary_tree_preorder_traversal/bst_preorder.cc create mode 100644 145_binary_tree_postorder_traversal/bst_postorder.cc diff --git a/144_binary_tree_preorder_traversal/bst_preorder.cc b/144_binary_tree_preorder_traversal/bst_preorder.cc new file mode 100644 index 0000000..1304a65 --- /dev/null +++ b/144_binary_tree_preorder_traversal/bst_preorder.cc @@ -0,0 +1,34 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector res; + stack stk; + while (!stk.empty() || root != nullptr) { + if (root != nullptr) { + res.push_back(root->val); + stk.push(root); + root = root->left; + } else { + root = stk.top(); + stk.pop(); + root = root->right; + } + } + return res; + } +}; diff --git a/145_binary_tree_postorder_traversal/bst_postorder.cc b/145_binary_tree_postorder_traversal/bst_postorder.cc new file mode 100644 index 0000000..a73d170 --- /dev/null +++ b/145_binary_tree_postorder_traversal/bst_postorder.cc @@ -0,0 +1,40 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector postorderTraversal(TreeNode* root) { + vector res; + stack> stk; + while (!stk.empty() || root != nullptr) { + if (root != nullptr) { + stk.push(make_pair(root, root->right)); + root = root->left; + } else { + if (stk.top().second != nullptr) { + // Into right + root = stk.top().second; + stk.top().second = nullptr; + } else { + // True backtracing + res.push_back(stk.top().first->val); + stk.pop(); + root = nullptr; + } + } + } + return res; + } +}; From 292a7935e5d13c7312915e49b663d9634694a132 Mon Sep 17 00:00:00 2001 From: Tim Gates Date: Mon, 23 Nov 2020 22:36:19 +1100 Subject: [PATCH 111/211] docs: fix simple typo, possiblity -> possibility There is a small typo in 095_unique_binary_search_trees_ii/unique_bst.c. Should read `possibility` rather than `possiblity`. --- 095_unique_binary_search_trees_ii/unique_bst.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/095_unique_binary_search_trees_ii/unique_bst.c b/095_unique_binary_search_trees_ii/unique_bst.c index 41f1478..bde5770 100644 --- a/095_unique_binary_search_trees_ii/unique_bst.c +++ b/095_unique_binary_search_trees_ii/unique_bst.c @@ -20,7 +20,7 @@ * * i=2 * / \ - * (1,1) (3,3) // 1 possiblity + * (1,1) (3,3) // 1 possibility * * * i=3 From 12965203aac71b5f4f8a4094e450f1c4b62c16f0 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 25 Nov 2020 22:38:30 +0800 Subject: [PATCH 112/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 198_house_robber/robber.c | 11 +++-------- 213_house_robber_ii/robber.c | 13 +++++-------- 337_house_robber_iii/robber.cc | 31 +++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 16 deletions(-) create mode 100644 337_house_robber_iii/robber.cc diff --git a/198_house_robber/robber.c b/198_house_robber/robber.c index e255487..d76228b 100644 --- a/198_house_robber/robber.c +++ b/198_house_robber/robber.c @@ -9,20 +9,15 @@ static inline int max(int a, int b) static int rob(int* nums, int numsSize) { - if (numsSize == 0) { - return 0; - } - int i; - int taken = nums[0]; + int taken = 0; int untaken = 0; /* Record max profits of nums[0...i] respectively */ - for (i = 1; i < numsSize; i++) { + for (i = 0; i < numsSize; i++) { int tmp_taken = taken; - int tmp_untaken = untaken; /* Taken or untaken nums[i] */ taken = untaken + nums[i]; - untaken = max(tmp_taken, tmp_untaken); + untaken = max(tmp_taken, untaken); } return max(taken, untaken); diff --git a/213_house_robber_ii/robber.c b/213_house_robber_ii/robber.c index 391bb83..ed54519 100644 --- a/213_house_robber_ii/robber.c +++ b/213_house_robber_ii/robber.c @@ -10,15 +10,14 @@ static inline int max(int a, int b) static int _rob(int* nums, int numsSize) { int i; - int taken = nums[0]; + int taken = 0; int untaken = 0; /* Record max profits of nums[0...i] respectively */ - for (i = 1; i < numsSize; i++) { + for (i = 0; i < numsSize; i++) { int tmp_taken = taken; - int tmp_untaken = untaken; /* Taken or untaken nums[i] */ - taken = tmp_untaken + nums[i]; - untaken = max(tmp_taken, tmp_untaken); + taken = untaken + nums[i]; + untaken = max(tmp_taken, untaken); } return max(taken, untaken); @@ -26,9 +25,7 @@ static int _rob(int* nums, int numsSize) static int rob(int* nums, int numsSize) { - if (numsSize == 0) { - return 0; - } else if (numsSize == 1) { + if (numsSize == 1) { return nums[0]; } else { /* The first and the last element are adjacent */ diff --git a/337_house_robber_iii/robber.cc b/337_house_robber_iii/robber.cc new file mode 100644 index 0000000..b25e2cc --- /dev/null +++ b/337_house_robber_iii/robber.cc @@ -0,0 +1,31 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int rob(TreeNode* root) { + auto res = dfs(root); + return max(res.first, res.second); + } + + pair dfs(TreeNode *root) { + if (root == nullptr) { + return make_pair(0, 0); + } + auto subl = dfs(root->left); + auto subr = dfs(root->right); + int taken = root->val + subl.second + subr.second; + int untaken = max(subl.first, subl.second) + max(subr.first, subr.second); + return make_pair(taken, untaken); + } +}; From 98adda64f97860ac4befcb8e21b5436681f37ee2 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 25 Nov 2020 22:41:42 +0800 Subject: [PATCH 113/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 198_house_robber/robber.cc | 17 +++++++++++++++++ 213_house_robber_ii/robber.cc | 27 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 198_house_robber/robber.cc create mode 100644 213_house_robber_ii/robber.cc diff --git a/198_house_robber/robber.cc b/198_house_robber/robber.cc new file mode 100644 index 0000000..3d2ffb5 --- /dev/null +++ b/198_house_robber/robber.cc @@ -0,0 +1,17 @@ +#include + +using namespace std; + +class Solution { +public: + int rob(vector& nums) { + int taken = 0; + int untaken = 0; + for (int i = 0; i < nums.size(); i++) { + int tmp_taken = taken; + taken = untaken + nums[i]; + untaken = max(untaken, tmp_taken); + } + return max(taken, untaken); + } +}; diff --git a/213_house_robber_ii/robber.cc b/213_house_robber_ii/robber.cc new file mode 100644 index 0000000..0ace8ab --- /dev/null +++ b/213_house_robber_ii/robber.cc @@ -0,0 +1,27 @@ +#include + +using namespace std; + +class Solution { +public: + int rob(vector& nums) { + if (nums.size() == 1) { + return nums[0]; + } else { + return max(rob_(nums.begin() + 1, nums.end()), rob_(nums.begin(), nums.end() - 1)); + } + } + +private: + int rob_(vector::iterator begin, vector::iterator end) { + int taken = 0; + int untaken = 0; + vector::iterator i; + for (i = begin; i != end; i++) { + int tmp_taken = taken; + taken = untaken + *i; + untaken = max(untaken, tmp_taken); + } + return max(taken, untaken); + } +}; From 96639988e8ebfb8470eb5c734ee7895c1fda1ea4 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 26 Nov 2020 00:39:29 +0800 Subject: [PATCH 114/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../bst_max_path.cc | 36 +++++++++++++ .../zigzag.cc | 34 +++++++++++++ .../max_bst.cc | 51 +++++++++++++++++++ 543_diameter_of_binary_tree/diameter_bst.cc | 33 ++++++++++++ 563_binary_tree_tilt/tilt.cc | 35 +++++++++++++ 5 files changed, 189 insertions(+) create mode 100644 124_binary_tree_maximum_path_sum/bst_max_path.cc create mode 100644 1372_longest_zigzag_path_in_a_binary_tree/zigzag.cc create mode 100644 1373_maximum_sum_bst_in_binary_tree/max_bst.cc create mode 100644 543_diameter_of_binary_tree/diameter_bst.cc create mode 100644 563_binary_tree_tilt/tilt.cc diff --git a/124_binary_tree_maximum_path_sum/bst_max_path.cc b/124_binary_tree_maximum_path_sum/bst_max_path.cc new file mode 100644 index 0000000..ab1ef58 --- /dev/null +++ b/124_binary_tree_maximum_path_sum/bst_max_path.cc @@ -0,0 +1,36 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxPathSum(TreeNode* root) { + dfs(root); + return max_sum; + } + +private: + int max_sum = INT_MIN; + int dfs(TreeNode *root) { + if (root == nullptr) { + return 0; + } + + int subl = max(0, dfs(root->left)); + int subr = max(0, dfs(root->right)); + int sum = root->val + subl + subr; + max_sum = max(sum, max_sum); + return root->val + max(subl, subr); + } +}; diff --git a/1372_longest_zigzag_path_in_a_binary_tree/zigzag.cc b/1372_longest_zigzag_path_in_a_binary_tree/zigzag.cc new file mode 100644 index 0000000..be69eb1 --- /dev/null +++ b/1372_longest_zigzag_path_in_a_binary_tree/zigzag.cc @@ -0,0 +1,34 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int longestZigZag(TreeNode* root) { + dfs(root); + return maxzz - 1; + } +private: + int maxzz = 0; + pair dfs(TreeNode *root) { + if (root == nullptr) { + return make_pair(0, 0); + } + + auto subl = dfs(root->left); + auto subr = dfs(root->right); + int sublzz = 1 + subl.second; + int subrzz = 1 + subr.first; + maxzz = max(maxzz, max(sublzz, subrzz)); + return make_pair(sublzz, subrzz); + } +}; diff --git a/1373_maximum_sum_bst_in_binary_tree/max_bst.cc b/1373_maximum_sum_bst_in_binary_tree/max_bst.cc new file mode 100644 index 0000000..a1ba2a8 --- /dev/null +++ b/1373_maximum_sum_bst_in_binary_tree/max_bst.cc @@ -0,0 +1,51 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +struct TreeInfo { + bool isBst; + int min_val; + int max_val; + int sum_val; + TreeInfo() : isBst(true), min_val(INT_MAX), max_val(INT_MIN), sum_val(0) {} + TreeInfo(bool bst, int min, int max, int sum) : isBst(bst), min_val(min), max_val(max), sum_val(sum) {} +}; + +class Solution { +public: + int maxSumBST(TreeNode* root) { + dfs(root); + return max(0, max_sum); + } +private: + int max_sum = INT_MIN; + TreeInfo *dfs(TreeNode *root) { + if (root == nullptr) { + return new TreeInfo(); + } + + auto subl = dfs(root->left); + auto subr = dfs(root->right); + + int sum = root->val + subl->sum_val + subr->sum_val; + if (subl->isBst && subr->isBst && root->val > subl->max_val && root->val < subr->min_val) { + max_sum = max(sum, max_sum); + int min_val = min(root->val, subl->min_val); + int max_val = max(root->val, subr->max_val); + return new TreeInfo(true, min_val, max_val, sum); + } else { + return new TreeInfo(false, INT_MAX, INT_MIN, sum); + } + } +}; diff --git a/543_diameter_of_binary_tree/diameter_bst.cc b/543_diameter_of_binary_tree/diameter_bst.cc new file mode 100644 index 0000000..28d57fe --- /dev/null +++ b/543_diameter_of_binary_tree/diameter_bst.cc @@ -0,0 +1,33 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int diameterOfBinaryTree(TreeNode* root) { + dfs(root); + return max_diameter; + } + +private: + int max_diameter = 0; + int dfs(TreeNode* root) { + if (root == nullptr) { + return 0; + } + + int ld = dfs(root->left); + int rd = dfs(root->right); + max_diameter = max(max_diameter, ld + rd); + return 1 + max(ld, rd); + } +}; diff --git a/563_binary_tree_tilt/tilt.cc b/563_binary_tree_tilt/tilt.cc new file mode 100644 index 0000000..fec3498 --- /dev/null +++ b/563_binary_tree_tilt/tilt.cc @@ -0,0 +1,35 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int findTilt(TreeNode* root) { + dfs(root); + return tilt; + } + +private: + int tilt = 0; + int dfs(TreeNode *root) { + if (root == nullptr) { + return 0; + } + + int subl = dfs(root->left); + int subr = dfs(root->right); + tilt += abs(subl - subr); + return root->val + subl + subr; + } +}; From a8863f7de924ec606702aafeeadea0b5a67352f8 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 29 Nov 2020 00:16:18 +0800 Subject: [PATCH 115/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 072_edit_distance/edit_distance.cc | 2 +- .../max_bst.cc | 1 + 416_partition_equal_subset_sum/partition.cc | 28 +++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 416_partition_equal_subset_sum/partition.cc diff --git a/072_edit_distance/edit_distance.cc b/072_edit_distance/edit_distance.cc index b7c6bb5..deb09f8 100644 --- a/072_edit_distance/edit_distance.cc +++ b/072_edit_distance/edit_distance.cc @@ -23,7 +23,7 @@ class Solution { } } } - + return dp[word1.length()][word2.length()]; } }; diff --git a/1373_maximum_sum_bst_in_binary_tree/max_bst.cc b/1373_maximum_sum_bst_in_binary_tree/max_bst.cc index a1ba2a8..2d42627 100644 --- a/1373_maximum_sum_bst_in_binary_tree/max_bst.cc +++ b/1373_maximum_sum_bst_in_binary_tree/max_bst.cc @@ -41,6 +41,7 @@ class Solution { int sum = root->val + subl->sum_val + subr->sum_val; if (subl->isBst && subr->isBst && root->val > subl->max_val && root->val < subr->min_val) { max_sum = max(sum, max_sum); + // For leaf nodes int min_val = min(root->val, subl->min_val); int max_val = max(root->val, subr->max_val); return new TreeInfo(true, min_val, max_val, sum); diff --git a/416_partition_equal_subset_sum/partition.cc b/416_partition_equal_subset_sum/partition.cc new file mode 100644 index 0000000..79e8edf --- /dev/null +++ b/416_partition_equal_subset_sum/partition.cc @@ -0,0 +1,28 @@ +#include + +using namespace std; + +class Solution { +public: + bool canPartition(vector& nums) { + int sum = 0; + for (int n : nums) { + sum += n; + } + if (sum % 2 != 0) { + return false; + } + + vector dp(sum / 2 + 1, false); + dp[0] = true; + for (int i = 0; i < nums.size(); i++) { + for (int j = sum / 2 ; j >= 0; j--) { + if (j >= nums[i]) { + dp[j] = dp[j] || dp[j - nums[i]]; + } + } + } + + return dp[sum / 2]; + } +}; From 8bad1f667d6669bd84ed77a1d0df156aa06b182c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 3 Dec 2020 14:01:48 +0800 Subject: [PATCH 116/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 018_four_sum/four_sum.cc | 2 +- 146_lru_cache/lru_cache.cc | 10 ++- 460_lfu_cache/Makefile | 2 + 460_lfu_cache/lfu_cache.cc | 124 +++++++++++++++++++++++++++++++++++++ 4 files changed, 134 insertions(+), 4 deletions(-) create mode 100644 460_lfu_cache/Makefile create mode 100644 460_lfu_cache/lfu_cache.cc diff --git a/018_four_sum/four_sum.cc b/018_four_sum/four_sum.cc index dd7a5e5..d661eb9 100644 --- a/018_four_sum/four_sum.cc +++ b/018_four_sum/four_sum.cc @@ -33,7 +33,7 @@ class Solution { } } } else { - for (vector::iterator it = lo; it + k - 1 != hi + 1; it++) { + for (auto it = lo; it + k - 1 != hi + 1; it++) { if (it > lo && *(it - 1) == *it) { continue; } stack.push_back(*it); k_sum(it + 1, hi, target - *it, k - 1, stack, res); diff --git a/146_lru_cache/lru_cache.cc b/146_lru_cache/lru_cache.cc index 123806e..a0b3d67 100644 --- a/146_lru_cache/lru_cache.cc +++ b/146_lru_cache/lru_cache.cc @@ -11,7 +11,7 @@ using namespace std; class LRUCache { public: LRUCache(int capacity) { - capacity_ = capacity; + cap_ = capacity; } int get(int key) { @@ -30,10 +30,14 @@ class LRUCache { } void put(int key, int value) { + if (cap_ <= 0) { + return; + } + if (ht_.find(key) != ht_.end()) { li_.erase(ht_[key]); } else { - if (li_.size() == capacity_) { + if (li_.size() == cap_) { auto lru = li_.back(); li_.pop_back(); ht_.erase(lru.first); @@ -44,7 +48,7 @@ class LRUCache { } private: - int capacity_; + int cap_; list> li_; unordered_map>::iterator> ht_; }; diff --git a/460_lfu_cache/Makefile b/460_lfu_cache/Makefile new file mode 100644 index 0000000..36ebfc3 --- /dev/null +++ b/460_lfu_cache/Makefile @@ -0,0 +1,2 @@ +all: + g++ -O1 -std=c++11 -o test lfu_cache.cc diff --git a/460_lfu_cache/lfu_cache.cc b/460_lfu_cache/lfu_cache.cc new file mode 100644 index 0000000..749fac8 --- /dev/null +++ b/460_lfu_cache/lfu_cache.cc @@ -0,0 +1,124 @@ +#include +#include +#include +#include + +using namespace std; + +class LFUCache { + typedef struct LFU { + int key_; + int value_; + int freq_; + LFU(int key, int value, int freq) : key_(key), value_(value), freq_(freq) {}; + } LFU; + +public: + LFUCache(int capacity) { + cap_ = capacity; + } + + int get(int key) { + if (key_map_.find(key) == key_map_.end()) { + return -1; + } + + freq_incr(key); + return (*key_map_[key])->value_; + } + + void put(int key, int value) { + if (cap_ <= 0) { + return; + } + + if (key_map_.find(key) != key_map_.end()) { + freq_incr(key); + (*key_map_[key])->value_ = value; + } else { + if (key_map_.size() == cap_) { + freq_del(); + } + + if (key_map_.empty()) { + freq_map_[1] = li_; + } + auto& li = freq_map_[1]; + li.push_front(new LFU(key, value, 1)); + key_map_[key] = li.begin(); + } + } + +private: + void freq_incr(int key) { + int value = (*key_map_[key])->value_; + int freq = (*key_map_[key])->freq_; + + // list.erase + map.erase + freq_map_[freq].erase(key_map_[key]); + if (freq_map_[freq].empty()) { + freq_map_.erase(freq); + } + + if (freq_map_.find(freq + 1) == freq_map_.end()) { + freq_map_[freq + 1] = li_; + } + + auto& li = freq_map_[freq + 1]; + li.push_front(new LFU(key, value, freq + 1)); + key_map_[key] = li.begin(); + } + + void freq_del() { + auto& li = freq_map_.begin()->second; + key_map_.erase(li.back()->key_); + li.pop_back(); + } + + void freq_map_show() { + cout << "freq map show:" << endl; + for (auto it : freq_map_) { + cout << it.first << ": "; + for (auto lfu : it.second) + cout << lfu->key_ << " "; + cout << "\t"; + } + cout << endl; + } + + int cap_; + list li_; + map freq_map_; + unordered_map key_map_; +}; + +/** + * Your LFUCache object will be instantiated and called as such: + * LFUCache* obj = new LFUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); + */ + +int main() { + LFUCache *lfu = new LFUCache(2); + lfu->put(1, 1); + cout << "put 1 1" << endl; + lfu->put(2, 2); + cout << "put 2 2" << endl; + cout << "get " << lfu->get(1) << endl; // return 1 + lfu->put(3, 3); // evicts key 2 + cout << "put 3 3" << endl; + //lfu->get(2); // return -1 (not found) + cout << "get " << lfu->get(2) << endl; + //lfu->get(3); // return 3 + cout << "get " << lfu->get(3) << endl; + lfu->put(4, 4); // evicts key 1. + cout << "put 4 4" << endl; + //lfu->get(1); // return -1 (not found) + cout << "get " << lfu->get(1) << endl; + //lfu->get(3); // return 3 + cout << "get " << lfu->get(3) << endl; + //lfu->get(4); // return 4 + cout << "get " << lfu->get(4) << endl; + return 0; +} From e58c64eea99cec39da30b69cd42b9fbdd91c1f5f Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 14 Dec 2020 23:50:42 +0800 Subject: [PATCH 117/211] Refine Signed-off-by: begeekmyfriend --- 049_group_anagrams/anagrams.c | 5 +- 126_word_ladder_ii/word_ladder.c | 52 +++---------- 127_word_ladder/word_ladder.c | 46 ++--------- 146_lru_cache/lru_cache.c | 128 ++++++++++--------------------- 4 files changed, 60 insertions(+), 171 deletions(-) diff --git a/049_group_anagrams/anagrams.c b/049_group_anagrams/anagrams.c index 7838798..52d5bb0 100644 --- a/049_group_anagrams/anagrams.c +++ b/049_group_anagrams/anagrams.c @@ -43,7 +43,7 @@ static char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** r qsort(words[i], len, sizeof(char), compare); int hash = BKDRHash(words[i], hash_size); /* find available hash bucket */ - for (j = hash; ht[j].num > 0 && strcmp(ht[j].word, words[i]); j = ++j % hash_size) {} + for (j = hash; ht[j].num > 0 && strcmp(ht[j].word, words[i]); j = (j + 1) % hash_size) {} if (ht[j].num == 0) { ht[j].word = words[i]; count++; @@ -52,7 +52,6 @@ static char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** r } int k = 0; - struct hlist_node *p; char ***lists = malloc(count * sizeof(char **)); *returnColumnSizes = malloc(count * sizeof(int)); for (i = 0; i < hash_size; i++) { @@ -74,7 +73,7 @@ static char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** r int main(int argc, char **argv) { int *column_sizes, count = 0, i, j; - char ***lists = groupAnagrams(argv + 1, argc - 1, &column_sizes, &count); + char ***lists = groupAnagrams(argv + 1, argc - 1, &count, &column_sizes); for (i = 0; i < count; i++) { for (j = 0; j < column_sizes[i]; j++) { printf("%s ", lists[i][j]); diff --git a/126_word_ladder_ii/word_ladder.c b/126_word_ladder_ii/word_ladder.c index a4cd2f7..d0980e0 100644 --- a/126_word_ladder_ii/word_ladder.c +++ b/126_word_ladder_ii/word_ladder.c @@ -17,40 +17,6 @@ #define list_for_each_safe(p, n, head) \ for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - -struct hlist_node; - -struct hlist_head { - struct hlist_node *first; -}; - -struct hlist_node { - struct hlist_node *next, **pprev; -}; - -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; -} - -static inline int hlist_empty(struct hlist_head *h) { - return !h->first; -} - -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) -{ - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; -} - struct list_head { struct list_head *next, *prev; }; @@ -98,7 +64,7 @@ static inline void list_del(struct list_head *entry) struct word_node { int step; char *word; - struct hlist_node node; + struct list_head node; }; struct word_tree { @@ -121,11 +87,11 @@ static int BKDRHash(char* str, int size) return hash % size; } -static struct word_node *find(char *word, struct hlist_head *hhead, int size, int step) +static struct word_node *find(char *word, struct list_head *hheads, int size, int step) { - struct hlist_node *p; + struct list_head *p; int hash = BKDRHash(word, size); - hlist_for_each(p, &hhead[hash]) { + list_for_each(p, &hheads[hash]) { struct word_node *node = list_entry(p, struct word_node, node); if (!strcmp(node->word, word)) { if (node->step == 0 || node->step == step) { @@ -160,9 +126,9 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int int hashsize = wordListSize * 2; char *word = malloc(len + 1); - struct hlist_head *hhead = malloc(hashsize * sizeof(*hhead)); + struct list_head *hheads = malloc(hashsize * sizeof(*hheads)); for (i = 0; i < hashsize; i++) { - INIT_HLIST_HEAD(hhead + i); + INIT_LIST_HEAD(hheads + i); } struct list_head *level_heads = malloc(wordListSize * sizeof(*level_heads)); @@ -177,7 +143,7 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int node->word = wordList[i]; node->step = 0; int hash = BKDRHash(wordList[i], hashsize); - hlist_add_head(&node->node, &hhead[hash]); + list_add(&node->node, &hheads[hash]); } /* FIFO */ @@ -193,7 +159,7 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int root->parents = malloc(sizeof(void *)); root->parents[0] = NULL; list_add_tail(&root->sibling, &level_heads[0]); - node = find(beginWord, hhead, hashsize, 1); + node = find(beginWord, hheads, hashsize, 1); if (node != NULL) { node->step = 1; } @@ -207,7 +173,7 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int char o = word[i]; for (c = 'a'; c <= 'z'; c++) { word[i] = c; - node = find(word, hhead, hashsize, first->step + 1); + node = find(word, hheads, hashsize, first->step + 1); if (node != NULL) { int enqueue = 1; list_for_each(p, &level_heads[first->step]) { diff --git a/127_word_ladder/word_ladder.c b/127_word_ladder/word_ladder.c index c025ce4..013d081 100644 --- a/127_word_ladder/word_ladder.c +++ b/127_word_ladder/word_ladder.c @@ -17,36 +17,6 @@ #define list_for_each_safe(p, n, head) \ for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - -struct hlist_node; - -struct hlist_head { - struct hlist_node *first; -}; - -struct hlist_node { - struct hlist_node *next, **pprev; -}; - -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; -} - -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) -{ - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; -} - struct list_head { struct list_head *next, *prev; }; @@ -94,7 +64,7 @@ static inline void list_del(struct list_head *entry) struct word_node { int step; char *word; - struct hlist_node node; + struct list_head node; struct list_head link; }; @@ -108,11 +78,11 @@ static int BKDRHash(char* str, int size) return hash % size; } -static struct word_node *find(char *word, struct hlist_head *hhead, int size) +static struct word_node *find(char *word, struct list_head *hheads, int size) { - struct hlist_node *p; + struct list_head *p; int hash = BKDRHash(word, size); - hlist_for_each(p, &hhead[hash]) { + list_for_each(p, &hheads[hash]) { struct word_node *node = list_entry(p, struct word_node, node); if (node->step == 0 && !strcmp(node->word, word)) { return node; @@ -128,9 +98,9 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor struct list_head queue; struct word_node *node; - struct hlist_head *hhead = malloc(wordListSize * sizeof(*hhead)); + struct list_head *hheads = malloc(wordListSize * sizeof(*hheads)); for (i = 0; i < wordListSize; i++) { - INIT_HLIST_HEAD(hhead + i); + INIT_LIST_HEAD(hheads + i); } /* Add into hash list */ @@ -139,7 +109,7 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor node->word = wordList[i]; node->step = 0; int hash = BKDRHash(wordList[i], wordListSize); - hlist_add_head(&node->node, &hhead[hash]); + list_add(&node->node, &hheads[hash]); } /* FIFO */ @@ -157,7 +127,7 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor for (c = 'a'; c <= 'z'; c++) { if (c == o) continue; word[i] = c; - node = find(word, hhead, wordListSize); + node = find(word, hheads, wordListSize); if (node != NULL) { list_add_tail(&node->link, &queue); node->step = first->step + 1; diff --git a/146_lru_cache/lru_cache.c b/146_lru_cache/lru_cache.c index 3618501..e268453 100644 --- a/146_lru_cache/lru_cache.c +++ b/146_lru_cache/lru_cache.c @@ -7,12 +7,6 @@ #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) #define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) @@ -22,44 +16,6 @@ #define list_for_each_safe(p, n, head) \ for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) -struct hlist_node; - -struct hlist_head { - struct hlist_node *first; -}; - -struct hlist_node { - struct hlist_node *next, **pprev; -}; - -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; -} - -static inline int hlist_empty(struct hlist_head *h) { - return !h->first; -} - -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) -{ - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; -} - -static inline void hlist_del(struct hlist_node *n) -{ - struct hlist_node *next = n->next; - struct hlist_node **pprev = n->pprev; - *pprev = next; - if (next != NULL) { - next->pprev = pprev; - } -} - struct list_head { struct list_head *next, *prev; }; @@ -129,26 +85,26 @@ typedef struct { int capacity; int count; struct list_head dhead; - struct hlist_head hhead[]; + struct list_head hheads[]; } LRUCache; typedef struct { int key; int value; - struct hlist_node node; - struct list_head link; + struct list_head hlink; + struct list_head dlink; } LRUNode; LRUCache *lRUCacheCreate(int capacity) { int i; - LRUCache *obj = malloc(2 * sizeof(int) + sizeof(struct list_head) + capacity * sizeof(struct hlist_head)); + LRUCache *obj = malloc(sizeof(*obj) + capacity * sizeof(struct list_head)); obj->count = 0; obj->capacity = capacity; INIT_LIST_HEAD(&obj->dhead); for (i = 0; i < capacity; i++) { - INIT_HLIST_HEAD(&obj->hhead[i]); + INIT_LIST_HEAD(&obj->hheads[i]); } return obj; } @@ -157,9 +113,9 @@ void lRUCacheFree(LRUCache *obj) { struct list_head *pos, *n; list_for_each_safe(pos, n, &obj->dhead) { - LRUNode *cache = list_entry(pos, LRUNode, link); - list_del(&cache->link); - free(cache); + LRUNode *lru = list_entry(pos, LRUNode, dlink); + list_del(&lru->dlink); + free(lru); } free(obj); } @@ -167,13 +123,13 @@ void lRUCacheFree(LRUCache *obj) int lRUCacheGet(LRUCache *obj, int key) { int hash = key % obj->capacity; - struct hlist_node *pos; - hlist_for_each(pos, &obj->hhead[hash]) { - LRUNode *cache = list_entry(pos, LRUNode, node); - if (cache->key == key) { + struct list_head *pos; + list_for_each(pos, &obj->hheads[hash]) { + LRUNode *lru = list_entry(pos, LRUNode, hlink); + if (lru->key == key) { /* Move it to header */ - list_move(&cache->link, &obj->dhead); - return cache->value; + list_move(&lru->dlink, &obj->dhead); + return lru->value; } } return -1; @@ -181,32 +137,30 @@ int lRUCacheGet(LRUCache *obj, int key) void lRUCachePut(LRUCache *obj, int key, int value) { - LRUNode *cache = NULL; + LRUNode *lru; int hash = key % obj->capacity; - struct hlist_node *pos; - hlist_for_each(pos, &obj->hhead[hash]) { - LRUNode *c = list_entry(pos, LRUNode, node); - if (c->key == key) { - list_move(&c->link, &obj->dhead); - cache = c; - break; + struct list_head *pos; + list_for_each(pos, &obj->hheads[hash]) { + lru = list_entry(pos, LRUNode, hlink); + if (lru->key == key) { + list_move(&lru->dlink, &obj->dhead); + lru->value = value; + return; } } - if (cache == NULL) { - if (obj->count == obj->capacity) { - cache = list_last_entry(&obj->dhead, LRUNode, link); - list_del(&cache->link); - hlist_del(&cache->node); - } else { - cache = malloc(sizeof(LRUNode)); - obj->count++; - } - cache->key = key; - list_add(&cache->link, &obj->dhead); - hlist_add_head(&cache->node, &obj->hhead[hash]); + if (obj->count == obj->capacity) { + lru = list_last_entry(&obj->dhead, LRUNode, dlink); + list_del(&lru->dlink); + list_del(&lru->hlink); + } else { + lru = malloc(sizeof(LRUNode)); + obj->count++; } - cache->value = value; + lru->key = key; + list_add(&lru->dlink, &obj->dhead); + list_add(&lru->hlink, &obj->hheads[hash]); + lru->value = value; } void lRUCacheDump(LRUCache *obj) @@ -214,15 +168,15 @@ void lRUCacheDump(LRUCache *obj) if (obj == NULL) return; int i; - LRUNode *cache; + LRUNode *lru; printf(">>> Total %d nodes: \n", obj->count); for (i = 0; i < obj->count; i++) { printf("hash:%d:", i); - struct hlist_node *pos; - hlist_for_each(pos, &obj->hhead[i]) { - cache = list_entry(pos, LRUNode, node); - if (cache != NULL) { - printf(" (%d %d)", cache->key, cache->value); + struct list_head *pos; + list_for_each(pos, &obj->hheads[i]) { + lru = list_entry(pos, LRUNode, hlink); + if (lru != NULL) { + printf(" (%d %d)", lru->key, lru->value); } } printf("\n"); @@ -231,8 +185,8 @@ void lRUCacheDump(LRUCache *obj) printf(">>> Double list dump\n"); struct list_head *p; list_for_each(p, &obj->dhead) { - cache = list_entry(p, LRUNode, link); - printf("(%d %d)\n", cache->key, cache->value); + lru = list_entry(p, LRUNode, dlink); + printf("(%d %d)\n", lru->key, lru->value); } } From fd94736611ed28de681d3e102789f1b58108d4c9 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 15 Dec 2020 17:33:17 +0800 Subject: [PATCH 118/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 146_lru_cache/lru_cache.cc | 2 +- 460_lfu_cache/Makefile | 3 +- 460_lfu_cache/lfu_cache.c | 462 +++++++++++++++++++++++++++++++++++++ 460_lfu_cache/lfu_cache.cc | 31 ++- 4 files changed, 479 insertions(+), 19 deletions(-) create mode 100644 460_lfu_cache/lfu_cache.c diff --git a/146_lru_cache/lru_cache.cc b/146_lru_cache/lru_cache.cc index a0b3d67..9a21c81 100644 --- a/146_lru_cache/lru_cache.cc +++ b/146_lru_cache/lru_cache.cc @@ -19,7 +19,7 @@ class LRUCache { return -1; } - int value = ht_[key]->second; + int value = (*ht_[key]).second; if (li_.front().first != key) { li_.erase(ht_[key]); li_.push_front(make_pair(key, value)); diff --git a/460_lfu_cache/Makefile b/460_lfu_cache/Makefile index 36ebfc3..d324ed9 100644 --- a/460_lfu_cache/Makefile +++ b/460_lfu_cache/Makefile @@ -1,2 +1,3 @@ all: - g++ -O1 -std=c++11 -o test lfu_cache.cc + gcc -O1 -o test lfu_cache.c + #g++ -O1 -std=c++11 -o test lfu_cache.cc diff --git a/460_lfu_cache/lfu_cache.c b/460_lfu_cache/lfu_cache.c new file mode 100644 index 0000000..ec02bff --- /dev/null +++ b/460_lfu_cache/lfu_cache.c @@ -0,0 +1,462 @@ +#include +#include +#include + +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) +#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) + +#define list_for_each(p, head) \ + for (p = (head)->next; p != (head); p = p->next) + +#define list_for_each_safe(p, n, head) \ + for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) + +struct list_head { + struct list_head *next, *prev; +}; + +typedef struct FreqAVLNode { + int freq; + int height; + struct FreqAVLNode *children[2]; + struct FreqAVLNode *parent; + struct list_head dhead; /* freq_list head */ +} FreqAVLNode; + +typedef struct { + FreqAVLNode *root; +} FreqAVLTree; + +typedef struct LFUNode { + int key; + int val; + int freq; + FreqAVLNode *node; /* freq tree node */ + struct list_head dlink; /* freq_list */ + struct list_head key_link; /* key_map */ +} LFUNode; + +typedef struct { + int size; + int capacity; + FreqAVLTree *tree; + struct list_head hheads[0]; +} LFUCache; + +static inline void +INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list->prev = list; +} + +static inline int +list_empty(const struct list_head *head) +{ + return (head->next == head); +} + +static inline void +__list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +static inline void +list_add(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head, head->next); +} + +static inline void +list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} + +static inline void +__list_del(struct list_head *entry) +{ + entry->next->prev = entry->prev; + entry->prev->next = entry->next; +} + +static inline void +list_del(struct list_head *entry) +{ + __list_del(entry); + entry->next = entry->prev = NULL; +} + +static inline int height(FreqAVLNode *node) +{ + return node != NULL ? node->height : 0; +} + +static inline void avl_update_height(FreqAVLNode *node) +{ + int ld = height(node->children[0]); + int rd = height(node->children[1]); + node->height = 1 + (ld > rd ? ld : rd); +} + +static void avl_node_replace(FreqAVLTree *tree, FreqAVLNode *old, FreqAVLNode *new) +{ + if (new != NULL) { + new->parent = old->parent; + } + + FreqAVLNode *parent = old->parent; + if (parent == NULL) { + tree->root = new; + } else { + if (parent->children[0] == old) { + parent->children[0] = new; + } else { + parent->children[1] = new; + } + avl_update_height(parent); + } +} + +static FreqAVLNode *avl_node_rotate(FreqAVLTree *tree, FreqAVLNode *node, int side) +{ + /* The child of this node will take its place: + for a left rotation, it is the right child, and vice versa. */ + FreqAVLNode *new = node->children[1 - side]; + + /* Make new the root, rearrange pointers */ + avl_node_replace(tree, node, new); + node->children[1 - side] = new->children[side]; + new->children[side] = node; + + /* Update parent references */ + node->parent = new; + if (node->children[1 - side] != NULL) { + node->children[1 - side]->parent = node; + } + + /* Update heights of the affected nodes */ + avl_update_height(new); + avl_update_height(node); + + return new; +} + +static FreqAVLNode *avl_node_balance(FreqAVLTree *tree, FreqAVLNode *node) +{ + FreqAVLNode *left = node->children[0]; + FreqAVLNode *right = node->children[1]; + + int diff = height(left) - height(right); + if (diff <= -2) { + /* Biased toward the right side */ + if (height(right->children[0]) > height(right->children[1])) { + /* double rotation: at node->right->left */ + avl_node_rotate(tree, right, 1); + } + /* single rotation: at node->right->right */ + node = avl_node_rotate(tree, node, 0); + } else if (diff >= 2) { + /* Biased toward the left side */ + if (height(left->children[0]) < height(left->children[1])) { + /* double rotation: at node->left->right */ + avl_node_rotate(tree, left, 0); + } + /* single rotation: at node->left->left */ + node = avl_node_rotate(tree, node, 1); + } + + avl_update_height(node); + return node; +} + +static void avl_tree_balance(FreqAVLTree *tree, FreqAVLNode *node) +{ + while (node != NULL) { + node = avl_node_balance(tree, node); + node = node->parent; + } +} + +static FreqAVLNode *avl_tree_insert(FreqAVLTree *tree, int freq) +{ + /* Walk down the tree until we reach a NULL pointer */ + FreqAVLNode *parent = NULL; + FreqAVLNode **rover = &tree->root; + while (*rover != NULL) { + parent = *rover; + if (freq < (*rover)->freq) { + rover = &((*rover)->children[0]); + } else { + rover = &((*rover)->children[1]); + } + } + + /* Create a new node and insert into parent's children link */ + FreqAVLNode *node = malloc(sizeof(*node)); + INIT_LIST_HEAD(&node->dhead); + node->children[0] = NULL; + node->children[1] = NULL; + node->parent = parent; + node->freq = freq; + node->height = 1; + + /* Insert at parent's children link (assign the children pointer value) */ + *rover = node; + /* Rebalance the tree */ + avl_tree_balance(tree, parent); + return node; +} + +static FreqAVLNode *avl_node_closest_get(FreqAVLTree *tree, FreqAVLNode *node) +{ + FreqAVLNode *left = node->children[0]; + FreqAVLNode *right = node->children[1]; + if (left == NULL && right == NULL) { + /* return NULL if leaf node */ + return NULL; + } + + /* Search down the tree, back towards the center. */ + int side = height(left) > height(right) ? 0 : 1; + FreqAVLNode *closest = node->children[side]; + while (closest->children[1 - side] != NULL) { + closest = closest->children[1 - side]; + } + + /* Unlink the closest node, and hook in its remaining child + * (if it has one) to replace it. */ + avl_node_replace(tree, closest, closest->children[side]); + + /* Update the subtree height for the closest node's old parent. */ + avl_update_height(closest->parent); + return closest; +} + +static void avl_node_erase(FreqAVLTree *tree, FreqAVLNode *node) +{ + /* The node to be erased must be swapped with an "adjacent" node, ie. + * one which has the closest key to this one. Find the node to swap with. */ + FreqAVLNode *startpoint; + FreqAVLNode *swap_node = avl_node_closest_get(tree, node); + if (swap_node == NULL) { + /* This is a leaf node and has no children, therefore + * it can be immediately erased. */ + avl_node_replace(tree, node, NULL); + /* Start rebalancing from the parent of the original node */ + startpoint = node->parent; + } else { + /* We will start rebalancing from the old parent of the swap node. + * Sometimes, the old parent is the node we are removing, + * in which case we must start rebalancing from the swap node. */ + if (swap_node->parent == node) { + startpoint = swap_node; + } else { + startpoint = swap_node->parent; + } + + /* Copy references */ + int i; + for (i = 0; i < 2; i++) { + swap_node->children[i] = node->children[i]; + if (swap_node->children[i] != NULL) { + swap_node->children[i]->parent = swap_node; + } + } + + swap_node->height = node->height; + /* Link the parent's reference to this node */ + avl_node_replace(tree, node, swap_node); + } + + free(node); + + /* Rebalance the tree */ + avl_tree_balance(tree, startpoint); +} + +static FreqAVLNode *avl_tree_min_get(FreqAVLTree *tree) +{ + FreqAVLNode *node = tree->root; + while (node->children[0] != NULL) { + node = node->children[0]; + } + return node; +} + +static FreqAVLTree *avl_tree_init(void) +{ + FreqAVLTree *tree = malloc(sizeof(*tree)); + tree->root = NULL; + return tree; +} + +static void avl_node_destory_recursive(FreqAVLNode *root) +{ + if (root == NULL) { + return; + } + + avl_node_destory_recursive(root->children[0]); + avl_node_destory_recursive(root->children[1]); + + free(root); +} + +static void avl_tree_destory(FreqAVLTree *tree) +{ + avl_node_destory_recursive(tree->root); +} + +static void freq_incr(FreqAVLTree* tree, LFUNode *lfu, int key) +{ + /* erase */ + list_del(&lfu->dlink); + if (list_empty(&lfu->node->dhead)) { + avl_node_erase(tree, lfu->node); + } + + /* New frequency */ + int freq = ++lfu->freq; + lfu->node = avl_tree_insert(tree, freq); + list_add(&lfu->dlink, &lfu->node->dhead); +} + +LFUCache* lFUCacheCreate(int capacity) +{ + int i; + LFUCache* obj = malloc(sizeof(*obj) + capacity * sizeof(struct list_head)); + obj->size = 0; + obj->capacity = capacity; + obj->tree = avl_tree_init(); + for (i = 0; i < capacity; i++) { + INIT_LIST_HEAD(&obj->hheads[i]); + } + return obj; +} + +int lFUCacheGet(LFUCache* obj, int key) +{ + struct list_head *pos; + int hash = key % obj->capacity; + list_for_each(pos, &obj->hheads[hash]) { + LFUNode *lfu = list_entry(pos, LFUNode, key_link); + if (lfu->key == key) { + freq_incr(obj->tree, lfu, key); + return lfu->val; + } + } + return -1; +} + +void lFUCachePut(LFUCache* obj, int key, int value) +{ + if (obj->capacity <= 0) { + return; + } + + LFUNode *lfu; + int hash = key % obj->capacity; + struct list_head *pos; + list_for_each(pos, &obj->hheads[hash]) { + lfu = list_entry(pos, LFUNode, key_link); + if (lfu->key == key) { + freq_incr(obj->tree, lfu, key); + lfu->val = value; + return; + } + } + + /* squeeze minimum frequency */ + if (obj->size == obj->capacity) { + FreqAVLNode *node = avl_tree_min_get(obj->tree); + lfu = list_last_entry(&node->dhead, LFUNode, dlink); + list_del(&lfu->dlink); + list_del(&lfu->key_link); + if (list_empty(&node->dhead)) { + avl_node_erase(obj->tree, node); + } + } else { + /* new LFU */ + obj->size++; + lfu = malloc(sizeof(*lfu)); + } + + lfu->key = key; + lfu->val = value; + lfu->freq = 1; + lfu->node = avl_tree_insert(obj->tree, lfu->freq); + list_add(&lfu->dlink, &lfu->node->dhead); + list_add(&lfu->key_link, &obj->hheads[hash]); +} + +void lFUCacheFree(LFUCache* obj) +{ + int i; + for (i = 0; i < obj->capacity; i++) { + struct list_head *pos, *n; + list_for_each_safe(pos, n, &obj->hheads[i]) { + LFUNode *lfu = list_entry(pos, LFUNode, key_link); + list_del(&lfu->dlink); + list_del(&lfu->key_link); + free(lfu); + } + } + + avl_tree_destory(obj->tree); + free(obj); +} + +/** + * Your LFUCache struct will be instantiated and called as such: + * LFUCache* obj = lFUCacheCreate(capacity); + * int param_1 = lFUCacheGet(obj, key); + + * lFUCachePut(obj, key, value); + + * lFUCacheFree(obj); +*/ + +int main(void) +{ + LFUCache* obj = lFUCacheCreate(2); +#if 1 + lFUCachePut(obj, 1, 1); + printf("Put 1 1\n"); + lFUCachePut(obj, 2, 2); + printf("Put 2 2\n"); + printf("Get 1 %d\n", lFUCacheGet(obj, 1)); + lFUCachePut(obj, 3, 3); + printf("Put 3 3\n"); + printf("Get 2 %d\n", lFUCacheGet(obj, 2)); + printf("Get 3 %d\n", lFUCacheGet(obj, 3)); + lFUCachePut(obj, 4, 4); + printf("Put 4 4\n"); + printf("Get 1 %d\n", lFUCacheGet(obj, 1)); + printf("Get 3 %d\n", lFUCacheGet(obj, 3)); + printf("Get 4 %d\n", lFUCacheGet(obj, 4)); +#else + lFUCachePut(obj, 2, 1); + printf("Put 2 1\n"); + lFUCachePut(obj, 3, 2); + printf("Put 3 2\n"); + printf("Get 3 %d\n", lFUCacheGet(obj, 3)); + printf("Get 2 %d\n", lFUCacheGet(obj, 2)); + lFUCachePut(obj, 4, 3); + printf("Put 4 3\n"); + printf("Get 2 %d\n", lFUCacheGet(obj, 2)); + printf("Get 3 %d\n", lFUCacheGet(obj, 3)); + printf("Get 4 %d\n", lFUCacheGet(obj, 4)); +#endif + lFUCacheFree(obj); + return 0; +} diff --git a/460_lfu_cache/lfu_cache.cc b/460_lfu_cache/lfu_cache.cc index 749fac8..134d5fa 100644 --- a/460_lfu_cache/lfu_cache.cc +++ b/460_lfu_cache/lfu_cache.cc @@ -26,7 +26,7 @@ class LFUCache { freq_incr(key); return (*key_map_[key])->value_; } - + void put(int key, int value) { if (cap_ <= 0) { return; @@ -37,15 +37,13 @@ class LFUCache { (*key_map_[key])->value_ = value; } else { if (key_map_.size() == cap_) { - freq_del(); + // squeeze minimum frequency + auto& li = freq_map_.begin()->second; + key_map_.erase(li.back()->key_); + li.pop_back(); } - if (key_map_.empty()) { - freq_map_[1] = li_; - } - auto& li = freq_map_[1]; - li.push_front(new LFU(key, value, 1)); - key_map_[key] = li.begin(); + _freq_incr(key, value, 0); } } @@ -54,12 +52,17 @@ class LFUCache { int value = (*key_map_[key])->value_; int freq = (*key_map_[key])->freq_; - // list.erase + map.erase - freq_map_[freq].erase(key_map_[key]); - if (freq_map_[freq].empty()) { + // list.erase + freq_map.erase + auto& li = freq_map_[freq]; + li.erase(key_map_[key]); + if (li.empty()) { freq_map_.erase(freq); } + _freq_incr(key, value, freq); + } + + void _freq_incr(int key, int value, int freq) { if (freq_map_.find(freq + 1) == freq_map_.end()) { freq_map_[freq + 1] = li_; } @@ -69,12 +72,6 @@ class LFUCache { key_map_[key] = li.begin(); } - void freq_del() { - auto& li = freq_map_.begin()->second; - key_map_.erase(li.back()->key_); - li.pop_back(); - } - void freq_map_show() { cout << "freq map show:" << endl; for (auto it : freq_map_) { From 275ecc7fb11f848b6c03f3b92ca7a3dde0609ec7 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 15 Dec 2020 17:55:06 +0800 Subject: [PATCH 119/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 460_lfu_cache/lfu_cache.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/460_lfu_cache/lfu_cache.c b/460_lfu_cache/lfu_cache.c index ec02bff..63879b8 100644 --- a/460_lfu_cache/lfu_cache.c +++ b/460_lfu_cache/lfu_cache.c @@ -319,9 +319,9 @@ static void avl_tree_destory(FreqAVLTree *tree) static void freq_incr(FreqAVLTree* tree, LFUNode *lfu, int key) { - /* erase */ list_del(&lfu->dlink); if (list_empty(&lfu->node->dhead)) { + /* we must erase the empty node to rearrange the AVL tree */ avl_node_erase(tree, lfu->node); } @@ -383,6 +383,7 @@ void lFUCachePut(LFUCache* obj, int key, int value) list_del(&lfu->dlink); list_del(&lfu->key_link); if (list_empty(&node->dhead)) { + /* we must erase the empty node to rearrange the AVL tree */ avl_node_erase(obj->tree, node); } } else { From 4d28c1b1506265f57639eb9750f523840d81f26c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 15 Dec 2020 18:06:27 +0800 Subject: [PATCH 120/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 460_lfu_cache/lfu_cache.c | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/460_lfu_cache/lfu_cache.c b/460_lfu_cache/lfu_cache.c index 63879b8..a57abb5 100644 --- a/460_lfu_cache/lfu_cache.c +++ b/460_lfu_cache/lfu_cache.c @@ -31,6 +31,7 @@ typedef struct FreqAVLNode { typedef struct { FreqAVLNode *root; + FreqAVLNode *min_freq_node; } FreqAVLTree; typedef struct LFUNode { @@ -284,19 +285,11 @@ static void avl_node_erase(FreqAVLTree *tree, FreqAVLNode *node) avl_tree_balance(tree, startpoint); } -static FreqAVLNode *avl_tree_min_get(FreqAVLTree *tree) -{ - FreqAVLNode *node = tree->root; - while (node->children[0] != NULL) { - node = node->children[0]; - } - return node; -} - static FreqAVLTree *avl_tree_init(void) { FreqAVLTree *tree = malloc(sizeof(*tree)); tree->root = NULL; + tree->min_freq_node = NULL; return tree; } @@ -327,7 +320,11 @@ static void freq_incr(FreqAVLTree* tree, LFUNode *lfu, int key) /* New frequency */ int freq = ++lfu->freq; - lfu->node = avl_tree_insert(tree, freq); + FreqAVLNode *node = avl_tree_insert(tree, freq); + if (lfu->node == tree->min_freq_node) { + tree->min_freq_node = node; + } + lfu->node = node; list_add(&lfu->dlink, &lfu->node->dhead); } @@ -378,7 +375,7 @@ void lFUCachePut(LFUCache* obj, int key, int value) /* squeeze minimum frequency */ if (obj->size == obj->capacity) { - FreqAVLNode *node = avl_tree_min_get(obj->tree); + FreqAVLNode *node = obj->tree->min_freq_node; lfu = list_last_entry(&node->dhead, LFUNode, dlink); list_del(&lfu->dlink); list_del(&lfu->key_link); @@ -396,6 +393,7 @@ void lFUCachePut(LFUCache* obj, int key, int value) lfu->val = value; lfu->freq = 1; lfu->node = avl_tree_insert(obj->tree, lfu->freq); + obj->tree->min_freq_node = lfu->node; list_add(&lfu->dlink, &lfu->node->dhead); list_add(&lfu->key_link, &obj->hheads[hash]); } @@ -430,7 +428,7 @@ void lFUCacheFree(LFUCache* obj) int main(void) { LFUCache* obj = lFUCacheCreate(2); -#if 1 +#if 0 lFUCachePut(obj, 1, 1); printf("Put 1 1\n"); lFUCachePut(obj, 2, 2); From e319ebf3da437e8b907a26d5e0dd746bc4f8b9db Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 15 Dec 2020 19:25:35 +0800 Subject: [PATCH 121/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 460_lfu_cache/lfu_cache.c | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/460_lfu_cache/lfu_cache.c b/460_lfu_cache/lfu_cache.c index a57abb5..87c43c3 100644 --- a/460_lfu_cache/lfu_cache.c +++ b/460_lfu_cache/lfu_cache.c @@ -197,8 +197,10 @@ static FreqAVLNode *avl_tree_insert(FreqAVLTree *tree, int freq) parent = *rover; if (freq < (*rover)->freq) { rover = &((*rover)->children[0]); - } else { + } else if (freq > (*rover)->freq) { rover = &((*rover)->children[1]); + } else { + return *rover; } } @@ -312,18 +314,17 @@ static void avl_tree_destory(FreqAVLTree *tree) static void freq_incr(FreqAVLTree* tree, LFUNode *lfu, int key) { + /* New frequency */ list_del(&lfu->dlink); + int freq = ++lfu->freq; + FreqAVLNode *node = avl_tree_insert(tree, freq); if (list_empty(&lfu->node->dhead)) { + if (lfu->node == tree->min_freq_node) { + tree->min_freq_node = node; + } /* we must erase the empty node to rearrange the AVL tree */ avl_node_erase(tree, lfu->node); } - - /* New frequency */ - int freq = ++lfu->freq; - FreqAVLNode *node = avl_tree_insert(tree, freq); - if (lfu->node == tree->min_freq_node) { - tree->min_freq_node = node; - } lfu->node = node; list_add(&lfu->dlink, &lfu->node->dhead); } @@ -379,10 +380,7 @@ void lFUCachePut(LFUCache* obj, int key, int value) lfu = list_last_entry(&node->dhead, LFUNode, dlink); list_del(&lfu->dlink); list_del(&lfu->key_link); - if (list_empty(&node->dhead)) { - /* we must erase the empty node to rearrange the AVL tree */ - avl_node_erase(obj->tree, node); - } + /* NOTE: we DO NOT need to erase the empty AVL node since the min freq node would be update immediately */ } else { /* new LFU */ obj->size++; @@ -428,7 +426,7 @@ void lFUCacheFree(LFUCache* obj) int main(void) { LFUCache* obj = lFUCacheCreate(2); -#if 0 +#if 1 lFUCachePut(obj, 1, 1); printf("Put 1 1\n"); lFUCachePut(obj, 2, 2); From fde050464fa1750dcaad702be50e5cc0f8391147 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 17 Dec 2020 16:17:54 +0800 Subject: [PATCH 122/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../zigzag.cc | 2 +- 1373_maximum_sum_bst_in_binary_tree/max_bst.cc | 17 +++++++++-------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/1372_longest_zigzag_path_in_a_binary_tree/zigzag.cc b/1372_longest_zigzag_path_in_a_binary_tree/zigzag.cc index be69eb1..9ac4d56 100644 --- a/1372_longest_zigzag_path_in_a_binary_tree/zigzag.cc +++ b/1372_longest_zigzag_path_in_a_binary_tree/zigzag.cc @@ -30,5 +30,5 @@ class Solution { int subrzz = 1 + subr.first; maxzz = max(maxzz, max(sublzz, subrzz)); return make_pair(sublzz, subrzz); - } + } }; diff --git a/1373_maximum_sum_bst_in_binary_tree/max_bst.cc b/1373_maximum_sum_bst_in_binary_tree/max_bst.cc index 2d42627..72d9493 100644 --- a/1373_maximum_sum_bst_in_binary_tree/max_bst.cc +++ b/1373_maximum_sum_bst_in_binary_tree/max_bst.cc @@ -13,14 +13,6 @@ using namespace std; * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ -struct TreeInfo { - bool isBst; - int min_val; - int max_val; - int sum_val; - TreeInfo() : isBst(true), min_val(INT_MAX), max_val(INT_MIN), sum_val(0) {} - TreeInfo(bool bst, int min, int max, int sum) : isBst(bst), min_val(min), max_val(max), sum_val(sum) {} -}; class Solution { public: @@ -29,6 +21,15 @@ class Solution { return max(0, max_sum); } private: + struct TreeInfo { + bool isBst; + int min_val; + int max_val; + int sum_val; + TreeInfo() : isBst(true), min_val(INT_MAX), max_val(INT_MIN), sum_val(0) {} + TreeInfo(bool bst, int min, int max, int sum) : isBst(bst), min_val(min), max_val(max), sum_val(sum) {} + }; + int max_sum = INT_MIN; TreeInfo *dfs(TreeNode *root) { if (root == nullptr) { From af3227784f02a5e5213bbad90a7ec148542c8d77 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 20 Dec 2020 17:51:00 +0800 Subject: [PATCH 123/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 146_lru_cache/lru_cache.cc | 4 ++-- 460_lfu_cache/lfu_cache.c | 4 ++++ 460_lfu_cache/lfu_cache.cc | 6 +++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/146_lru_cache/lru_cache.cc b/146_lru_cache/lru_cache.cc index 9a21c81..74cb60c 100644 --- a/146_lru_cache/lru_cache.cc +++ b/146_lru_cache/lru_cache.cc @@ -15,7 +15,7 @@ class LRUCache { } int get(int key) { - if (ht_.find(key) == ht_.end()) { + if (ht_.count(key) == 0) { return -1; } @@ -34,7 +34,7 @@ class LRUCache { return; } - if (ht_.find(key) != ht_.end()) { + if (ht_.count(key) == 0) { li_.erase(ht_[key]); } else { if (li_.size() == cap_) { diff --git a/460_lfu_cache/lfu_cache.c b/460_lfu_cache/lfu_cache.c index 87c43c3..c77ba2c 100644 --- a/460_lfu_cache/lfu_cache.c +++ b/460_lfu_cache/lfu_cache.c @@ -344,6 +344,10 @@ LFUCache* lFUCacheCreate(int capacity) int lFUCacheGet(LFUCache* obj, int key) { + if (obj->capacity <= 0) { + return; + } + struct list_head *pos; int hash = key % obj->capacity; list_for_each(pos, &obj->hheads[hash]) { diff --git a/460_lfu_cache/lfu_cache.cc b/460_lfu_cache/lfu_cache.cc index 134d5fa..cfb3bc9 100644 --- a/460_lfu_cache/lfu_cache.cc +++ b/460_lfu_cache/lfu_cache.cc @@ -19,7 +19,7 @@ class LFUCache { } int get(int key) { - if (key_map_.find(key) == key_map_.end()) { + if (key_map_.count(key) == 0) { return -1; } @@ -32,7 +32,7 @@ class LFUCache { return; } - if (key_map_.find(key) != key_map_.end()) { + if (key_map_.count(key) == 0) { freq_incr(key); (*key_map_[key])->value_ = value; } else { @@ -63,7 +63,7 @@ class LFUCache { } void _freq_incr(int key, int value, int freq) { - if (freq_map_.find(freq + 1) == freq_map_.end()) { + if (freq_map_.count(freq + 1) == 0) { freq_map_[freq + 1] = li_; } From b8bb2322a7f03559601f85b7aacaf3e5738f6c16 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 28 Dec 2020 17:05:45 +0800 Subject: [PATCH 124/211] Rename Signed-off-by: begeekmyfriend --- {001_two_sum => 0001_two_sum}/Makefile | 0 {001_two_sum => 0001_two_sum}/two_sum.c | 0 {001_two_sum => 0001_two_sum}/two_sum.cc | 0 {001_two_sum => 0001_two_sum}/two_sum.py | 0 {002_add_two_numbers => 0002_add_two_numbers}/Makefile | 0 {002_add_two_numbers => 0002_add_two_numbers}/add_two_numbers.c | 0 {002_add_two_numbers => 0002_add_two_numbers}/add_two_numbers.cc | 0 .../Makefile | 0 .../longest_substring_without_repeat.c | 0 .../longest_substring_without_repeat.cc | 0 .../Makefile | 0 .../median_of_two_sorted_array.c | 0 .../median_of_two_sorted_array.cc | 0 .../Makefile | 0 .../longest_palindromic_substring.c | 0 {006_zigzag_conversion => 0006_zigzag_conversion}/Makefile | 0 .../zigzag_conversion.c | 0 .../zigzag_conversion.cc | 0 {007_reverse_integer => 0007_reverse_integer}/Makefile | 0 {007_reverse_integer => 0007_reverse_integer}/reverse_integer.c | 0 {007_reverse_integer => 0007_reverse_integer}/reverse_integer.cc | 0 {008_atoi => 0008_atoi}/Makefile | 0 {008_atoi => 0008_atoi}/atoi.c | 0 {008_atoi => 0008_atoi}/atoi.cc | 0 {009_palindrome_number => 0009_palindrome_number}/Makefile | 0 .../palindrome_number.c | 0 .../palindrome_number.cc | 0 .../Makefile | 0 .../regular_expression.c | 0 .../regular_expression.cc | 0 .../Makefile | 0 .../container.c | 0 .../container.cc | 0 {012_roman_numeral => 0012_roman_numeral}/Makefile | 0 {012_roman_numeral => 0012_roman_numeral}/roman_numeral.c | 0 {012_roman_numeral => 0012_roman_numeral}/roman_numeral.cc | 0 {013_roman_to_integer => 0013_roman_to_integer}/Makefile | 0 .../roman_to_integer.c | 0 .../roman_to_integer.cc | 0 .../Makefile | 0 .../common_prefix.c | 0 .../common_prefix.cc | 0 {015_three_sum => 0015_three_sum}/Makefile | 0 {015_three_sum => 0015_three_sum}/three_sum.c | 0 {015_three_sum => 0015_three_sum}/three_sum.cc | 0 {016_three_sum_closest => 0016_three_sum_closest}/Makefile | 0 .../three_sum_closest.c | 0 .../three_sum_closest.cc | 0 .../Makefile | 0 .../letter_combinations.c | 0 {018_four_sum => 0018_four_sum}/Makefile | 0 {018_four_sum => 0018_four_sum}/four_sum.c | 0 {018_four_sum => 0018_four_sum}/four_sum.cc | 0 .../Makefile | 0 .../remove_end.c | 0 .../remove_end.cc | 0 {020_valid_parentheses => 0020_valid_parentheses}/Makefile | 0 .../valid_parentheses.c | 0 .../valid_parentheses.cc | 0 .../Makefile | 0 .../merge_lists.c | 0 .../merge_lists.cc | 0 {022_generate_parathesis => 0022_generate_parathesis}/Makefile | 0 .../parenthesis.c | 0 .../parenthesis.cc | 0 {023_merge_k_sorted_lists => 0023_merge_k_sorted_lists}/Makefile | 0 .../merge_lists.c | 0 .../merge_lists.cc | 0 {024_swap_nodes_in_pairs => 0024_swap_nodes_in_pairs}/Makefile | 0 .../swap_nodes.c | 0 .../swap_nodes.cc | 0 .../Makefile | 0 .../reverse_nodes.c | 0 .../reverse_nodes.cc | 0 .../Makefile | 0 .../rm_dup.c | 0 .../rm_dup.cc | 0 {027_remove_element => 0027_remove_element}/Makefile | 0 {027_remove_element => 0027_remove_element}/rm_elem.c | 0 {027_remove_element => 0027_remove_element}/rm_elem.cc | 0 {028_implement_strstr => 0028_implement_strstr}/Makefile | 0 {028_implement_strstr => 0028_implement_strstr}/strstr.c | 0 {028_implement_strstr => 0028_implement_strstr}/strstr.cc | 0 {029_divide_two_integers => 0029_divide_two_integers}/Makefile | 0 {029_divide_two_integers => 0029_divide_two_integers}/divide.c | 0 {029_divide_two_integers => 0029_divide_two_integers}/divide.cc | 0 .../Makefile | 0 .../concatenation.c | 0 .../concatenation.cc | 0 {031_next_permutation => 0031_next_permutation}/Makefile | 0 .../next_permutation.c | 0 .../next_permutation.cc | 0 .../Makefile | 0 .../valid_parentheses.c | 0 .../valid_parentheses.cc | 0 .../Makefile | 0 .../rotated_array.c | 0 .../rotated_array.cc | 0 {034_search_for_a_range => 0034_search_for_a_range}/Makefile | 0 .../range_search.c | 0 .../range_search.cc | 0 .../Makefile | 0 .../insert_position.c | 0 .../insert_position.cc | 0 {036_valid_sudoku => 0036_valid_sudoku}/Makefile | 0 {036_valid_sudoku => 0036_valid_sudoku}/valid_sudoku.c | 0 {036_valid_sudoku => 0036_valid_sudoku}/valid_sudoku.cc | 0 {037_sudoku_solver => 0037_sudoku_solver}/Makefile | 0 {037_sudoku_solver => 0037_sudoku_solver}/sudoku_solver.c | 0 {037_sudoku_solver => 0037_sudoku_solver}/sudoku_solver.cc | 0 {038_count_and_say => 0038_count_and_say}/Makefile | 0 {038_count_and_say => 0038_count_and_say}/count_and_say.c | 0 {039_combination_sum => 0039_combination_sum}/Makefile | 0 {039_combination_sum => 0039_combination_sum}/combination_sum.c | 0 {039_combination_sum => 0039_combination_sum}/combination_sum.cc | 0 {040_combination_sum_ii => 0040_combination_sum_ii}/Makefile | 0 .../combination_sum.c | 0 .../combination_sum.cc | 0 .../Makefile | 0 .../missing_positive.c | 0 .../missing_positive.cc | 0 {042_trapping_rain_water => 0042_trapping_rain_water}/Makefile | 0 .../trap_water.c | 0 .../trap_water.cc | 0 {043_multiply_strings => 0043_multiply_strings}/Makefile | 0 .../multiply_strings.c | 0 .../multiply_strings.cc | 0 {044_wildcard_matching => 0044_wildcard_matching}/Makefile | 0 .../wildcard_matching.c | 0 {045_jump_game_ii => 0045_jump_game_ii}/Makefile | 0 {045_jump_game_ii => 0045_jump_game_ii}/jump_game.c | 0 {045_jump_game_ii => 0045_jump_game_ii}/jump_game.cc | 0 {046_permutations => 0046_permutations}/Makefile | 0 {046_permutations => 0046_permutations}/permutations.c | 0 {046_permutations => 0046_permutations}/permutations.cc | 0 {047_permutations_ii => 0047_permutations_ii}/Makefile | 0 {047_permutations_ii => 0047_permutations_ii}/permutations.c | 0 {047_permutations_ii => 0047_permutations_ii}/permutations.cc | 0 {048_rotate_image => 0048_rotate_image}/Makefile | 0 {048_rotate_image => 0048_rotate_image}/rotate.c | 0 {048_rotate_image => 0048_rotate_image}/rotate.cc | 0 {049_group_anagrams => 0049_group_anagrams}/Makefile | 0 {049_group_anagrams => 0049_group_anagrams}/anagrams.c | 0 {049_group_anagrams => 0049_group_anagrams}/anagrams.cc | 0 {050_pow => 0050_pow}/Makefile | 0 {050_pow => 0050_pow}/pow.c | 0 {050_pow => 0050_pow}/pow.cc | 0 {051_n_queens => 0051_n_queens}/Makefile | 0 {051_n_queens => 0051_n_queens}/n_queens.c | 0 {051_n_queens => 0051_n_queens}/n_queens.cc | 0 {052_n_queens_ii => 0052_n_queens_ii}/Makefile | 0 {052_n_queens_ii => 0052_n_queens_ii}/n_queens.c | 0 {052_n_queens_ii => 0052_n_queens_ii}/n_queens.cc | 0 {053_maximum_subarray => 0053_maximum_subarray}/Makefile | 0 {053_maximum_subarray => 0053_maximum_subarray}/max_subarray.c | 0 {053_maximum_subarray => 0053_maximum_subarray}/max_subarray.cc | 0 {054_spiral_matrix => 0054_spiral_matrix}/Makefile | 0 {054_spiral_matrix => 0054_spiral_matrix}/spiral_matrix.c | 0 {054_spiral_matrix => 0054_spiral_matrix}/spiral_matrix.cc | 0 {055_jump_game => 0055_jump_game}/Makefile | 0 {055_jump_game => 0055_jump_game}/jump_game.c | 0 {056_merge_intervals => 0056_merge_intervals}/Makefile | 0 {056_merge_intervals => 0056_merge_intervals}/merge_intervals.c | 0 {057_insert_interval => 0057_insert_interval}/Makefile | 0 {057_insert_interval => 0057_insert_interval}/insert_interval.c | 0 {058_length_of_last_word => 0058_length_of_last_word}/Makefile | 0 .../word_length.c | 0 {059_spiral_matrix_ii => 0059_spiral_matrix_ii}/Makefile | 0 {059_spiral_matrix_ii => 0059_spiral_matrix_ii}/spiral_matrix.c | 0 {060_permutation_sequence => 0060_permutation_sequence}/Makefile | 0 .../permutation_sequence.c | 0 {061_rotate_list => 0061_rotate_list}/Makefile | 0 {061_rotate_list => 0061_rotate_list}/rotate_list.c | 0 {062_unique_path => 0062_unique_path}/Makefile | 0 {062_unique_path => 0062_unique_path}/unique_path.c | 0 {063_unique_paths_ii => 0063_unique_paths_ii}/Makefile | 0 {063_unique_paths_ii => 0063_unique_paths_ii}/unique_path.c | 0 {064_minumum_path_sum => 0064_minumum_path_sum}/Makefile | 0 .../minimum_path_sum.c | 0 {065_valid_number => 0065_valid_number}/Makefile | 0 {065_valid_number => 0065_valid_number}/valid_number.c | 0 {066_plus_one => 0066_plus_one}/Makefile | 0 {066_plus_one => 0066_plus_one}/plus_one.c | 0 {066_plus_one => 0066_plus_one}/plus_one.cc | 0 {067_add_binary => 0067_add_binary}/Makefile | 0 {067_add_binary => 0067_add_binary}/add_binary.c | 0 {067_add_binary => 0067_add_binary}/add_binary.cc | 0 {068_text_justification => 0068_text_justification}/Makefile | 0 .../justification.c | 0 {069_sqrt => 0069_sqrt}/Makefile | 0 {069_sqrt => 0069_sqrt}/sqrt.c | 0 {070_climbing_stairs => 0070_climbing_stairs}/Makefile | 0 {070_climbing_stairs => 0070_climbing_stairs}/climb_stairs.c | 0 {070_climbing_stairs => 0070_climbing_stairs}/climb_stairs.cc | 0 {071_simplify_path => 0071_simplify_path}/Makefile | 0 {071_simplify_path => 0071_simplify_path}/simplify_path.c | 0 {072_edit_distance => 0072_edit_distance}/Makefile | 0 {072_edit_distance => 0072_edit_distance}/edit_distance.c | 0 {072_edit_distance => 0072_edit_distance}/edit_distance.cc | 0 {073_set_matrix_zeroes => 0073_set_matrix_zeroes}/Makefile | 0 {073_set_matrix_zeroes => 0073_set_matrix_zeroes}/set_zero.c | 0 {074_search_a_2d_matrix => 0074_search_a_2d_matrix}/Makefile | 0 .../matrix_search.c | 0 {075_sort_colors => 0075_sort_colors}/Makefile | 0 {075_sort_colors => 0075_sort_colors}/sort_colors.c | 0 .../Makefile | 0 .../window_substring.c | 0 {077_combinations => 0077_combinations}/Makefile | 0 {077_combinations => 0077_combinations}/combinations.c | 0 {077_combinations => 0077_combinations}/combinations.cc | 0 {078_subsets => 0078_subsets}/Makefile | 0 {078_subsets => 0078_subsets}/subsets.c | 0 {078_subsets => 0078_subsets}/subsets.cc | 0 {079_word_search => 0079_word_search}/Makefile | 0 {079_word_search => 0079_word_search}/word_search.c | 0 .../Makefile | 0 .../rm_dups.c | 0 .../Makefile | 0 .../search_rotated_array.c | 0 .../Makefile | 0 .../rm_dup.c | 0 .../Makefile | 0 .../rm_dup.c | 0 .../rm_dup.cc | 0 .../Makefile | 0 .../rect_in_histogram.c | 0 {085_maximal_rectangle => 0085_maximal_rectangle}/Makefile | 0 .../maximal_rectangle.c | 0 {086_partition_list => 0086_partition_list}/Makefile | 0 {086_partition_list => 0086_partition_list}/partition_list.c | 0 {087_scramble_string => 0087_scramble_string}/Makefile | 0 {087_scramble_string => 0087_scramble_string}/scramble_string.c | 0 {088_merge_sorted_array => 0088_merge_sorted_array}/Makefile | 0 {088_merge_sorted_array => 0088_merge_sorted_array}/merge_array.c | 0 .../merge_array.cc | 0 {089_gray_code => 0089_gray_code}/Makefile | 0 {089_gray_code => 0089_gray_code}/gray_code.c | 0 {090_subsets_ii => 0090_subsets_ii}/Makefile | 0 {090_subsets_ii => 0090_subsets_ii}/subsets.c | 0 {090_subsets_ii => 0090_subsets_ii}/subsets.cc | 0 {091_decode_ways => 0091_decode_ways}/Makefile | 0 {091_decode_ways => 0091_decode_ways}/decode_ways.c | 0 .../Makefile | 0 .../reverse_list.c | 0 {093_restore_ip_addresses => 0093_restore_ip_addresses}/Makefile | 0 {093_restore_ip_addresses => 0093_restore_ip_addresses}/ip_addr.c | 0 .../Makefile | 0 .../bst_inorder_traversal.c | 0 .../Makefile | 0 .../unique_bst.c | 0 .../Makefile | 0 .../unique_bst.c | 0 {097_interleaving_string => 0097_interleaving_string}/Makefile | 0 .../interleaving_string.c | 0 .../Makefile | 0 .../valid_bst.c | 0 .../valid_bst.cc | 0 .../Makefile | 0 .../recover_bst.c | 0 {100_same_tree => 0100_same_tree}/Makefile | 0 {100_same_tree => 0100_same_tree}/same_tree.c | 0 {100_same_tree => 0100_same_tree}/same_tree.cc | 0 {101_symmetric_tree => 0101_symmetric_tree}/Makefile | 0 {101_symmetric_tree => 0101_symmetric_tree}/symmetric_tree.c | 0 {101_symmetric_tree => 0101_symmetric_tree}/symmetric_tree.cc | 0 .../Makefile | 0 .../bst_bfs.c | 0 .../bst_bfs.cc | 0 .../Makefile | 0 .../bst_zigzag.c | 0 .../Makefile | 0 .../bst_depth.c | 0 .../bst_depth.cc | 0 .../Makefile | 0 .../binary_tree_build.c | 0 .../Makefile | 0 .../binary_tree_build.c | 0 .../Makefile | 0 .../bst_bfs.c | 0 .../bst_bfs.cc | 0 .../Makefile | 0 .../bst_convert.c | 0 .../bst_convert.cc | 0 .../Makefile | 0 .../bst_convert.c | 0 {110_balanced_binary_tree => 0110_balanced_binary_tree}/Makefile | 0 .../balanced_bst.c | 0 .../balanced_bst.cc | 0 .../Makefile | 0 .../bst_depth.c | 0 .../bst_depth.cc | 0 {112_path_sum => 0112_path_sum}/Makefile | 0 {112_path_sum => 0112_path_sum}/path_sum.c | 0 {112_path_sum => 0112_path_sum}/path_sum.cc | 0 {113_path_sum_ii => 0113_path_sum_ii}/Makefile | 0 {113_path_sum_ii => 0113_path_sum_ii}/path_sum.c | 0 .../Makefile | 0 .../flatten.c | 0 .../Makefile | 0 .../distinct_subseq.c | 0 .../Makefile | 0 .../connect.c | 0 .../Makefile | 0 .../connect.c | 0 {118_pascal_triangle => 0118_pascal_triangle}/Makefile | 0 {118_pascal_triangle => 0118_pascal_triangle}/pascal_triangle.c | 0 {119_pascal_triangle_ii => 0119_pascal_triangle_ii}/Makefile | 0 .../pascal_triangle.c | 0 {120_triangle => 0120_triangle}/Makefile | 0 {120_triangle => 0120_triangle}/triangle.c | 0 .../Makefile | 0 .../stock.c | 0 .../stock.cc | 0 .../Makefile | 0 .../stock.c | 0 .../stock.cc | 0 .../Makefile | 0 .../stock.c | 0 .../Makefile | 0 .../bst_max_path.c | 0 .../bst_max_path.cc | 0 {125_valid_palindrome => 0125_valid_palindrome}/Makefile | 0 .../valid_palindrome.c | 0 {126_word_ladder_ii => 0126_word_ladder_ii}/Makefile | 0 {126_word_ladder_ii => 0126_word_ladder_ii}/word_ladder.c | 0 {127_word_ladder => 0127_word_ladder}/Makefile | 0 {127_word_ladder => 0127_word_ladder}/word_ladder.c | 0 .../Makefile | 0 .../consec_seq.c | 0 .../Makefile | 0 .../sum_tree.c | 0 {130_surrounded_regions => 0130_surrounded_regions}/Makefile | 0 .../surrounded_regions.c | 0 .../Makefile | 0 .../palindrome_partition.c | 0 .../Makefile | 0 .../palindrome_partition.c | 0 {133_clone_graph => 0133_clone_graph}/Makefile | 0 {133_clone_graph => 0133_clone_graph}/clone_graph.c | 0 {134_gas_station => 0134_gas_station}/Makefile | 0 {134_gas_station => 0134_gas_station}/gas_station.c | 0 {135_candy => 0135_candy}/Makefile | 0 {135_candy => 0135_candy}/candy.c | 0 {136_single_number => 0136_single_number}/Makefile | 0 {136_single_number => 0136_single_number}/single_number.c | 0 {136_single_number => 0136_single_number}/single_number.cc | 0 {137_single_number_ii => 0137_single_number_ii}/Makefile | 0 {137_single_number_ii => 0137_single_number_ii}/single_number.c | 0 .../Makefile | 0 .../copy_list.c | 0 .../copy_list.cc | 0 {139_word_break => 0139_word_break}/Makefile | 0 {139_word_break => 0139_word_break}/word_break.c | 0 {140_word_break_ii => 0140_word_break_ii}/Makefile | 0 {140_word_break_ii => 0140_word_break_ii}/word_break.c | 0 {141_linked_list_cycle => 0141_linked_list_cycle}/Makefile | 0 {141_linked_list_cycle => 0141_linked_list_cycle}/list_cycle.c | 0 {141_linked_list_cycle => 0141_linked_list_cycle}/list_cycle.cc | 0 {142_linked_list_cycle_ii => 0142_linked_list_cycle_ii}/Makefile | 0 .../list_cycle.c | 0 .../list_cycle.cc | 0 {143_reorder_list => 0143_reorder_list}/Makefile | 0 {143_reorder_list => 0143_reorder_list}/reorder_list.c | 0 .../Makefile | 0 .../bst_preorder.c | 0 .../bst_preorder.cc | 0 .../Makefile | 0 .../bst_postorder.c | 0 .../bst_postorder.cc | 0 {146_lru_cache => 0146_lru_cache}/Makefile | 0 {146_lru_cache => 0146_lru_cache}/lru_cache.c | 0 {146_lru_cache => 0146_lru_cache}/lru_cache.cc | 0 {147_insertion_sort_list => 0147_insertion_sort_list}/Makefile | 0 .../insert_sort_list.c | 0 {148_sort_list => 0148_sort_list}/Makefile | 0 {148_sort_list => 0148_sort_list}/sort_list.c | 0 {149_max_points_on_a_line => 0149_max_points_on_a_line}/Makefile | 0 .../points_on_line.c | 0 .../Makefile | 0 .../eval_rpn.c | 0 .../Makefile | 0 .../reverse.c | 0 .../Makefile | 0 .../subarray.c | 0 .../Makefile | 0 .../minimum.c | 0 .../Makefile | 0 .../minimum.c | 0 {155_min_stack => 0155_min_stack}/Makefile | 0 {155_min_stack => 0155_min_stack}/stack.c | 0 .../Makefile | 0 .../intersection.c | 0 {162_find_peak_element => 0162_find_peak_element}/Makefile | 0 {162_find_peak_element => 0162_find_peak_element}/peak.c | 0 {164_maximum_gap => 0164_maximum_gap}/Makefile | 0 {164_maximum_gap => 0164_maximum_gap}/max_gap.c | 0 {164_maximum_gap => 0164_maximum_gap}/max_gap.cc | 0 .../Makefile | 0 .../version.c | 0 .../Makefile | 0 .../fraction.c | 0 {167_two_sum_ii => 0167_two_sum_ii}/Makefile | 0 {167_two_sum_ii => 0167_two_sum_ii}/two_sum.c | 0 {167_two_sum_ii => 0167_two_sum_ii}/two_sum.cc | 0 .../Makefile | 0 .../sheet_column.c | 0 {169_majority_element => 0169_majority_element}/Makefile | 0 {169_majority_element => 0169_majority_element}/majority.c | 0 {169_majority_element => 0169_majority_element}/majority.cc | 0 .../Makefile | 0 .../sheet_column.c | 0 .../Makefile | 0 .../zeroes.c | 0 .../zeroes.cc | 0 .../Makefile | 0 .../bst_iter.c | 0 {174_dungeon_game => 0174_dungeon_game}/Makefile | 0 {174_dungeon_game => 0174_dungeon_game}/dungeon.c | 0 {179_largest_number => 0179_largest_number}/Makefile | 0 {179_largest_number => 0179_largest_number}/largest_number.c | 0 {179_largest_number => 0179_largest_number}/largest_number.cc | 0 .../Makefile | 0 .../stock.c | 0 {189_rotate_array => 0189_rotate_array}/Makefile | 0 {189_rotate_array => 0189_rotate_array}/rotate_array.c | 0 {189_rotate_array => 0189_rotate_array}/rotate_array.cc | 0 {190_reverse_bits => 0190_reverse_bits}/Makefile | 0 {190_reverse_bits => 0190_reverse_bits}/reverse_bits.c | 0 {191_number_of_one_bits => 0191_number_of_one_bits}/Makefile | 0 .../hamming_weight.c | 0 {198_house_robber => 0198_house_robber}/Makefile | 0 {198_house_robber => 0198_house_robber}/robber.c | 0 {198_house_robber => 0198_house_robber}/robber.cc | 0 .../Makefile | 0 .../bst_right.c | 0 {200_number_of_islands => 0200_number_of_islands}/Makefile | 0 {200_number_of_islands => 0200_number_of_islands}/islands.c | 0 .../Makefile | 0 .../and.c | 0 {202_happy_number => 0202_happy_number}/Makefile | 0 {202_happy_number => 0202_happy_number}/happy_number.c | 0 .../Makefile | 0 .../rm_elem.c | 0 {204_count_primes => 0204_count_primes}/Makefile | 0 {204_count_primes => 0204_count_primes}/count_primes.c | 0 {205_isomorphic_strings => 0205_isomorphic_strings}/Makefile | 0 .../isomorphic_strings.c | 0 {206_reverse_linked_list => 0206_reverse_linked_list}/Makefile | 0 .../reverse_list.c | 0 {207_course_schedule => 0207_course_schedule}/Makefile | 0 {207_course_schedule => 0207_course_schedule}/course_schedule.c | 0 {208_implement_trie => 0208_implement_trie}/Makefile | 0 {208_implement_trie => 0208_implement_trie}/trie.c | 0 .../Makefile | 0 .../mini_size.c | 0 {210_course_schedule_ii => 0210_course_schedule_ii}/Makefile | 0 .../course_schedule.c | 0 {211_add_and_search_word => 0211_add_and_search_word}/Makefile | 0 {211_add_and_search_word => 0211_add_and_search_word}/word_dict.c | 0 {212_word_search_ii => 0212_word_search_ii}/Makefile | 0 {212_word_search_ii => 0212_word_search_ii}/word_search.c | 0 {213_house_robber_ii => 0213_house_robber_ii}/Makefile | 0 {213_house_robber_ii => 0213_house_robber_ii}/robber.c | 0 {213_house_robber_ii => 0213_house_robber_ii}/robber.cc | 0 {214_shortest_palindrome => 0214_shortest_palindrome}/Makefile | 0 .../shortest_palindrome.c | 0 .../Makefile | 0 .../kth_elem.c | 0 .../kth_elem.cc | 0 {216_combination_sum_iii => 0216_combination_sum_iii}/Makefile | 0 .../combination_sum.c | 0 {221_maximal_square => 0221_maximal_square}/Makefile | 0 {221_maximal_square => 0221_maximal_square}/maximal_square.c | 0 {224_basic_calculator => 0224_basic_calculator}/Makefile | 0 {224_basic_calculator => 0224_basic_calculator}/calculator.c | 0 {226_invert_binary_tree => 0226_invert_binary_tree}/Makefile | 0 .../invert_binary_tree.c | 0 .../invert_binary_tree.cc | 0 {227_basic_calculator_ii => 0227_basic_calculator_ii}/Makefile | 0 .../calculator.c | 0 {229_majority_element_ii => 0229_majority_element_ii}/Makefile | 0 {229_majority_element_ii => 0229_majority_element_ii}/majority.c | 0 .../Makefile | 0 .../kth_bst.c | 0 .../kth_bst.cc | 0 .../Makefile | 0 .../bst_lca.c | 0 .../Makefile | 0 .../bst_lca.c | 0 .../Makefile | 0 .../slide_window.c | 0 .../slide_window.cc | 0 {337_house_robber_iii => 0337_house_robber_iii}/robber.cc | 0 .../partition.cc | 0 {460_lfu_cache => 0460_lfu_cache}/Makefile | 0 {460_lfu_cache => 0460_lfu_cache}/lfu_cache.c | 0 {460_lfu_cache => 0460_lfu_cache}/lfu_cache.cc | 0 .../diameter_bst.cc | 0 {563_binary_tree_tilt => 0563_binary_tree_tilt}/tilt.cc | 0 499 files changed, 0 insertions(+), 0 deletions(-) rename {001_two_sum => 0001_two_sum}/Makefile (100%) rename {001_two_sum => 0001_two_sum}/two_sum.c (100%) rename {001_two_sum => 0001_two_sum}/two_sum.cc (100%) rename {001_two_sum => 0001_two_sum}/two_sum.py (100%) rename {002_add_two_numbers => 0002_add_two_numbers}/Makefile (100%) rename {002_add_two_numbers => 0002_add_two_numbers}/add_two_numbers.c (100%) rename {002_add_two_numbers => 0002_add_two_numbers}/add_two_numbers.cc (100%) rename {003_longest_substring_without_repeat => 0003_longest_substring_without_repeat}/Makefile (100%) rename {003_longest_substring_without_repeat => 0003_longest_substring_without_repeat}/longest_substring_without_repeat.c (100%) rename {003_longest_substring_without_repeat => 0003_longest_substring_without_repeat}/longest_substring_without_repeat.cc (100%) rename {004_median_of_two_sorted_array => 0004_median_of_two_sorted_array}/Makefile (100%) rename {004_median_of_two_sorted_array => 0004_median_of_two_sorted_array}/median_of_two_sorted_array.c (100%) rename {004_median_of_two_sorted_array => 0004_median_of_two_sorted_array}/median_of_two_sorted_array.cc (100%) rename {005_longest_palindromic_substring => 0005_longest_palindromic_substring}/Makefile (100%) rename {005_longest_palindromic_substring => 0005_longest_palindromic_substring}/longest_palindromic_substring.c (100%) rename {006_zigzag_conversion => 0006_zigzag_conversion}/Makefile (100%) rename {006_zigzag_conversion => 0006_zigzag_conversion}/zigzag_conversion.c (100%) rename {006_zigzag_conversion => 0006_zigzag_conversion}/zigzag_conversion.cc (100%) rename {007_reverse_integer => 0007_reverse_integer}/Makefile (100%) rename {007_reverse_integer => 0007_reverse_integer}/reverse_integer.c (100%) rename {007_reverse_integer => 0007_reverse_integer}/reverse_integer.cc (100%) rename {008_atoi => 0008_atoi}/Makefile (100%) rename {008_atoi => 0008_atoi}/atoi.c (100%) rename {008_atoi => 0008_atoi}/atoi.cc (100%) rename {009_palindrome_number => 0009_palindrome_number}/Makefile (100%) rename {009_palindrome_number => 0009_palindrome_number}/palindrome_number.c (100%) rename {009_palindrome_number => 0009_palindrome_number}/palindrome_number.cc (100%) rename {010_regular_expression_matching => 0010_regular_expression_matching}/Makefile (100%) rename {010_regular_expression_matching => 0010_regular_expression_matching}/regular_expression.c (100%) rename {010_regular_expression_matching => 0010_regular_expression_matching}/regular_expression.cc (100%) rename {011_container_with_most_water => 0011_container_with_most_water}/Makefile (100%) rename {011_container_with_most_water => 0011_container_with_most_water}/container.c (100%) rename {011_container_with_most_water => 0011_container_with_most_water}/container.cc (100%) rename {012_roman_numeral => 0012_roman_numeral}/Makefile (100%) rename {012_roman_numeral => 0012_roman_numeral}/roman_numeral.c (100%) rename {012_roman_numeral => 0012_roman_numeral}/roman_numeral.cc (100%) rename {013_roman_to_integer => 0013_roman_to_integer}/Makefile (100%) rename {013_roman_to_integer => 0013_roman_to_integer}/roman_to_integer.c (100%) rename {013_roman_to_integer => 0013_roman_to_integer}/roman_to_integer.cc (100%) rename {014_longest_common_prefix => 0014_longest_common_prefix}/Makefile (100%) rename {014_longest_common_prefix => 0014_longest_common_prefix}/common_prefix.c (100%) rename {014_longest_common_prefix => 0014_longest_common_prefix}/common_prefix.cc (100%) rename {015_three_sum => 0015_three_sum}/Makefile (100%) rename {015_three_sum => 0015_three_sum}/three_sum.c (100%) rename {015_three_sum => 0015_three_sum}/three_sum.cc (100%) rename {016_three_sum_closest => 0016_three_sum_closest}/Makefile (100%) rename {016_three_sum_closest => 0016_three_sum_closest}/three_sum_closest.c (100%) rename {016_three_sum_closest => 0016_three_sum_closest}/three_sum_closest.cc (100%) rename {017_letter_combinations_of_a_phone_number => 0017_letter_combinations_of_a_phone_number}/Makefile (100%) rename {017_letter_combinations_of_a_phone_number => 0017_letter_combinations_of_a_phone_number}/letter_combinations.c (100%) rename {018_four_sum => 0018_four_sum}/Makefile (100%) rename {018_four_sum => 0018_four_sum}/four_sum.c (100%) rename {018_four_sum => 0018_four_sum}/four_sum.cc (100%) rename {019_remove_nth_node_from_end_of_list => 0019_remove_nth_node_from_end_of_list}/Makefile (100%) rename {019_remove_nth_node_from_end_of_list => 0019_remove_nth_node_from_end_of_list}/remove_end.c (100%) rename {019_remove_nth_node_from_end_of_list => 0019_remove_nth_node_from_end_of_list}/remove_end.cc (100%) rename {020_valid_parentheses => 0020_valid_parentheses}/Makefile (100%) rename {020_valid_parentheses => 0020_valid_parentheses}/valid_parentheses.c (100%) rename {020_valid_parentheses => 0020_valid_parentheses}/valid_parentheses.cc (100%) rename {021_merge_two_sorted_lists => 0021_merge_two_sorted_lists}/Makefile (100%) rename {021_merge_two_sorted_lists => 0021_merge_two_sorted_lists}/merge_lists.c (100%) rename {021_merge_two_sorted_lists => 0021_merge_two_sorted_lists}/merge_lists.cc (100%) rename {022_generate_parathesis => 0022_generate_parathesis}/Makefile (100%) rename {022_generate_parathesis => 0022_generate_parathesis}/parenthesis.c (100%) rename {022_generate_parathesis => 0022_generate_parathesis}/parenthesis.cc (100%) rename {023_merge_k_sorted_lists => 0023_merge_k_sorted_lists}/Makefile (100%) rename {023_merge_k_sorted_lists => 0023_merge_k_sorted_lists}/merge_lists.c (100%) rename {023_merge_k_sorted_lists => 0023_merge_k_sorted_lists}/merge_lists.cc (100%) rename {024_swap_nodes_in_pairs => 0024_swap_nodes_in_pairs}/Makefile (100%) rename {024_swap_nodes_in_pairs => 0024_swap_nodes_in_pairs}/swap_nodes.c (100%) rename {024_swap_nodes_in_pairs => 0024_swap_nodes_in_pairs}/swap_nodes.cc (100%) rename {025_reverse_nodes_in_k_group => 0025_reverse_nodes_in_k_group}/Makefile (100%) rename {025_reverse_nodes_in_k_group => 0025_reverse_nodes_in_k_group}/reverse_nodes.c (100%) rename {025_reverse_nodes_in_k_group => 0025_reverse_nodes_in_k_group}/reverse_nodes.cc (100%) rename {026_remove_duplicates_from_sorted_array => 0026_remove_duplicates_from_sorted_array}/Makefile (100%) rename {026_remove_duplicates_from_sorted_array => 0026_remove_duplicates_from_sorted_array}/rm_dup.c (100%) rename {026_remove_duplicates_from_sorted_array => 0026_remove_duplicates_from_sorted_array}/rm_dup.cc (100%) rename {027_remove_element => 0027_remove_element}/Makefile (100%) rename {027_remove_element => 0027_remove_element}/rm_elem.c (100%) rename {027_remove_element => 0027_remove_element}/rm_elem.cc (100%) rename {028_implement_strstr => 0028_implement_strstr}/Makefile (100%) rename {028_implement_strstr => 0028_implement_strstr}/strstr.c (100%) rename {028_implement_strstr => 0028_implement_strstr}/strstr.cc (100%) rename {029_divide_two_integers => 0029_divide_two_integers}/Makefile (100%) rename {029_divide_two_integers => 0029_divide_two_integers}/divide.c (100%) rename {029_divide_two_integers => 0029_divide_two_integers}/divide.cc (100%) rename {030_substring_with_concatenation_of_all_words => 0030_substring_with_concatenation_of_all_words}/Makefile (100%) rename {030_substring_with_concatenation_of_all_words => 0030_substring_with_concatenation_of_all_words}/concatenation.c (100%) rename {030_substring_with_concatenation_of_all_words => 0030_substring_with_concatenation_of_all_words}/concatenation.cc (100%) rename {031_next_permutation => 0031_next_permutation}/Makefile (100%) rename {031_next_permutation => 0031_next_permutation}/next_permutation.c (100%) rename {031_next_permutation => 0031_next_permutation}/next_permutation.cc (100%) rename {032_longest_valid_parentheses => 0032_longest_valid_parentheses}/Makefile (100%) rename {032_longest_valid_parentheses => 0032_longest_valid_parentheses}/valid_parentheses.c (100%) rename {032_longest_valid_parentheses => 0032_longest_valid_parentheses}/valid_parentheses.cc (100%) rename {033_search_in_rotated_sorted_array => 0033_search_in_rotated_sorted_array}/Makefile (100%) rename {033_search_in_rotated_sorted_array => 0033_search_in_rotated_sorted_array}/rotated_array.c (100%) rename {033_search_in_rotated_sorted_array => 0033_search_in_rotated_sorted_array}/rotated_array.cc (100%) rename {034_search_for_a_range => 0034_search_for_a_range}/Makefile (100%) rename {034_search_for_a_range => 0034_search_for_a_range}/range_search.c (100%) rename {034_search_for_a_range => 0034_search_for_a_range}/range_search.cc (100%) rename {035_search_insert_position => 0035_search_insert_position}/Makefile (100%) rename {035_search_insert_position => 0035_search_insert_position}/insert_position.c (100%) rename {035_search_insert_position => 0035_search_insert_position}/insert_position.cc (100%) rename {036_valid_sudoku => 0036_valid_sudoku}/Makefile (100%) rename {036_valid_sudoku => 0036_valid_sudoku}/valid_sudoku.c (100%) rename {036_valid_sudoku => 0036_valid_sudoku}/valid_sudoku.cc (100%) rename {037_sudoku_solver => 0037_sudoku_solver}/Makefile (100%) rename {037_sudoku_solver => 0037_sudoku_solver}/sudoku_solver.c (100%) rename {037_sudoku_solver => 0037_sudoku_solver}/sudoku_solver.cc (100%) rename {038_count_and_say => 0038_count_and_say}/Makefile (100%) rename {038_count_and_say => 0038_count_and_say}/count_and_say.c (100%) rename {039_combination_sum => 0039_combination_sum}/Makefile (100%) rename {039_combination_sum => 0039_combination_sum}/combination_sum.c (100%) rename {039_combination_sum => 0039_combination_sum}/combination_sum.cc (100%) rename {040_combination_sum_ii => 0040_combination_sum_ii}/Makefile (100%) rename {040_combination_sum_ii => 0040_combination_sum_ii}/combination_sum.c (100%) rename {040_combination_sum_ii => 0040_combination_sum_ii}/combination_sum.cc (100%) rename {041_first_missing_positive => 0041_first_missing_positive}/Makefile (100%) rename {041_first_missing_positive => 0041_first_missing_positive}/missing_positive.c (100%) rename {041_first_missing_positive => 0041_first_missing_positive}/missing_positive.cc (100%) rename {042_trapping_rain_water => 0042_trapping_rain_water}/Makefile (100%) rename {042_trapping_rain_water => 0042_trapping_rain_water}/trap_water.c (100%) rename {042_trapping_rain_water => 0042_trapping_rain_water}/trap_water.cc (100%) rename {043_multiply_strings => 0043_multiply_strings}/Makefile (100%) rename {043_multiply_strings => 0043_multiply_strings}/multiply_strings.c (100%) rename {043_multiply_strings => 0043_multiply_strings}/multiply_strings.cc (100%) rename {044_wildcard_matching => 0044_wildcard_matching}/Makefile (100%) rename {044_wildcard_matching => 0044_wildcard_matching}/wildcard_matching.c (100%) rename {045_jump_game_ii => 0045_jump_game_ii}/Makefile (100%) rename {045_jump_game_ii => 0045_jump_game_ii}/jump_game.c (100%) rename {045_jump_game_ii => 0045_jump_game_ii}/jump_game.cc (100%) rename {046_permutations => 0046_permutations}/Makefile (100%) rename {046_permutations => 0046_permutations}/permutations.c (100%) rename {046_permutations => 0046_permutations}/permutations.cc (100%) rename {047_permutations_ii => 0047_permutations_ii}/Makefile (100%) rename {047_permutations_ii => 0047_permutations_ii}/permutations.c (100%) rename {047_permutations_ii => 0047_permutations_ii}/permutations.cc (100%) rename {048_rotate_image => 0048_rotate_image}/Makefile (100%) rename {048_rotate_image => 0048_rotate_image}/rotate.c (100%) rename {048_rotate_image => 0048_rotate_image}/rotate.cc (100%) rename {049_group_anagrams => 0049_group_anagrams}/Makefile (100%) rename {049_group_anagrams => 0049_group_anagrams}/anagrams.c (100%) rename {049_group_anagrams => 0049_group_anagrams}/anagrams.cc (100%) rename {050_pow => 0050_pow}/Makefile (100%) rename {050_pow => 0050_pow}/pow.c (100%) rename {050_pow => 0050_pow}/pow.cc (100%) rename {051_n_queens => 0051_n_queens}/Makefile (100%) rename {051_n_queens => 0051_n_queens}/n_queens.c (100%) rename {051_n_queens => 0051_n_queens}/n_queens.cc (100%) rename {052_n_queens_ii => 0052_n_queens_ii}/Makefile (100%) rename {052_n_queens_ii => 0052_n_queens_ii}/n_queens.c (100%) rename {052_n_queens_ii => 0052_n_queens_ii}/n_queens.cc (100%) rename {053_maximum_subarray => 0053_maximum_subarray}/Makefile (100%) rename {053_maximum_subarray => 0053_maximum_subarray}/max_subarray.c (100%) rename {053_maximum_subarray => 0053_maximum_subarray}/max_subarray.cc (100%) rename {054_spiral_matrix => 0054_spiral_matrix}/Makefile (100%) rename {054_spiral_matrix => 0054_spiral_matrix}/spiral_matrix.c (100%) rename {054_spiral_matrix => 0054_spiral_matrix}/spiral_matrix.cc (100%) rename {055_jump_game => 0055_jump_game}/Makefile (100%) rename {055_jump_game => 0055_jump_game}/jump_game.c (100%) rename {056_merge_intervals => 0056_merge_intervals}/Makefile (100%) rename {056_merge_intervals => 0056_merge_intervals}/merge_intervals.c (100%) rename {057_insert_interval => 0057_insert_interval}/Makefile (100%) rename {057_insert_interval => 0057_insert_interval}/insert_interval.c (100%) rename {058_length_of_last_word => 0058_length_of_last_word}/Makefile (100%) rename {058_length_of_last_word => 0058_length_of_last_word}/word_length.c (100%) rename {059_spiral_matrix_ii => 0059_spiral_matrix_ii}/Makefile (100%) rename {059_spiral_matrix_ii => 0059_spiral_matrix_ii}/spiral_matrix.c (100%) rename {060_permutation_sequence => 0060_permutation_sequence}/Makefile (100%) rename {060_permutation_sequence => 0060_permutation_sequence}/permutation_sequence.c (100%) rename {061_rotate_list => 0061_rotate_list}/Makefile (100%) rename {061_rotate_list => 0061_rotate_list}/rotate_list.c (100%) rename {062_unique_path => 0062_unique_path}/Makefile (100%) rename {062_unique_path => 0062_unique_path}/unique_path.c (100%) rename {063_unique_paths_ii => 0063_unique_paths_ii}/Makefile (100%) rename {063_unique_paths_ii => 0063_unique_paths_ii}/unique_path.c (100%) rename {064_minumum_path_sum => 0064_minumum_path_sum}/Makefile (100%) rename {064_minumum_path_sum => 0064_minumum_path_sum}/minimum_path_sum.c (100%) rename {065_valid_number => 0065_valid_number}/Makefile (100%) rename {065_valid_number => 0065_valid_number}/valid_number.c (100%) rename {066_plus_one => 0066_plus_one}/Makefile (100%) rename {066_plus_one => 0066_plus_one}/plus_one.c (100%) rename {066_plus_one => 0066_plus_one}/plus_one.cc (100%) rename {067_add_binary => 0067_add_binary}/Makefile (100%) rename {067_add_binary => 0067_add_binary}/add_binary.c (100%) rename {067_add_binary => 0067_add_binary}/add_binary.cc (100%) rename {068_text_justification => 0068_text_justification}/Makefile (100%) rename {068_text_justification => 0068_text_justification}/justification.c (100%) rename {069_sqrt => 0069_sqrt}/Makefile (100%) rename {069_sqrt => 0069_sqrt}/sqrt.c (100%) rename {070_climbing_stairs => 0070_climbing_stairs}/Makefile (100%) rename {070_climbing_stairs => 0070_climbing_stairs}/climb_stairs.c (100%) rename {070_climbing_stairs => 0070_climbing_stairs}/climb_stairs.cc (100%) rename {071_simplify_path => 0071_simplify_path}/Makefile (100%) rename {071_simplify_path => 0071_simplify_path}/simplify_path.c (100%) rename {072_edit_distance => 0072_edit_distance}/Makefile (100%) rename {072_edit_distance => 0072_edit_distance}/edit_distance.c (100%) rename {072_edit_distance => 0072_edit_distance}/edit_distance.cc (100%) rename {073_set_matrix_zeroes => 0073_set_matrix_zeroes}/Makefile (100%) rename {073_set_matrix_zeroes => 0073_set_matrix_zeroes}/set_zero.c (100%) rename {074_search_a_2d_matrix => 0074_search_a_2d_matrix}/Makefile (100%) rename {074_search_a_2d_matrix => 0074_search_a_2d_matrix}/matrix_search.c (100%) rename {075_sort_colors => 0075_sort_colors}/Makefile (100%) rename {075_sort_colors => 0075_sort_colors}/sort_colors.c (100%) rename {076_minimum_window_substring => 0076_minimum_window_substring}/Makefile (100%) rename {076_minimum_window_substring => 0076_minimum_window_substring}/window_substring.c (100%) rename {077_combinations => 0077_combinations}/Makefile (100%) rename {077_combinations => 0077_combinations}/combinations.c (100%) rename {077_combinations => 0077_combinations}/combinations.cc (100%) rename {078_subsets => 0078_subsets}/Makefile (100%) rename {078_subsets => 0078_subsets}/subsets.c (100%) rename {078_subsets => 0078_subsets}/subsets.cc (100%) rename {079_word_search => 0079_word_search}/Makefile (100%) rename {079_word_search => 0079_word_search}/word_search.c (100%) rename {080_remove_duplicates_from_sorted_array_ii => 0080_remove_duplicates_from_sorted_array_ii}/Makefile (100%) rename {080_remove_duplicates_from_sorted_array_ii => 0080_remove_duplicates_from_sorted_array_ii}/rm_dups.c (100%) rename {081_search_in_rotated_sorted_array_ii => 0081_search_in_rotated_sorted_array_ii}/Makefile (100%) rename {081_search_in_rotated_sorted_array_ii => 0081_search_in_rotated_sorted_array_ii}/search_rotated_array.c (100%) rename {082_remove_duplicates_from_sorted_list_ii => 0082_remove_duplicates_from_sorted_list_ii}/Makefile (100%) rename {082_remove_duplicates_from_sorted_list_ii => 0082_remove_duplicates_from_sorted_list_ii}/rm_dup.c (100%) rename {083_remove_duplicates_from_sorted_list => 0083_remove_duplicates_from_sorted_list}/Makefile (100%) rename {083_remove_duplicates_from_sorted_list => 0083_remove_duplicates_from_sorted_list}/rm_dup.c (100%) rename {083_remove_duplicates_from_sorted_list => 0083_remove_duplicates_from_sorted_list}/rm_dup.cc (100%) rename {084_largest_rectangle_in_histogram => 0084_largest_rectangle_in_histogram}/Makefile (100%) rename {084_largest_rectangle_in_histogram => 0084_largest_rectangle_in_histogram}/rect_in_histogram.c (100%) rename {085_maximal_rectangle => 0085_maximal_rectangle}/Makefile (100%) rename {085_maximal_rectangle => 0085_maximal_rectangle}/maximal_rectangle.c (100%) rename {086_partition_list => 0086_partition_list}/Makefile (100%) rename {086_partition_list => 0086_partition_list}/partition_list.c (100%) rename {087_scramble_string => 0087_scramble_string}/Makefile (100%) rename {087_scramble_string => 0087_scramble_string}/scramble_string.c (100%) rename {088_merge_sorted_array => 0088_merge_sorted_array}/Makefile (100%) rename {088_merge_sorted_array => 0088_merge_sorted_array}/merge_array.c (100%) rename {088_merge_sorted_array => 0088_merge_sorted_array}/merge_array.cc (100%) rename {089_gray_code => 0089_gray_code}/Makefile (100%) rename {089_gray_code => 0089_gray_code}/gray_code.c (100%) rename {090_subsets_ii => 0090_subsets_ii}/Makefile (100%) rename {090_subsets_ii => 0090_subsets_ii}/subsets.c (100%) rename {090_subsets_ii => 0090_subsets_ii}/subsets.cc (100%) rename {091_decode_ways => 0091_decode_ways}/Makefile (100%) rename {091_decode_ways => 0091_decode_ways}/decode_ways.c (100%) rename {092_reverse_linked_list_ii => 0092_reverse_linked_list_ii}/Makefile (100%) rename {092_reverse_linked_list_ii => 0092_reverse_linked_list_ii}/reverse_list.c (100%) rename {093_restore_ip_addresses => 0093_restore_ip_addresses}/Makefile (100%) rename {093_restore_ip_addresses => 0093_restore_ip_addresses}/ip_addr.c (100%) rename {094_binary_tree_inorder_traversal => 0094_binary_tree_inorder_traversal}/Makefile (100%) rename {094_binary_tree_inorder_traversal => 0094_binary_tree_inorder_traversal}/bst_inorder_traversal.c (100%) rename {095_unique_binary_search_trees_ii => 0095_unique_binary_search_trees_ii}/Makefile (100%) rename {095_unique_binary_search_trees_ii => 0095_unique_binary_search_trees_ii}/unique_bst.c (100%) rename {096_unique_binary_search_trees => 0096_unique_binary_search_trees}/Makefile (100%) rename {096_unique_binary_search_trees => 0096_unique_binary_search_trees}/unique_bst.c (100%) rename {097_interleaving_string => 0097_interleaving_string}/Makefile (100%) rename {097_interleaving_string => 0097_interleaving_string}/interleaving_string.c (100%) rename {098_validate_binary_search_tree => 0098_validate_binary_search_tree}/Makefile (100%) rename {098_validate_binary_search_tree => 0098_validate_binary_search_tree}/valid_bst.c (100%) rename {098_validate_binary_search_tree => 0098_validate_binary_search_tree}/valid_bst.cc (100%) rename {099_recover_binary_search_tree => 0099_recover_binary_search_tree}/Makefile (100%) rename {099_recover_binary_search_tree => 0099_recover_binary_search_tree}/recover_bst.c (100%) rename {100_same_tree => 0100_same_tree}/Makefile (100%) rename {100_same_tree => 0100_same_tree}/same_tree.c (100%) rename {100_same_tree => 0100_same_tree}/same_tree.cc (100%) rename {101_symmetric_tree => 0101_symmetric_tree}/Makefile (100%) rename {101_symmetric_tree => 0101_symmetric_tree}/symmetric_tree.c (100%) rename {101_symmetric_tree => 0101_symmetric_tree}/symmetric_tree.cc (100%) rename {102_binary_tree_level_order_traversal => 0102_binary_tree_level_order_traversal}/Makefile (100%) rename {102_binary_tree_level_order_traversal => 0102_binary_tree_level_order_traversal}/bst_bfs.c (100%) rename {102_binary_tree_level_order_traversal => 0102_binary_tree_level_order_traversal}/bst_bfs.cc (100%) rename {103_binary_tree_zigzag_level_order_traversal => 0103_binary_tree_zigzag_level_order_traversal}/Makefile (100%) rename {103_binary_tree_zigzag_level_order_traversal => 0103_binary_tree_zigzag_level_order_traversal}/bst_zigzag.c (100%) rename {104_maximum_depth_of_binary_tree => 0104_maximum_depth_of_binary_tree}/Makefile (100%) rename {104_maximum_depth_of_binary_tree => 0104_maximum_depth_of_binary_tree}/bst_depth.c (100%) rename {104_maximum_depth_of_binary_tree => 0104_maximum_depth_of_binary_tree}/bst_depth.cc (100%) rename {105_construct_binary_tree_from_preorder_and_inorder_traversal => 0105_construct_binary_tree_from_preorder_and_inorder_traversal}/Makefile (100%) rename {105_construct_binary_tree_from_preorder_and_inorder_traversal => 0105_construct_binary_tree_from_preorder_and_inorder_traversal}/binary_tree_build.c (100%) rename {106_construct_binary_tree_from_inorder_and_postorder_traversal => 0106_construct_binary_tree_from_inorder_and_postorder_traversal}/Makefile (100%) rename {106_construct_binary_tree_from_inorder_and_postorder_traversal => 0106_construct_binary_tree_from_inorder_and_postorder_traversal}/binary_tree_build.c (100%) rename {107_binary_tree_level_order_traversal_ii => 0107_binary_tree_level_order_traversal_ii}/Makefile (100%) rename {107_binary_tree_level_order_traversal_ii => 0107_binary_tree_level_order_traversal_ii}/bst_bfs.c (100%) rename {107_binary_tree_level_order_traversal_ii => 0107_binary_tree_level_order_traversal_ii}/bst_bfs.cc (100%) rename {108_convert_sorted_array_to_binary_search_tree => 0108_convert_sorted_array_to_binary_search_tree}/Makefile (100%) rename {108_convert_sorted_array_to_binary_search_tree => 0108_convert_sorted_array_to_binary_search_tree}/bst_convert.c (100%) rename {108_convert_sorted_array_to_binary_search_tree => 0108_convert_sorted_array_to_binary_search_tree}/bst_convert.cc (100%) rename {109_convert_sorted_list_to_binary_search_tree => 0109_convert_sorted_list_to_binary_search_tree}/Makefile (100%) rename {109_convert_sorted_list_to_binary_search_tree => 0109_convert_sorted_list_to_binary_search_tree}/bst_convert.c (100%) rename {110_balanced_binary_tree => 0110_balanced_binary_tree}/Makefile (100%) rename {110_balanced_binary_tree => 0110_balanced_binary_tree}/balanced_bst.c (100%) rename {110_balanced_binary_tree => 0110_balanced_binary_tree}/balanced_bst.cc (100%) rename {111_minimum_depth_of_binary_tree => 0111_minimum_depth_of_binary_tree}/Makefile (100%) rename {111_minimum_depth_of_binary_tree => 0111_minimum_depth_of_binary_tree}/bst_depth.c (100%) rename {111_minimum_depth_of_binary_tree => 0111_minimum_depth_of_binary_tree}/bst_depth.cc (100%) rename {112_path_sum => 0112_path_sum}/Makefile (100%) rename {112_path_sum => 0112_path_sum}/path_sum.c (100%) rename {112_path_sum => 0112_path_sum}/path_sum.cc (100%) rename {113_path_sum_ii => 0113_path_sum_ii}/Makefile (100%) rename {113_path_sum_ii => 0113_path_sum_ii}/path_sum.c (100%) rename {114_flatten_binary_tree_to_linked_list => 0114_flatten_binary_tree_to_linked_list}/Makefile (100%) rename {114_flatten_binary_tree_to_linked_list => 0114_flatten_binary_tree_to_linked_list}/flatten.c (100%) rename {115_distinct_subsequences => 0115_distinct_subsequences}/Makefile (100%) rename {115_distinct_subsequences => 0115_distinct_subsequences}/distinct_subseq.c (100%) rename {116_populating_next_right_pointers_in_each_node => 0116_populating_next_right_pointers_in_each_node}/Makefile (100%) rename {116_populating_next_right_pointers_in_each_node => 0116_populating_next_right_pointers_in_each_node}/connect.c (100%) rename {117_populating_next_right_pointers_in_each_node_ii => 0117_populating_next_right_pointers_in_each_node_ii}/Makefile (100%) rename {117_populating_next_right_pointers_in_each_node_ii => 0117_populating_next_right_pointers_in_each_node_ii}/connect.c (100%) rename {118_pascal_triangle => 0118_pascal_triangle}/Makefile (100%) rename {118_pascal_triangle => 0118_pascal_triangle}/pascal_triangle.c (100%) rename {119_pascal_triangle_ii => 0119_pascal_triangle_ii}/Makefile (100%) rename {119_pascal_triangle_ii => 0119_pascal_triangle_ii}/pascal_triangle.c (100%) rename {120_triangle => 0120_triangle}/Makefile (100%) rename {120_triangle => 0120_triangle}/triangle.c (100%) rename {121_best_time_to_buy_and_sell_stock => 0121_best_time_to_buy_and_sell_stock}/Makefile (100%) rename {121_best_time_to_buy_and_sell_stock => 0121_best_time_to_buy_and_sell_stock}/stock.c (100%) rename {121_best_time_to_buy_and_sell_stock => 0121_best_time_to_buy_and_sell_stock}/stock.cc (100%) rename {122_best_time_to_buy_and_sell_stock_ii => 0122_best_time_to_buy_and_sell_stock_ii}/Makefile (100%) rename {122_best_time_to_buy_and_sell_stock_ii => 0122_best_time_to_buy_and_sell_stock_ii}/stock.c (100%) rename {122_best_time_to_buy_and_sell_stock_ii => 0122_best_time_to_buy_and_sell_stock_ii}/stock.cc (100%) rename {123_best_time_to_buy_and_sell_stock_iii => 0123_best_time_to_buy_and_sell_stock_iii}/Makefile (100%) rename {123_best_time_to_buy_and_sell_stock_iii => 0123_best_time_to_buy_and_sell_stock_iii}/stock.c (100%) rename {124_binary_tree_maximum_path_sum => 0124_binary_tree_maximum_path_sum}/Makefile (100%) rename {124_binary_tree_maximum_path_sum => 0124_binary_tree_maximum_path_sum}/bst_max_path.c (100%) rename {124_binary_tree_maximum_path_sum => 0124_binary_tree_maximum_path_sum}/bst_max_path.cc (100%) rename {125_valid_palindrome => 0125_valid_palindrome}/Makefile (100%) rename {125_valid_palindrome => 0125_valid_palindrome}/valid_palindrome.c (100%) rename {126_word_ladder_ii => 0126_word_ladder_ii}/Makefile (100%) rename {126_word_ladder_ii => 0126_word_ladder_ii}/word_ladder.c (100%) rename {127_word_ladder => 0127_word_ladder}/Makefile (100%) rename {127_word_ladder => 0127_word_ladder}/word_ladder.c (100%) rename {128_longest_consecutive_sequence => 0128_longest_consecutive_sequence}/Makefile (100%) rename {128_longest_consecutive_sequence => 0128_longest_consecutive_sequence}/consec_seq.c (100%) rename {129_sum_root_to_leaf_numbers => 0129_sum_root_to_leaf_numbers}/Makefile (100%) rename {129_sum_root_to_leaf_numbers => 0129_sum_root_to_leaf_numbers}/sum_tree.c (100%) rename {130_surrounded_regions => 0130_surrounded_regions}/Makefile (100%) rename {130_surrounded_regions => 0130_surrounded_regions}/surrounded_regions.c (100%) rename {131_palindrome_patitioning => 0131_palindrome_patitioning}/Makefile (100%) rename {131_palindrome_patitioning => 0131_palindrome_patitioning}/palindrome_partition.c (100%) rename {132_palindrome_patitioning_ii => 0132_palindrome_patitioning_ii}/Makefile (100%) rename {132_palindrome_patitioning_ii => 0132_palindrome_patitioning_ii}/palindrome_partition.c (100%) rename {133_clone_graph => 0133_clone_graph}/Makefile (100%) rename {133_clone_graph => 0133_clone_graph}/clone_graph.c (100%) rename {134_gas_station => 0134_gas_station}/Makefile (100%) rename {134_gas_station => 0134_gas_station}/gas_station.c (100%) rename {135_candy => 0135_candy}/Makefile (100%) rename {135_candy => 0135_candy}/candy.c (100%) rename {136_single_number => 0136_single_number}/Makefile (100%) rename {136_single_number => 0136_single_number}/single_number.c (100%) rename {136_single_number => 0136_single_number}/single_number.cc (100%) rename {137_single_number_ii => 0137_single_number_ii}/Makefile (100%) rename {137_single_number_ii => 0137_single_number_ii}/single_number.c (100%) rename {138_copy_list_with_random_pointer => 0138_copy_list_with_random_pointer}/Makefile (100%) rename {138_copy_list_with_random_pointer => 0138_copy_list_with_random_pointer}/copy_list.c (100%) rename {138_copy_list_with_random_pointer => 0138_copy_list_with_random_pointer}/copy_list.cc (100%) rename {139_word_break => 0139_word_break}/Makefile (100%) rename {139_word_break => 0139_word_break}/word_break.c (100%) rename {140_word_break_ii => 0140_word_break_ii}/Makefile (100%) rename {140_word_break_ii => 0140_word_break_ii}/word_break.c (100%) rename {141_linked_list_cycle => 0141_linked_list_cycle}/Makefile (100%) rename {141_linked_list_cycle => 0141_linked_list_cycle}/list_cycle.c (100%) rename {141_linked_list_cycle => 0141_linked_list_cycle}/list_cycle.cc (100%) rename {142_linked_list_cycle_ii => 0142_linked_list_cycle_ii}/Makefile (100%) rename {142_linked_list_cycle_ii => 0142_linked_list_cycle_ii}/list_cycle.c (100%) rename {142_linked_list_cycle_ii => 0142_linked_list_cycle_ii}/list_cycle.cc (100%) rename {143_reorder_list => 0143_reorder_list}/Makefile (100%) rename {143_reorder_list => 0143_reorder_list}/reorder_list.c (100%) rename {144_binary_tree_preorder_traversal => 0144_binary_tree_preorder_traversal}/Makefile (100%) rename {144_binary_tree_preorder_traversal => 0144_binary_tree_preorder_traversal}/bst_preorder.c (100%) rename {144_binary_tree_preorder_traversal => 0144_binary_tree_preorder_traversal}/bst_preorder.cc (100%) rename {145_binary_tree_postorder_traversal => 0145_binary_tree_postorder_traversal}/Makefile (100%) rename {145_binary_tree_postorder_traversal => 0145_binary_tree_postorder_traversal}/bst_postorder.c (100%) rename {145_binary_tree_postorder_traversal => 0145_binary_tree_postorder_traversal}/bst_postorder.cc (100%) rename {146_lru_cache => 0146_lru_cache}/Makefile (100%) rename {146_lru_cache => 0146_lru_cache}/lru_cache.c (100%) rename {146_lru_cache => 0146_lru_cache}/lru_cache.cc (100%) rename {147_insertion_sort_list => 0147_insertion_sort_list}/Makefile (100%) rename {147_insertion_sort_list => 0147_insertion_sort_list}/insert_sort_list.c (100%) rename {148_sort_list => 0148_sort_list}/Makefile (100%) rename {148_sort_list => 0148_sort_list}/sort_list.c (100%) rename {149_max_points_on_a_line => 0149_max_points_on_a_line}/Makefile (100%) rename {149_max_points_on_a_line => 0149_max_points_on_a_line}/points_on_line.c (100%) rename {150_evaluate_reverse_polish_notation => 0150_evaluate_reverse_polish_notation}/Makefile (100%) rename {150_evaluate_reverse_polish_notation => 0150_evaluate_reverse_polish_notation}/eval_rpn.c (100%) rename {151_reverse_words_in_a_string => 0151_reverse_words_in_a_string}/Makefile (100%) rename {151_reverse_words_in_a_string => 0151_reverse_words_in_a_string}/reverse.c (100%) rename {152_maximum_product_subarray => 0152_maximum_product_subarray}/Makefile (100%) rename {152_maximum_product_subarray => 0152_maximum_product_subarray}/subarray.c (100%) rename {153_find_minimum_in_rotated_sorted_array => 0153_find_minimum_in_rotated_sorted_array}/Makefile (100%) rename {153_find_minimum_in_rotated_sorted_array => 0153_find_minimum_in_rotated_sorted_array}/minimum.c (100%) rename {154_find_minimum_in_rotated_sorted_array_ii => 0154_find_minimum_in_rotated_sorted_array_ii}/Makefile (100%) rename {154_find_minimum_in_rotated_sorted_array_ii => 0154_find_minimum_in_rotated_sorted_array_ii}/minimum.c (100%) rename {155_min_stack => 0155_min_stack}/Makefile (100%) rename {155_min_stack => 0155_min_stack}/stack.c (100%) rename {160_intersection_of_two_linked_list => 0160_intersection_of_two_linked_list}/Makefile (100%) rename {160_intersection_of_two_linked_list => 0160_intersection_of_two_linked_list}/intersection.c (100%) rename {162_find_peak_element => 0162_find_peak_element}/Makefile (100%) rename {162_find_peak_element => 0162_find_peak_element}/peak.c (100%) rename {164_maximum_gap => 0164_maximum_gap}/Makefile (100%) rename {164_maximum_gap => 0164_maximum_gap}/max_gap.c (100%) rename {164_maximum_gap => 0164_maximum_gap}/max_gap.cc (100%) rename {165_compare_version_numbers => 0165_compare_version_numbers}/Makefile (100%) rename {165_compare_version_numbers => 0165_compare_version_numbers}/version.c (100%) rename {166_fraction_to_recurring_decimal => 0166_fraction_to_recurring_decimal}/Makefile (100%) rename {166_fraction_to_recurring_decimal => 0166_fraction_to_recurring_decimal}/fraction.c (100%) rename {167_two_sum_ii => 0167_two_sum_ii}/Makefile (100%) rename {167_two_sum_ii => 0167_two_sum_ii}/two_sum.c (100%) rename {167_two_sum_ii => 0167_two_sum_ii}/two_sum.cc (100%) rename {168_excel_sheet_column_title => 0168_excel_sheet_column_title}/Makefile (100%) rename {168_excel_sheet_column_title => 0168_excel_sheet_column_title}/sheet_column.c (100%) rename {169_majority_element => 0169_majority_element}/Makefile (100%) rename {169_majority_element => 0169_majority_element}/majority.c (100%) rename {169_majority_element => 0169_majority_element}/majority.cc (100%) rename {171_excel_sheet_column_number => 0171_excel_sheet_column_number}/Makefile (100%) rename {171_excel_sheet_column_number => 0171_excel_sheet_column_number}/sheet_column.c (100%) rename {172_factorial_trailing_zeros => 0172_factorial_trailing_zeros}/Makefile (100%) rename {172_factorial_trailing_zeros => 0172_factorial_trailing_zeros}/zeroes.c (100%) rename {172_factorial_trailing_zeros => 0172_factorial_trailing_zeros}/zeroes.cc (100%) rename {173_binary_search_tree_iterator => 0173_binary_search_tree_iterator}/Makefile (100%) rename {173_binary_search_tree_iterator => 0173_binary_search_tree_iterator}/bst_iter.c (100%) rename {174_dungeon_game => 0174_dungeon_game}/Makefile (100%) rename {174_dungeon_game => 0174_dungeon_game}/dungeon.c (100%) rename {179_largest_number => 0179_largest_number}/Makefile (100%) rename {179_largest_number => 0179_largest_number}/largest_number.c (100%) rename {179_largest_number => 0179_largest_number}/largest_number.cc (100%) rename {188_best_time_to_buy_and_sell_stock_iv => 0188_best_time_to_buy_and_sell_stock_iv}/Makefile (100%) rename {188_best_time_to_buy_and_sell_stock_iv => 0188_best_time_to_buy_and_sell_stock_iv}/stock.c (100%) rename {189_rotate_array => 0189_rotate_array}/Makefile (100%) rename {189_rotate_array => 0189_rotate_array}/rotate_array.c (100%) rename {189_rotate_array => 0189_rotate_array}/rotate_array.cc (100%) rename {190_reverse_bits => 0190_reverse_bits}/Makefile (100%) rename {190_reverse_bits => 0190_reverse_bits}/reverse_bits.c (100%) rename {191_number_of_one_bits => 0191_number_of_one_bits}/Makefile (100%) rename {191_number_of_one_bits => 0191_number_of_one_bits}/hamming_weight.c (100%) rename {198_house_robber => 0198_house_robber}/Makefile (100%) rename {198_house_robber => 0198_house_robber}/robber.c (100%) rename {198_house_robber => 0198_house_robber}/robber.cc (100%) rename {199_binary_tree_right_side_view => 0199_binary_tree_right_side_view}/Makefile (100%) rename {199_binary_tree_right_side_view => 0199_binary_tree_right_side_view}/bst_right.c (100%) rename {200_number_of_islands => 0200_number_of_islands}/Makefile (100%) rename {200_number_of_islands => 0200_number_of_islands}/islands.c (100%) rename {201_bitwise_and_of_numbers_range => 0201_bitwise_and_of_numbers_range}/Makefile (100%) rename {201_bitwise_and_of_numbers_range => 0201_bitwise_and_of_numbers_range}/and.c (100%) rename {202_happy_number => 0202_happy_number}/Makefile (100%) rename {202_happy_number => 0202_happy_number}/happy_number.c (100%) rename {203_remove_linked_list_element => 0203_remove_linked_list_element}/Makefile (100%) rename {203_remove_linked_list_element => 0203_remove_linked_list_element}/rm_elem.c (100%) rename {204_count_primes => 0204_count_primes}/Makefile (100%) rename {204_count_primes => 0204_count_primes}/count_primes.c (100%) rename {205_isomorphic_strings => 0205_isomorphic_strings}/Makefile (100%) rename {205_isomorphic_strings => 0205_isomorphic_strings}/isomorphic_strings.c (100%) rename {206_reverse_linked_list => 0206_reverse_linked_list}/Makefile (100%) rename {206_reverse_linked_list => 0206_reverse_linked_list}/reverse_list.c (100%) rename {207_course_schedule => 0207_course_schedule}/Makefile (100%) rename {207_course_schedule => 0207_course_schedule}/course_schedule.c (100%) rename {208_implement_trie => 0208_implement_trie}/Makefile (100%) rename {208_implement_trie => 0208_implement_trie}/trie.c (100%) rename {209_minimum_size_subarray_sum => 0209_minimum_size_subarray_sum}/Makefile (100%) rename {209_minimum_size_subarray_sum => 0209_minimum_size_subarray_sum}/mini_size.c (100%) rename {210_course_schedule_ii => 0210_course_schedule_ii}/Makefile (100%) rename {210_course_schedule_ii => 0210_course_schedule_ii}/course_schedule.c (100%) rename {211_add_and_search_word => 0211_add_and_search_word}/Makefile (100%) rename {211_add_and_search_word => 0211_add_and_search_word}/word_dict.c (100%) rename {212_word_search_ii => 0212_word_search_ii}/Makefile (100%) rename {212_word_search_ii => 0212_word_search_ii}/word_search.c (100%) rename {213_house_robber_ii => 0213_house_robber_ii}/Makefile (100%) rename {213_house_robber_ii => 0213_house_robber_ii}/robber.c (100%) rename {213_house_robber_ii => 0213_house_robber_ii}/robber.cc (100%) rename {214_shortest_palindrome => 0214_shortest_palindrome}/Makefile (100%) rename {214_shortest_palindrome => 0214_shortest_palindrome}/shortest_palindrome.c (100%) rename {215_kth_largest_element_in_an_array => 0215_kth_largest_element_in_an_array}/Makefile (100%) rename {215_kth_largest_element_in_an_array => 0215_kth_largest_element_in_an_array}/kth_elem.c (100%) rename {215_kth_largest_element_in_an_array => 0215_kth_largest_element_in_an_array}/kth_elem.cc (100%) rename {216_combination_sum_iii => 0216_combination_sum_iii}/Makefile (100%) rename {216_combination_sum_iii => 0216_combination_sum_iii}/combination_sum.c (100%) rename {221_maximal_square => 0221_maximal_square}/Makefile (100%) rename {221_maximal_square => 0221_maximal_square}/maximal_square.c (100%) rename {224_basic_calculator => 0224_basic_calculator}/Makefile (100%) rename {224_basic_calculator => 0224_basic_calculator}/calculator.c (100%) rename {226_invert_binary_tree => 0226_invert_binary_tree}/Makefile (100%) rename {226_invert_binary_tree => 0226_invert_binary_tree}/invert_binary_tree.c (100%) rename {226_invert_binary_tree => 0226_invert_binary_tree}/invert_binary_tree.cc (100%) rename {227_basic_calculator_ii => 0227_basic_calculator_ii}/Makefile (100%) rename {227_basic_calculator_ii => 0227_basic_calculator_ii}/calculator.c (100%) rename {229_majority_element_ii => 0229_majority_element_ii}/Makefile (100%) rename {229_majority_element_ii => 0229_majority_element_ii}/majority.c (100%) rename {230_kth_smallest_element_in_a_bst => 0230_kth_smallest_element_in_a_bst}/Makefile (100%) rename {230_kth_smallest_element_in_a_bst => 0230_kth_smallest_element_in_a_bst}/kth_bst.c (100%) rename {230_kth_smallest_element_in_a_bst => 0230_kth_smallest_element_in_a_bst}/kth_bst.cc (100%) rename {235_lowest_common_ancestor_of_a_binary_search_tree => 0235_lowest_common_ancestor_of_a_binary_search_tree}/Makefile (100%) rename {235_lowest_common_ancestor_of_a_binary_search_tree => 0235_lowest_common_ancestor_of_a_binary_search_tree}/bst_lca.c (100%) rename {236_lowest_common_ancestor_of_a_binary_tree => 0236_lowest_common_ancestor_of_a_binary_tree}/Makefile (100%) rename {236_lowest_common_ancestor_of_a_binary_tree => 0236_lowest_common_ancestor_of_a_binary_tree}/bst_lca.c (100%) rename {239_sliding_window_maximum => 0239_sliding_window_maximum}/Makefile (100%) rename {239_sliding_window_maximum => 0239_sliding_window_maximum}/slide_window.c (100%) rename {239_sliding_window_maximum => 0239_sliding_window_maximum}/slide_window.cc (100%) rename {337_house_robber_iii => 0337_house_robber_iii}/robber.cc (100%) rename {416_partition_equal_subset_sum => 0416_partition_equal_subset_sum}/partition.cc (100%) rename {460_lfu_cache => 0460_lfu_cache}/Makefile (100%) rename {460_lfu_cache => 0460_lfu_cache}/lfu_cache.c (100%) rename {460_lfu_cache => 0460_lfu_cache}/lfu_cache.cc (100%) rename {543_diameter_of_binary_tree => 0543_diameter_of_binary_tree}/diameter_bst.cc (100%) rename {563_binary_tree_tilt => 0563_binary_tree_tilt}/tilt.cc (100%) diff --git a/001_two_sum/Makefile b/0001_two_sum/Makefile similarity index 100% rename from 001_two_sum/Makefile rename to 0001_two_sum/Makefile diff --git a/001_two_sum/two_sum.c b/0001_two_sum/two_sum.c similarity index 100% rename from 001_two_sum/two_sum.c rename to 0001_two_sum/two_sum.c diff --git a/001_two_sum/two_sum.cc b/0001_two_sum/two_sum.cc similarity index 100% rename from 001_two_sum/two_sum.cc rename to 0001_two_sum/two_sum.cc diff --git a/001_two_sum/two_sum.py b/0001_two_sum/two_sum.py similarity index 100% rename from 001_two_sum/two_sum.py rename to 0001_two_sum/two_sum.py diff --git a/002_add_two_numbers/Makefile b/0002_add_two_numbers/Makefile similarity index 100% rename from 002_add_two_numbers/Makefile rename to 0002_add_two_numbers/Makefile diff --git a/002_add_two_numbers/add_two_numbers.c b/0002_add_two_numbers/add_two_numbers.c similarity index 100% rename from 002_add_two_numbers/add_two_numbers.c rename to 0002_add_two_numbers/add_two_numbers.c diff --git a/002_add_two_numbers/add_two_numbers.cc b/0002_add_two_numbers/add_two_numbers.cc similarity index 100% rename from 002_add_two_numbers/add_two_numbers.cc rename to 0002_add_two_numbers/add_two_numbers.cc diff --git a/003_longest_substring_without_repeat/Makefile b/0003_longest_substring_without_repeat/Makefile similarity index 100% rename from 003_longest_substring_without_repeat/Makefile rename to 0003_longest_substring_without_repeat/Makefile diff --git a/003_longest_substring_without_repeat/longest_substring_without_repeat.c b/0003_longest_substring_without_repeat/longest_substring_without_repeat.c similarity index 100% rename from 003_longest_substring_without_repeat/longest_substring_without_repeat.c rename to 0003_longest_substring_without_repeat/longest_substring_without_repeat.c diff --git a/003_longest_substring_without_repeat/longest_substring_without_repeat.cc b/0003_longest_substring_without_repeat/longest_substring_without_repeat.cc similarity index 100% rename from 003_longest_substring_without_repeat/longest_substring_without_repeat.cc rename to 0003_longest_substring_without_repeat/longest_substring_without_repeat.cc diff --git a/004_median_of_two_sorted_array/Makefile b/0004_median_of_two_sorted_array/Makefile similarity index 100% rename from 004_median_of_two_sorted_array/Makefile rename to 0004_median_of_two_sorted_array/Makefile diff --git a/004_median_of_two_sorted_array/median_of_two_sorted_array.c b/0004_median_of_two_sorted_array/median_of_two_sorted_array.c similarity index 100% rename from 004_median_of_two_sorted_array/median_of_two_sorted_array.c rename to 0004_median_of_two_sorted_array/median_of_two_sorted_array.c diff --git a/004_median_of_two_sorted_array/median_of_two_sorted_array.cc b/0004_median_of_two_sorted_array/median_of_two_sorted_array.cc similarity index 100% rename from 004_median_of_two_sorted_array/median_of_two_sorted_array.cc rename to 0004_median_of_two_sorted_array/median_of_two_sorted_array.cc diff --git a/005_longest_palindromic_substring/Makefile b/0005_longest_palindromic_substring/Makefile similarity index 100% rename from 005_longest_palindromic_substring/Makefile rename to 0005_longest_palindromic_substring/Makefile diff --git a/005_longest_palindromic_substring/longest_palindromic_substring.c b/0005_longest_palindromic_substring/longest_palindromic_substring.c similarity index 100% rename from 005_longest_palindromic_substring/longest_palindromic_substring.c rename to 0005_longest_palindromic_substring/longest_palindromic_substring.c diff --git a/006_zigzag_conversion/Makefile b/0006_zigzag_conversion/Makefile similarity index 100% rename from 006_zigzag_conversion/Makefile rename to 0006_zigzag_conversion/Makefile diff --git a/006_zigzag_conversion/zigzag_conversion.c b/0006_zigzag_conversion/zigzag_conversion.c similarity index 100% rename from 006_zigzag_conversion/zigzag_conversion.c rename to 0006_zigzag_conversion/zigzag_conversion.c diff --git a/006_zigzag_conversion/zigzag_conversion.cc b/0006_zigzag_conversion/zigzag_conversion.cc similarity index 100% rename from 006_zigzag_conversion/zigzag_conversion.cc rename to 0006_zigzag_conversion/zigzag_conversion.cc diff --git a/007_reverse_integer/Makefile b/0007_reverse_integer/Makefile similarity index 100% rename from 007_reverse_integer/Makefile rename to 0007_reverse_integer/Makefile diff --git a/007_reverse_integer/reverse_integer.c b/0007_reverse_integer/reverse_integer.c similarity index 100% rename from 007_reverse_integer/reverse_integer.c rename to 0007_reverse_integer/reverse_integer.c diff --git a/007_reverse_integer/reverse_integer.cc b/0007_reverse_integer/reverse_integer.cc similarity index 100% rename from 007_reverse_integer/reverse_integer.cc rename to 0007_reverse_integer/reverse_integer.cc diff --git a/008_atoi/Makefile b/0008_atoi/Makefile similarity index 100% rename from 008_atoi/Makefile rename to 0008_atoi/Makefile diff --git a/008_atoi/atoi.c b/0008_atoi/atoi.c similarity index 100% rename from 008_atoi/atoi.c rename to 0008_atoi/atoi.c diff --git a/008_atoi/atoi.cc b/0008_atoi/atoi.cc similarity index 100% rename from 008_atoi/atoi.cc rename to 0008_atoi/atoi.cc diff --git a/009_palindrome_number/Makefile b/0009_palindrome_number/Makefile similarity index 100% rename from 009_palindrome_number/Makefile rename to 0009_palindrome_number/Makefile diff --git a/009_palindrome_number/palindrome_number.c b/0009_palindrome_number/palindrome_number.c similarity index 100% rename from 009_palindrome_number/palindrome_number.c rename to 0009_palindrome_number/palindrome_number.c diff --git a/009_palindrome_number/palindrome_number.cc b/0009_palindrome_number/palindrome_number.cc similarity index 100% rename from 009_palindrome_number/palindrome_number.cc rename to 0009_palindrome_number/palindrome_number.cc diff --git a/010_regular_expression_matching/Makefile b/0010_regular_expression_matching/Makefile similarity index 100% rename from 010_regular_expression_matching/Makefile rename to 0010_regular_expression_matching/Makefile diff --git a/010_regular_expression_matching/regular_expression.c b/0010_regular_expression_matching/regular_expression.c similarity index 100% rename from 010_regular_expression_matching/regular_expression.c rename to 0010_regular_expression_matching/regular_expression.c diff --git a/010_regular_expression_matching/regular_expression.cc b/0010_regular_expression_matching/regular_expression.cc similarity index 100% rename from 010_regular_expression_matching/regular_expression.cc rename to 0010_regular_expression_matching/regular_expression.cc diff --git a/011_container_with_most_water/Makefile b/0011_container_with_most_water/Makefile similarity index 100% rename from 011_container_with_most_water/Makefile rename to 0011_container_with_most_water/Makefile diff --git a/011_container_with_most_water/container.c b/0011_container_with_most_water/container.c similarity index 100% rename from 011_container_with_most_water/container.c rename to 0011_container_with_most_water/container.c diff --git a/011_container_with_most_water/container.cc b/0011_container_with_most_water/container.cc similarity index 100% rename from 011_container_with_most_water/container.cc rename to 0011_container_with_most_water/container.cc diff --git a/012_roman_numeral/Makefile b/0012_roman_numeral/Makefile similarity index 100% rename from 012_roman_numeral/Makefile rename to 0012_roman_numeral/Makefile diff --git a/012_roman_numeral/roman_numeral.c b/0012_roman_numeral/roman_numeral.c similarity index 100% rename from 012_roman_numeral/roman_numeral.c rename to 0012_roman_numeral/roman_numeral.c diff --git a/012_roman_numeral/roman_numeral.cc b/0012_roman_numeral/roman_numeral.cc similarity index 100% rename from 012_roman_numeral/roman_numeral.cc rename to 0012_roman_numeral/roman_numeral.cc diff --git a/013_roman_to_integer/Makefile b/0013_roman_to_integer/Makefile similarity index 100% rename from 013_roman_to_integer/Makefile rename to 0013_roman_to_integer/Makefile diff --git a/013_roman_to_integer/roman_to_integer.c b/0013_roman_to_integer/roman_to_integer.c similarity index 100% rename from 013_roman_to_integer/roman_to_integer.c rename to 0013_roman_to_integer/roman_to_integer.c diff --git a/013_roman_to_integer/roman_to_integer.cc b/0013_roman_to_integer/roman_to_integer.cc similarity index 100% rename from 013_roman_to_integer/roman_to_integer.cc rename to 0013_roman_to_integer/roman_to_integer.cc diff --git a/014_longest_common_prefix/Makefile b/0014_longest_common_prefix/Makefile similarity index 100% rename from 014_longest_common_prefix/Makefile rename to 0014_longest_common_prefix/Makefile diff --git a/014_longest_common_prefix/common_prefix.c b/0014_longest_common_prefix/common_prefix.c similarity index 100% rename from 014_longest_common_prefix/common_prefix.c rename to 0014_longest_common_prefix/common_prefix.c diff --git a/014_longest_common_prefix/common_prefix.cc b/0014_longest_common_prefix/common_prefix.cc similarity index 100% rename from 014_longest_common_prefix/common_prefix.cc rename to 0014_longest_common_prefix/common_prefix.cc diff --git a/015_three_sum/Makefile b/0015_three_sum/Makefile similarity index 100% rename from 015_three_sum/Makefile rename to 0015_three_sum/Makefile diff --git a/015_three_sum/three_sum.c b/0015_three_sum/three_sum.c similarity index 100% rename from 015_three_sum/three_sum.c rename to 0015_three_sum/three_sum.c diff --git a/015_three_sum/three_sum.cc b/0015_three_sum/three_sum.cc similarity index 100% rename from 015_three_sum/three_sum.cc rename to 0015_three_sum/three_sum.cc diff --git a/016_three_sum_closest/Makefile b/0016_three_sum_closest/Makefile similarity index 100% rename from 016_three_sum_closest/Makefile rename to 0016_three_sum_closest/Makefile diff --git a/016_three_sum_closest/three_sum_closest.c b/0016_three_sum_closest/three_sum_closest.c similarity index 100% rename from 016_three_sum_closest/three_sum_closest.c rename to 0016_three_sum_closest/three_sum_closest.c diff --git a/016_three_sum_closest/three_sum_closest.cc b/0016_three_sum_closest/three_sum_closest.cc similarity index 100% rename from 016_three_sum_closest/three_sum_closest.cc rename to 0016_three_sum_closest/three_sum_closest.cc diff --git a/017_letter_combinations_of_a_phone_number/Makefile b/0017_letter_combinations_of_a_phone_number/Makefile similarity index 100% rename from 017_letter_combinations_of_a_phone_number/Makefile rename to 0017_letter_combinations_of_a_phone_number/Makefile diff --git a/017_letter_combinations_of_a_phone_number/letter_combinations.c b/0017_letter_combinations_of_a_phone_number/letter_combinations.c similarity index 100% rename from 017_letter_combinations_of_a_phone_number/letter_combinations.c rename to 0017_letter_combinations_of_a_phone_number/letter_combinations.c diff --git a/018_four_sum/Makefile b/0018_four_sum/Makefile similarity index 100% rename from 018_four_sum/Makefile rename to 0018_four_sum/Makefile diff --git a/018_four_sum/four_sum.c b/0018_four_sum/four_sum.c similarity index 100% rename from 018_four_sum/four_sum.c rename to 0018_four_sum/four_sum.c diff --git a/018_four_sum/four_sum.cc b/0018_four_sum/four_sum.cc similarity index 100% rename from 018_four_sum/four_sum.cc rename to 0018_four_sum/four_sum.cc diff --git a/019_remove_nth_node_from_end_of_list/Makefile b/0019_remove_nth_node_from_end_of_list/Makefile similarity index 100% rename from 019_remove_nth_node_from_end_of_list/Makefile rename to 0019_remove_nth_node_from_end_of_list/Makefile diff --git a/019_remove_nth_node_from_end_of_list/remove_end.c b/0019_remove_nth_node_from_end_of_list/remove_end.c similarity index 100% rename from 019_remove_nth_node_from_end_of_list/remove_end.c rename to 0019_remove_nth_node_from_end_of_list/remove_end.c diff --git a/019_remove_nth_node_from_end_of_list/remove_end.cc b/0019_remove_nth_node_from_end_of_list/remove_end.cc similarity index 100% rename from 019_remove_nth_node_from_end_of_list/remove_end.cc rename to 0019_remove_nth_node_from_end_of_list/remove_end.cc diff --git a/020_valid_parentheses/Makefile b/0020_valid_parentheses/Makefile similarity index 100% rename from 020_valid_parentheses/Makefile rename to 0020_valid_parentheses/Makefile diff --git a/020_valid_parentheses/valid_parentheses.c b/0020_valid_parentheses/valid_parentheses.c similarity index 100% rename from 020_valid_parentheses/valid_parentheses.c rename to 0020_valid_parentheses/valid_parentheses.c diff --git a/020_valid_parentheses/valid_parentheses.cc b/0020_valid_parentheses/valid_parentheses.cc similarity index 100% rename from 020_valid_parentheses/valid_parentheses.cc rename to 0020_valid_parentheses/valid_parentheses.cc diff --git a/021_merge_two_sorted_lists/Makefile b/0021_merge_two_sorted_lists/Makefile similarity index 100% rename from 021_merge_two_sorted_lists/Makefile rename to 0021_merge_two_sorted_lists/Makefile diff --git a/021_merge_two_sorted_lists/merge_lists.c b/0021_merge_two_sorted_lists/merge_lists.c similarity index 100% rename from 021_merge_two_sorted_lists/merge_lists.c rename to 0021_merge_two_sorted_lists/merge_lists.c diff --git a/021_merge_two_sorted_lists/merge_lists.cc b/0021_merge_two_sorted_lists/merge_lists.cc similarity index 100% rename from 021_merge_two_sorted_lists/merge_lists.cc rename to 0021_merge_two_sorted_lists/merge_lists.cc diff --git a/022_generate_parathesis/Makefile b/0022_generate_parathesis/Makefile similarity index 100% rename from 022_generate_parathesis/Makefile rename to 0022_generate_parathesis/Makefile diff --git a/022_generate_parathesis/parenthesis.c b/0022_generate_parathesis/parenthesis.c similarity index 100% rename from 022_generate_parathesis/parenthesis.c rename to 0022_generate_parathesis/parenthesis.c diff --git a/022_generate_parathesis/parenthesis.cc b/0022_generate_parathesis/parenthesis.cc similarity index 100% rename from 022_generate_parathesis/parenthesis.cc rename to 0022_generate_parathesis/parenthesis.cc diff --git a/023_merge_k_sorted_lists/Makefile b/0023_merge_k_sorted_lists/Makefile similarity index 100% rename from 023_merge_k_sorted_lists/Makefile rename to 0023_merge_k_sorted_lists/Makefile diff --git a/023_merge_k_sorted_lists/merge_lists.c b/0023_merge_k_sorted_lists/merge_lists.c similarity index 100% rename from 023_merge_k_sorted_lists/merge_lists.c rename to 0023_merge_k_sorted_lists/merge_lists.c diff --git a/023_merge_k_sorted_lists/merge_lists.cc b/0023_merge_k_sorted_lists/merge_lists.cc similarity index 100% rename from 023_merge_k_sorted_lists/merge_lists.cc rename to 0023_merge_k_sorted_lists/merge_lists.cc diff --git a/024_swap_nodes_in_pairs/Makefile b/0024_swap_nodes_in_pairs/Makefile similarity index 100% rename from 024_swap_nodes_in_pairs/Makefile rename to 0024_swap_nodes_in_pairs/Makefile diff --git a/024_swap_nodes_in_pairs/swap_nodes.c b/0024_swap_nodes_in_pairs/swap_nodes.c similarity index 100% rename from 024_swap_nodes_in_pairs/swap_nodes.c rename to 0024_swap_nodes_in_pairs/swap_nodes.c diff --git a/024_swap_nodes_in_pairs/swap_nodes.cc b/0024_swap_nodes_in_pairs/swap_nodes.cc similarity index 100% rename from 024_swap_nodes_in_pairs/swap_nodes.cc rename to 0024_swap_nodes_in_pairs/swap_nodes.cc diff --git a/025_reverse_nodes_in_k_group/Makefile b/0025_reverse_nodes_in_k_group/Makefile similarity index 100% rename from 025_reverse_nodes_in_k_group/Makefile rename to 0025_reverse_nodes_in_k_group/Makefile diff --git a/025_reverse_nodes_in_k_group/reverse_nodes.c b/0025_reverse_nodes_in_k_group/reverse_nodes.c similarity index 100% rename from 025_reverse_nodes_in_k_group/reverse_nodes.c rename to 0025_reverse_nodes_in_k_group/reverse_nodes.c diff --git a/025_reverse_nodes_in_k_group/reverse_nodes.cc b/0025_reverse_nodes_in_k_group/reverse_nodes.cc similarity index 100% rename from 025_reverse_nodes_in_k_group/reverse_nodes.cc rename to 0025_reverse_nodes_in_k_group/reverse_nodes.cc diff --git a/026_remove_duplicates_from_sorted_array/Makefile b/0026_remove_duplicates_from_sorted_array/Makefile similarity index 100% rename from 026_remove_duplicates_from_sorted_array/Makefile rename to 0026_remove_duplicates_from_sorted_array/Makefile diff --git a/026_remove_duplicates_from_sorted_array/rm_dup.c b/0026_remove_duplicates_from_sorted_array/rm_dup.c similarity index 100% rename from 026_remove_duplicates_from_sorted_array/rm_dup.c rename to 0026_remove_duplicates_from_sorted_array/rm_dup.c diff --git a/026_remove_duplicates_from_sorted_array/rm_dup.cc b/0026_remove_duplicates_from_sorted_array/rm_dup.cc similarity index 100% rename from 026_remove_duplicates_from_sorted_array/rm_dup.cc rename to 0026_remove_duplicates_from_sorted_array/rm_dup.cc diff --git a/027_remove_element/Makefile b/0027_remove_element/Makefile similarity index 100% rename from 027_remove_element/Makefile rename to 0027_remove_element/Makefile diff --git a/027_remove_element/rm_elem.c b/0027_remove_element/rm_elem.c similarity index 100% rename from 027_remove_element/rm_elem.c rename to 0027_remove_element/rm_elem.c diff --git a/027_remove_element/rm_elem.cc b/0027_remove_element/rm_elem.cc similarity index 100% rename from 027_remove_element/rm_elem.cc rename to 0027_remove_element/rm_elem.cc diff --git a/028_implement_strstr/Makefile b/0028_implement_strstr/Makefile similarity index 100% rename from 028_implement_strstr/Makefile rename to 0028_implement_strstr/Makefile diff --git a/028_implement_strstr/strstr.c b/0028_implement_strstr/strstr.c similarity index 100% rename from 028_implement_strstr/strstr.c rename to 0028_implement_strstr/strstr.c diff --git a/028_implement_strstr/strstr.cc b/0028_implement_strstr/strstr.cc similarity index 100% rename from 028_implement_strstr/strstr.cc rename to 0028_implement_strstr/strstr.cc diff --git a/029_divide_two_integers/Makefile b/0029_divide_two_integers/Makefile similarity index 100% rename from 029_divide_two_integers/Makefile rename to 0029_divide_two_integers/Makefile diff --git a/029_divide_two_integers/divide.c b/0029_divide_two_integers/divide.c similarity index 100% rename from 029_divide_two_integers/divide.c rename to 0029_divide_two_integers/divide.c diff --git a/029_divide_two_integers/divide.cc b/0029_divide_two_integers/divide.cc similarity index 100% rename from 029_divide_two_integers/divide.cc rename to 0029_divide_two_integers/divide.cc diff --git a/030_substring_with_concatenation_of_all_words/Makefile b/0030_substring_with_concatenation_of_all_words/Makefile similarity index 100% rename from 030_substring_with_concatenation_of_all_words/Makefile rename to 0030_substring_with_concatenation_of_all_words/Makefile diff --git a/030_substring_with_concatenation_of_all_words/concatenation.c b/0030_substring_with_concatenation_of_all_words/concatenation.c similarity index 100% rename from 030_substring_with_concatenation_of_all_words/concatenation.c rename to 0030_substring_with_concatenation_of_all_words/concatenation.c diff --git a/030_substring_with_concatenation_of_all_words/concatenation.cc b/0030_substring_with_concatenation_of_all_words/concatenation.cc similarity index 100% rename from 030_substring_with_concatenation_of_all_words/concatenation.cc rename to 0030_substring_with_concatenation_of_all_words/concatenation.cc diff --git a/031_next_permutation/Makefile b/0031_next_permutation/Makefile similarity index 100% rename from 031_next_permutation/Makefile rename to 0031_next_permutation/Makefile diff --git a/031_next_permutation/next_permutation.c b/0031_next_permutation/next_permutation.c similarity index 100% rename from 031_next_permutation/next_permutation.c rename to 0031_next_permutation/next_permutation.c diff --git a/031_next_permutation/next_permutation.cc b/0031_next_permutation/next_permutation.cc similarity index 100% rename from 031_next_permutation/next_permutation.cc rename to 0031_next_permutation/next_permutation.cc diff --git a/032_longest_valid_parentheses/Makefile b/0032_longest_valid_parentheses/Makefile similarity index 100% rename from 032_longest_valid_parentheses/Makefile rename to 0032_longest_valid_parentheses/Makefile diff --git a/032_longest_valid_parentheses/valid_parentheses.c b/0032_longest_valid_parentheses/valid_parentheses.c similarity index 100% rename from 032_longest_valid_parentheses/valid_parentheses.c rename to 0032_longest_valid_parentheses/valid_parentheses.c diff --git a/032_longest_valid_parentheses/valid_parentheses.cc b/0032_longest_valid_parentheses/valid_parentheses.cc similarity index 100% rename from 032_longest_valid_parentheses/valid_parentheses.cc rename to 0032_longest_valid_parentheses/valid_parentheses.cc diff --git a/033_search_in_rotated_sorted_array/Makefile b/0033_search_in_rotated_sorted_array/Makefile similarity index 100% rename from 033_search_in_rotated_sorted_array/Makefile rename to 0033_search_in_rotated_sorted_array/Makefile diff --git a/033_search_in_rotated_sorted_array/rotated_array.c b/0033_search_in_rotated_sorted_array/rotated_array.c similarity index 100% rename from 033_search_in_rotated_sorted_array/rotated_array.c rename to 0033_search_in_rotated_sorted_array/rotated_array.c diff --git a/033_search_in_rotated_sorted_array/rotated_array.cc b/0033_search_in_rotated_sorted_array/rotated_array.cc similarity index 100% rename from 033_search_in_rotated_sorted_array/rotated_array.cc rename to 0033_search_in_rotated_sorted_array/rotated_array.cc diff --git a/034_search_for_a_range/Makefile b/0034_search_for_a_range/Makefile similarity index 100% rename from 034_search_for_a_range/Makefile rename to 0034_search_for_a_range/Makefile diff --git a/034_search_for_a_range/range_search.c b/0034_search_for_a_range/range_search.c similarity index 100% rename from 034_search_for_a_range/range_search.c rename to 0034_search_for_a_range/range_search.c diff --git a/034_search_for_a_range/range_search.cc b/0034_search_for_a_range/range_search.cc similarity index 100% rename from 034_search_for_a_range/range_search.cc rename to 0034_search_for_a_range/range_search.cc diff --git a/035_search_insert_position/Makefile b/0035_search_insert_position/Makefile similarity index 100% rename from 035_search_insert_position/Makefile rename to 0035_search_insert_position/Makefile diff --git a/035_search_insert_position/insert_position.c b/0035_search_insert_position/insert_position.c similarity index 100% rename from 035_search_insert_position/insert_position.c rename to 0035_search_insert_position/insert_position.c diff --git a/035_search_insert_position/insert_position.cc b/0035_search_insert_position/insert_position.cc similarity index 100% rename from 035_search_insert_position/insert_position.cc rename to 0035_search_insert_position/insert_position.cc diff --git a/036_valid_sudoku/Makefile b/0036_valid_sudoku/Makefile similarity index 100% rename from 036_valid_sudoku/Makefile rename to 0036_valid_sudoku/Makefile diff --git a/036_valid_sudoku/valid_sudoku.c b/0036_valid_sudoku/valid_sudoku.c similarity index 100% rename from 036_valid_sudoku/valid_sudoku.c rename to 0036_valid_sudoku/valid_sudoku.c diff --git a/036_valid_sudoku/valid_sudoku.cc b/0036_valid_sudoku/valid_sudoku.cc similarity index 100% rename from 036_valid_sudoku/valid_sudoku.cc rename to 0036_valid_sudoku/valid_sudoku.cc diff --git a/037_sudoku_solver/Makefile b/0037_sudoku_solver/Makefile similarity index 100% rename from 037_sudoku_solver/Makefile rename to 0037_sudoku_solver/Makefile diff --git a/037_sudoku_solver/sudoku_solver.c b/0037_sudoku_solver/sudoku_solver.c similarity index 100% rename from 037_sudoku_solver/sudoku_solver.c rename to 0037_sudoku_solver/sudoku_solver.c diff --git a/037_sudoku_solver/sudoku_solver.cc b/0037_sudoku_solver/sudoku_solver.cc similarity index 100% rename from 037_sudoku_solver/sudoku_solver.cc rename to 0037_sudoku_solver/sudoku_solver.cc diff --git a/038_count_and_say/Makefile b/0038_count_and_say/Makefile similarity index 100% rename from 038_count_and_say/Makefile rename to 0038_count_and_say/Makefile diff --git a/038_count_and_say/count_and_say.c b/0038_count_and_say/count_and_say.c similarity index 100% rename from 038_count_and_say/count_and_say.c rename to 0038_count_and_say/count_and_say.c diff --git a/039_combination_sum/Makefile b/0039_combination_sum/Makefile similarity index 100% rename from 039_combination_sum/Makefile rename to 0039_combination_sum/Makefile diff --git a/039_combination_sum/combination_sum.c b/0039_combination_sum/combination_sum.c similarity index 100% rename from 039_combination_sum/combination_sum.c rename to 0039_combination_sum/combination_sum.c diff --git a/039_combination_sum/combination_sum.cc b/0039_combination_sum/combination_sum.cc similarity index 100% rename from 039_combination_sum/combination_sum.cc rename to 0039_combination_sum/combination_sum.cc diff --git a/040_combination_sum_ii/Makefile b/0040_combination_sum_ii/Makefile similarity index 100% rename from 040_combination_sum_ii/Makefile rename to 0040_combination_sum_ii/Makefile diff --git a/040_combination_sum_ii/combination_sum.c b/0040_combination_sum_ii/combination_sum.c similarity index 100% rename from 040_combination_sum_ii/combination_sum.c rename to 0040_combination_sum_ii/combination_sum.c diff --git a/040_combination_sum_ii/combination_sum.cc b/0040_combination_sum_ii/combination_sum.cc similarity index 100% rename from 040_combination_sum_ii/combination_sum.cc rename to 0040_combination_sum_ii/combination_sum.cc diff --git a/041_first_missing_positive/Makefile b/0041_first_missing_positive/Makefile similarity index 100% rename from 041_first_missing_positive/Makefile rename to 0041_first_missing_positive/Makefile diff --git a/041_first_missing_positive/missing_positive.c b/0041_first_missing_positive/missing_positive.c similarity index 100% rename from 041_first_missing_positive/missing_positive.c rename to 0041_first_missing_positive/missing_positive.c diff --git a/041_first_missing_positive/missing_positive.cc b/0041_first_missing_positive/missing_positive.cc similarity index 100% rename from 041_first_missing_positive/missing_positive.cc rename to 0041_first_missing_positive/missing_positive.cc diff --git a/042_trapping_rain_water/Makefile b/0042_trapping_rain_water/Makefile similarity index 100% rename from 042_trapping_rain_water/Makefile rename to 0042_trapping_rain_water/Makefile diff --git a/042_trapping_rain_water/trap_water.c b/0042_trapping_rain_water/trap_water.c similarity index 100% rename from 042_trapping_rain_water/trap_water.c rename to 0042_trapping_rain_water/trap_water.c diff --git a/042_trapping_rain_water/trap_water.cc b/0042_trapping_rain_water/trap_water.cc similarity index 100% rename from 042_trapping_rain_water/trap_water.cc rename to 0042_trapping_rain_water/trap_water.cc diff --git a/043_multiply_strings/Makefile b/0043_multiply_strings/Makefile similarity index 100% rename from 043_multiply_strings/Makefile rename to 0043_multiply_strings/Makefile diff --git a/043_multiply_strings/multiply_strings.c b/0043_multiply_strings/multiply_strings.c similarity index 100% rename from 043_multiply_strings/multiply_strings.c rename to 0043_multiply_strings/multiply_strings.c diff --git a/043_multiply_strings/multiply_strings.cc b/0043_multiply_strings/multiply_strings.cc similarity index 100% rename from 043_multiply_strings/multiply_strings.cc rename to 0043_multiply_strings/multiply_strings.cc diff --git a/044_wildcard_matching/Makefile b/0044_wildcard_matching/Makefile similarity index 100% rename from 044_wildcard_matching/Makefile rename to 0044_wildcard_matching/Makefile diff --git a/044_wildcard_matching/wildcard_matching.c b/0044_wildcard_matching/wildcard_matching.c similarity index 100% rename from 044_wildcard_matching/wildcard_matching.c rename to 0044_wildcard_matching/wildcard_matching.c diff --git a/045_jump_game_ii/Makefile b/0045_jump_game_ii/Makefile similarity index 100% rename from 045_jump_game_ii/Makefile rename to 0045_jump_game_ii/Makefile diff --git a/045_jump_game_ii/jump_game.c b/0045_jump_game_ii/jump_game.c similarity index 100% rename from 045_jump_game_ii/jump_game.c rename to 0045_jump_game_ii/jump_game.c diff --git a/045_jump_game_ii/jump_game.cc b/0045_jump_game_ii/jump_game.cc similarity index 100% rename from 045_jump_game_ii/jump_game.cc rename to 0045_jump_game_ii/jump_game.cc diff --git a/046_permutations/Makefile b/0046_permutations/Makefile similarity index 100% rename from 046_permutations/Makefile rename to 0046_permutations/Makefile diff --git a/046_permutations/permutations.c b/0046_permutations/permutations.c similarity index 100% rename from 046_permutations/permutations.c rename to 0046_permutations/permutations.c diff --git a/046_permutations/permutations.cc b/0046_permutations/permutations.cc similarity index 100% rename from 046_permutations/permutations.cc rename to 0046_permutations/permutations.cc diff --git a/047_permutations_ii/Makefile b/0047_permutations_ii/Makefile similarity index 100% rename from 047_permutations_ii/Makefile rename to 0047_permutations_ii/Makefile diff --git a/047_permutations_ii/permutations.c b/0047_permutations_ii/permutations.c similarity index 100% rename from 047_permutations_ii/permutations.c rename to 0047_permutations_ii/permutations.c diff --git a/047_permutations_ii/permutations.cc b/0047_permutations_ii/permutations.cc similarity index 100% rename from 047_permutations_ii/permutations.cc rename to 0047_permutations_ii/permutations.cc diff --git a/048_rotate_image/Makefile b/0048_rotate_image/Makefile similarity index 100% rename from 048_rotate_image/Makefile rename to 0048_rotate_image/Makefile diff --git a/048_rotate_image/rotate.c b/0048_rotate_image/rotate.c similarity index 100% rename from 048_rotate_image/rotate.c rename to 0048_rotate_image/rotate.c diff --git a/048_rotate_image/rotate.cc b/0048_rotate_image/rotate.cc similarity index 100% rename from 048_rotate_image/rotate.cc rename to 0048_rotate_image/rotate.cc diff --git a/049_group_anagrams/Makefile b/0049_group_anagrams/Makefile similarity index 100% rename from 049_group_anagrams/Makefile rename to 0049_group_anagrams/Makefile diff --git a/049_group_anagrams/anagrams.c b/0049_group_anagrams/anagrams.c similarity index 100% rename from 049_group_anagrams/anagrams.c rename to 0049_group_anagrams/anagrams.c diff --git a/049_group_anagrams/anagrams.cc b/0049_group_anagrams/anagrams.cc similarity index 100% rename from 049_group_anagrams/anagrams.cc rename to 0049_group_anagrams/anagrams.cc diff --git a/050_pow/Makefile b/0050_pow/Makefile similarity index 100% rename from 050_pow/Makefile rename to 0050_pow/Makefile diff --git a/050_pow/pow.c b/0050_pow/pow.c similarity index 100% rename from 050_pow/pow.c rename to 0050_pow/pow.c diff --git a/050_pow/pow.cc b/0050_pow/pow.cc similarity index 100% rename from 050_pow/pow.cc rename to 0050_pow/pow.cc diff --git a/051_n_queens/Makefile b/0051_n_queens/Makefile similarity index 100% rename from 051_n_queens/Makefile rename to 0051_n_queens/Makefile diff --git a/051_n_queens/n_queens.c b/0051_n_queens/n_queens.c similarity index 100% rename from 051_n_queens/n_queens.c rename to 0051_n_queens/n_queens.c diff --git a/051_n_queens/n_queens.cc b/0051_n_queens/n_queens.cc similarity index 100% rename from 051_n_queens/n_queens.cc rename to 0051_n_queens/n_queens.cc diff --git a/052_n_queens_ii/Makefile b/0052_n_queens_ii/Makefile similarity index 100% rename from 052_n_queens_ii/Makefile rename to 0052_n_queens_ii/Makefile diff --git a/052_n_queens_ii/n_queens.c b/0052_n_queens_ii/n_queens.c similarity index 100% rename from 052_n_queens_ii/n_queens.c rename to 0052_n_queens_ii/n_queens.c diff --git a/052_n_queens_ii/n_queens.cc b/0052_n_queens_ii/n_queens.cc similarity index 100% rename from 052_n_queens_ii/n_queens.cc rename to 0052_n_queens_ii/n_queens.cc diff --git a/053_maximum_subarray/Makefile b/0053_maximum_subarray/Makefile similarity index 100% rename from 053_maximum_subarray/Makefile rename to 0053_maximum_subarray/Makefile diff --git a/053_maximum_subarray/max_subarray.c b/0053_maximum_subarray/max_subarray.c similarity index 100% rename from 053_maximum_subarray/max_subarray.c rename to 0053_maximum_subarray/max_subarray.c diff --git a/053_maximum_subarray/max_subarray.cc b/0053_maximum_subarray/max_subarray.cc similarity index 100% rename from 053_maximum_subarray/max_subarray.cc rename to 0053_maximum_subarray/max_subarray.cc diff --git a/054_spiral_matrix/Makefile b/0054_spiral_matrix/Makefile similarity index 100% rename from 054_spiral_matrix/Makefile rename to 0054_spiral_matrix/Makefile diff --git a/054_spiral_matrix/spiral_matrix.c b/0054_spiral_matrix/spiral_matrix.c similarity index 100% rename from 054_spiral_matrix/spiral_matrix.c rename to 0054_spiral_matrix/spiral_matrix.c diff --git a/054_spiral_matrix/spiral_matrix.cc b/0054_spiral_matrix/spiral_matrix.cc similarity index 100% rename from 054_spiral_matrix/spiral_matrix.cc rename to 0054_spiral_matrix/spiral_matrix.cc diff --git a/055_jump_game/Makefile b/0055_jump_game/Makefile similarity index 100% rename from 055_jump_game/Makefile rename to 0055_jump_game/Makefile diff --git a/055_jump_game/jump_game.c b/0055_jump_game/jump_game.c similarity index 100% rename from 055_jump_game/jump_game.c rename to 0055_jump_game/jump_game.c diff --git a/056_merge_intervals/Makefile b/0056_merge_intervals/Makefile similarity index 100% rename from 056_merge_intervals/Makefile rename to 0056_merge_intervals/Makefile diff --git a/056_merge_intervals/merge_intervals.c b/0056_merge_intervals/merge_intervals.c similarity index 100% rename from 056_merge_intervals/merge_intervals.c rename to 0056_merge_intervals/merge_intervals.c diff --git a/057_insert_interval/Makefile b/0057_insert_interval/Makefile similarity index 100% rename from 057_insert_interval/Makefile rename to 0057_insert_interval/Makefile diff --git a/057_insert_interval/insert_interval.c b/0057_insert_interval/insert_interval.c similarity index 100% rename from 057_insert_interval/insert_interval.c rename to 0057_insert_interval/insert_interval.c diff --git a/058_length_of_last_word/Makefile b/0058_length_of_last_word/Makefile similarity index 100% rename from 058_length_of_last_word/Makefile rename to 0058_length_of_last_word/Makefile diff --git a/058_length_of_last_word/word_length.c b/0058_length_of_last_word/word_length.c similarity index 100% rename from 058_length_of_last_word/word_length.c rename to 0058_length_of_last_word/word_length.c diff --git a/059_spiral_matrix_ii/Makefile b/0059_spiral_matrix_ii/Makefile similarity index 100% rename from 059_spiral_matrix_ii/Makefile rename to 0059_spiral_matrix_ii/Makefile diff --git a/059_spiral_matrix_ii/spiral_matrix.c b/0059_spiral_matrix_ii/spiral_matrix.c similarity index 100% rename from 059_spiral_matrix_ii/spiral_matrix.c rename to 0059_spiral_matrix_ii/spiral_matrix.c diff --git a/060_permutation_sequence/Makefile b/0060_permutation_sequence/Makefile similarity index 100% rename from 060_permutation_sequence/Makefile rename to 0060_permutation_sequence/Makefile diff --git a/060_permutation_sequence/permutation_sequence.c b/0060_permutation_sequence/permutation_sequence.c similarity index 100% rename from 060_permutation_sequence/permutation_sequence.c rename to 0060_permutation_sequence/permutation_sequence.c diff --git a/061_rotate_list/Makefile b/0061_rotate_list/Makefile similarity index 100% rename from 061_rotate_list/Makefile rename to 0061_rotate_list/Makefile diff --git a/061_rotate_list/rotate_list.c b/0061_rotate_list/rotate_list.c similarity index 100% rename from 061_rotate_list/rotate_list.c rename to 0061_rotate_list/rotate_list.c diff --git a/062_unique_path/Makefile b/0062_unique_path/Makefile similarity index 100% rename from 062_unique_path/Makefile rename to 0062_unique_path/Makefile diff --git a/062_unique_path/unique_path.c b/0062_unique_path/unique_path.c similarity index 100% rename from 062_unique_path/unique_path.c rename to 0062_unique_path/unique_path.c diff --git a/063_unique_paths_ii/Makefile b/0063_unique_paths_ii/Makefile similarity index 100% rename from 063_unique_paths_ii/Makefile rename to 0063_unique_paths_ii/Makefile diff --git a/063_unique_paths_ii/unique_path.c b/0063_unique_paths_ii/unique_path.c similarity index 100% rename from 063_unique_paths_ii/unique_path.c rename to 0063_unique_paths_ii/unique_path.c diff --git a/064_minumum_path_sum/Makefile b/0064_minumum_path_sum/Makefile similarity index 100% rename from 064_minumum_path_sum/Makefile rename to 0064_minumum_path_sum/Makefile diff --git a/064_minumum_path_sum/minimum_path_sum.c b/0064_minumum_path_sum/minimum_path_sum.c similarity index 100% rename from 064_minumum_path_sum/minimum_path_sum.c rename to 0064_minumum_path_sum/minimum_path_sum.c diff --git a/065_valid_number/Makefile b/0065_valid_number/Makefile similarity index 100% rename from 065_valid_number/Makefile rename to 0065_valid_number/Makefile diff --git a/065_valid_number/valid_number.c b/0065_valid_number/valid_number.c similarity index 100% rename from 065_valid_number/valid_number.c rename to 0065_valid_number/valid_number.c diff --git a/066_plus_one/Makefile b/0066_plus_one/Makefile similarity index 100% rename from 066_plus_one/Makefile rename to 0066_plus_one/Makefile diff --git a/066_plus_one/plus_one.c b/0066_plus_one/plus_one.c similarity index 100% rename from 066_plus_one/plus_one.c rename to 0066_plus_one/plus_one.c diff --git a/066_plus_one/plus_one.cc b/0066_plus_one/plus_one.cc similarity index 100% rename from 066_plus_one/plus_one.cc rename to 0066_plus_one/plus_one.cc diff --git a/067_add_binary/Makefile b/0067_add_binary/Makefile similarity index 100% rename from 067_add_binary/Makefile rename to 0067_add_binary/Makefile diff --git a/067_add_binary/add_binary.c b/0067_add_binary/add_binary.c similarity index 100% rename from 067_add_binary/add_binary.c rename to 0067_add_binary/add_binary.c diff --git a/067_add_binary/add_binary.cc b/0067_add_binary/add_binary.cc similarity index 100% rename from 067_add_binary/add_binary.cc rename to 0067_add_binary/add_binary.cc diff --git a/068_text_justification/Makefile b/0068_text_justification/Makefile similarity index 100% rename from 068_text_justification/Makefile rename to 0068_text_justification/Makefile diff --git a/068_text_justification/justification.c b/0068_text_justification/justification.c similarity index 100% rename from 068_text_justification/justification.c rename to 0068_text_justification/justification.c diff --git a/069_sqrt/Makefile b/0069_sqrt/Makefile similarity index 100% rename from 069_sqrt/Makefile rename to 0069_sqrt/Makefile diff --git a/069_sqrt/sqrt.c b/0069_sqrt/sqrt.c similarity index 100% rename from 069_sqrt/sqrt.c rename to 0069_sqrt/sqrt.c diff --git a/070_climbing_stairs/Makefile b/0070_climbing_stairs/Makefile similarity index 100% rename from 070_climbing_stairs/Makefile rename to 0070_climbing_stairs/Makefile diff --git a/070_climbing_stairs/climb_stairs.c b/0070_climbing_stairs/climb_stairs.c similarity index 100% rename from 070_climbing_stairs/climb_stairs.c rename to 0070_climbing_stairs/climb_stairs.c diff --git a/070_climbing_stairs/climb_stairs.cc b/0070_climbing_stairs/climb_stairs.cc similarity index 100% rename from 070_climbing_stairs/climb_stairs.cc rename to 0070_climbing_stairs/climb_stairs.cc diff --git a/071_simplify_path/Makefile b/0071_simplify_path/Makefile similarity index 100% rename from 071_simplify_path/Makefile rename to 0071_simplify_path/Makefile diff --git a/071_simplify_path/simplify_path.c b/0071_simplify_path/simplify_path.c similarity index 100% rename from 071_simplify_path/simplify_path.c rename to 0071_simplify_path/simplify_path.c diff --git a/072_edit_distance/Makefile b/0072_edit_distance/Makefile similarity index 100% rename from 072_edit_distance/Makefile rename to 0072_edit_distance/Makefile diff --git a/072_edit_distance/edit_distance.c b/0072_edit_distance/edit_distance.c similarity index 100% rename from 072_edit_distance/edit_distance.c rename to 0072_edit_distance/edit_distance.c diff --git a/072_edit_distance/edit_distance.cc b/0072_edit_distance/edit_distance.cc similarity index 100% rename from 072_edit_distance/edit_distance.cc rename to 0072_edit_distance/edit_distance.cc diff --git a/073_set_matrix_zeroes/Makefile b/0073_set_matrix_zeroes/Makefile similarity index 100% rename from 073_set_matrix_zeroes/Makefile rename to 0073_set_matrix_zeroes/Makefile diff --git a/073_set_matrix_zeroes/set_zero.c b/0073_set_matrix_zeroes/set_zero.c similarity index 100% rename from 073_set_matrix_zeroes/set_zero.c rename to 0073_set_matrix_zeroes/set_zero.c diff --git a/074_search_a_2d_matrix/Makefile b/0074_search_a_2d_matrix/Makefile similarity index 100% rename from 074_search_a_2d_matrix/Makefile rename to 0074_search_a_2d_matrix/Makefile diff --git a/074_search_a_2d_matrix/matrix_search.c b/0074_search_a_2d_matrix/matrix_search.c similarity index 100% rename from 074_search_a_2d_matrix/matrix_search.c rename to 0074_search_a_2d_matrix/matrix_search.c diff --git a/075_sort_colors/Makefile b/0075_sort_colors/Makefile similarity index 100% rename from 075_sort_colors/Makefile rename to 0075_sort_colors/Makefile diff --git a/075_sort_colors/sort_colors.c b/0075_sort_colors/sort_colors.c similarity index 100% rename from 075_sort_colors/sort_colors.c rename to 0075_sort_colors/sort_colors.c diff --git a/076_minimum_window_substring/Makefile b/0076_minimum_window_substring/Makefile similarity index 100% rename from 076_minimum_window_substring/Makefile rename to 0076_minimum_window_substring/Makefile diff --git a/076_minimum_window_substring/window_substring.c b/0076_minimum_window_substring/window_substring.c similarity index 100% rename from 076_minimum_window_substring/window_substring.c rename to 0076_minimum_window_substring/window_substring.c diff --git a/077_combinations/Makefile b/0077_combinations/Makefile similarity index 100% rename from 077_combinations/Makefile rename to 0077_combinations/Makefile diff --git a/077_combinations/combinations.c b/0077_combinations/combinations.c similarity index 100% rename from 077_combinations/combinations.c rename to 0077_combinations/combinations.c diff --git a/077_combinations/combinations.cc b/0077_combinations/combinations.cc similarity index 100% rename from 077_combinations/combinations.cc rename to 0077_combinations/combinations.cc diff --git a/078_subsets/Makefile b/0078_subsets/Makefile similarity index 100% rename from 078_subsets/Makefile rename to 0078_subsets/Makefile diff --git a/078_subsets/subsets.c b/0078_subsets/subsets.c similarity index 100% rename from 078_subsets/subsets.c rename to 0078_subsets/subsets.c diff --git a/078_subsets/subsets.cc b/0078_subsets/subsets.cc similarity index 100% rename from 078_subsets/subsets.cc rename to 0078_subsets/subsets.cc diff --git a/079_word_search/Makefile b/0079_word_search/Makefile similarity index 100% rename from 079_word_search/Makefile rename to 0079_word_search/Makefile diff --git a/079_word_search/word_search.c b/0079_word_search/word_search.c similarity index 100% rename from 079_word_search/word_search.c rename to 0079_word_search/word_search.c diff --git a/080_remove_duplicates_from_sorted_array_ii/Makefile b/0080_remove_duplicates_from_sorted_array_ii/Makefile similarity index 100% rename from 080_remove_duplicates_from_sorted_array_ii/Makefile rename to 0080_remove_duplicates_from_sorted_array_ii/Makefile diff --git a/080_remove_duplicates_from_sorted_array_ii/rm_dups.c b/0080_remove_duplicates_from_sorted_array_ii/rm_dups.c similarity index 100% rename from 080_remove_duplicates_from_sorted_array_ii/rm_dups.c rename to 0080_remove_duplicates_from_sorted_array_ii/rm_dups.c diff --git a/081_search_in_rotated_sorted_array_ii/Makefile b/0081_search_in_rotated_sorted_array_ii/Makefile similarity index 100% rename from 081_search_in_rotated_sorted_array_ii/Makefile rename to 0081_search_in_rotated_sorted_array_ii/Makefile diff --git a/081_search_in_rotated_sorted_array_ii/search_rotated_array.c b/0081_search_in_rotated_sorted_array_ii/search_rotated_array.c similarity index 100% rename from 081_search_in_rotated_sorted_array_ii/search_rotated_array.c rename to 0081_search_in_rotated_sorted_array_ii/search_rotated_array.c diff --git a/082_remove_duplicates_from_sorted_list_ii/Makefile b/0082_remove_duplicates_from_sorted_list_ii/Makefile similarity index 100% rename from 082_remove_duplicates_from_sorted_list_ii/Makefile rename to 0082_remove_duplicates_from_sorted_list_ii/Makefile diff --git a/082_remove_duplicates_from_sorted_list_ii/rm_dup.c b/0082_remove_duplicates_from_sorted_list_ii/rm_dup.c similarity index 100% rename from 082_remove_duplicates_from_sorted_list_ii/rm_dup.c rename to 0082_remove_duplicates_from_sorted_list_ii/rm_dup.c diff --git a/083_remove_duplicates_from_sorted_list/Makefile b/0083_remove_duplicates_from_sorted_list/Makefile similarity index 100% rename from 083_remove_duplicates_from_sorted_list/Makefile rename to 0083_remove_duplicates_from_sorted_list/Makefile diff --git a/083_remove_duplicates_from_sorted_list/rm_dup.c b/0083_remove_duplicates_from_sorted_list/rm_dup.c similarity index 100% rename from 083_remove_duplicates_from_sorted_list/rm_dup.c rename to 0083_remove_duplicates_from_sorted_list/rm_dup.c diff --git a/083_remove_duplicates_from_sorted_list/rm_dup.cc b/0083_remove_duplicates_from_sorted_list/rm_dup.cc similarity index 100% rename from 083_remove_duplicates_from_sorted_list/rm_dup.cc rename to 0083_remove_duplicates_from_sorted_list/rm_dup.cc diff --git a/084_largest_rectangle_in_histogram/Makefile b/0084_largest_rectangle_in_histogram/Makefile similarity index 100% rename from 084_largest_rectangle_in_histogram/Makefile rename to 0084_largest_rectangle_in_histogram/Makefile diff --git a/084_largest_rectangle_in_histogram/rect_in_histogram.c b/0084_largest_rectangle_in_histogram/rect_in_histogram.c similarity index 100% rename from 084_largest_rectangle_in_histogram/rect_in_histogram.c rename to 0084_largest_rectangle_in_histogram/rect_in_histogram.c diff --git a/085_maximal_rectangle/Makefile b/0085_maximal_rectangle/Makefile similarity index 100% rename from 085_maximal_rectangle/Makefile rename to 0085_maximal_rectangle/Makefile diff --git a/085_maximal_rectangle/maximal_rectangle.c b/0085_maximal_rectangle/maximal_rectangle.c similarity index 100% rename from 085_maximal_rectangle/maximal_rectangle.c rename to 0085_maximal_rectangle/maximal_rectangle.c diff --git a/086_partition_list/Makefile b/0086_partition_list/Makefile similarity index 100% rename from 086_partition_list/Makefile rename to 0086_partition_list/Makefile diff --git a/086_partition_list/partition_list.c b/0086_partition_list/partition_list.c similarity index 100% rename from 086_partition_list/partition_list.c rename to 0086_partition_list/partition_list.c diff --git a/087_scramble_string/Makefile b/0087_scramble_string/Makefile similarity index 100% rename from 087_scramble_string/Makefile rename to 0087_scramble_string/Makefile diff --git a/087_scramble_string/scramble_string.c b/0087_scramble_string/scramble_string.c similarity index 100% rename from 087_scramble_string/scramble_string.c rename to 0087_scramble_string/scramble_string.c diff --git a/088_merge_sorted_array/Makefile b/0088_merge_sorted_array/Makefile similarity index 100% rename from 088_merge_sorted_array/Makefile rename to 0088_merge_sorted_array/Makefile diff --git a/088_merge_sorted_array/merge_array.c b/0088_merge_sorted_array/merge_array.c similarity index 100% rename from 088_merge_sorted_array/merge_array.c rename to 0088_merge_sorted_array/merge_array.c diff --git a/088_merge_sorted_array/merge_array.cc b/0088_merge_sorted_array/merge_array.cc similarity index 100% rename from 088_merge_sorted_array/merge_array.cc rename to 0088_merge_sorted_array/merge_array.cc diff --git a/089_gray_code/Makefile b/0089_gray_code/Makefile similarity index 100% rename from 089_gray_code/Makefile rename to 0089_gray_code/Makefile diff --git a/089_gray_code/gray_code.c b/0089_gray_code/gray_code.c similarity index 100% rename from 089_gray_code/gray_code.c rename to 0089_gray_code/gray_code.c diff --git a/090_subsets_ii/Makefile b/0090_subsets_ii/Makefile similarity index 100% rename from 090_subsets_ii/Makefile rename to 0090_subsets_ii/Makefile diff --git a/090_subsets_ii/subsets.c b/0090_subsets_ii/subsets.c similarity index 100% rename from 090_subsets_ii/subsets.c rename to 0090_subsets_ii/subsets.c diff --git a/090_subsets_ii/subsets.cc b/0090_subsets_ii/subsets.cc similarity index 100% rename from 090_subsets_ii/subsets.cc rename to 0090_subsets_ii/subsets.cc diff --git a/091_decode_ways/Makefile b/0091_decode_ways/Makefile similarity index 100% rename from 091_decode_ways/Makefile rename to 0091_decode_ways/Makefile diff --git a/091_decode_ways/decode_ways.c b/0091_decode_ways/decode_ways.c similarity index 100% rename from 091_decode_ways/decode_ways.c rename to 0091_decode_ways/decode_ways.c diff --git a/092_reverse_linked_list_ii/Makefile b/0092_reverse_linked_list_ii/Makefile similarity index 100% rename from 092_reverse_linked_list_ii/Makefile rename to 0092_reverse_linked_list_ii/Makefile diff --git a/092_reverse_linked_list_ii/reverse_list.c b/0092_reverse_linked_list_ii/reverse_list.c similarity index 100% rename from 092_reverse_linked_list_ii/reverse_list.c rename to 0092_reverse_linked_list_ii/reverse_list.c diff --git a/093_restore_ip_addresses/Makefile b/0093_restore_ip_addresses/Makefile similarity index 100% rename from 093_restore_ip_addresses/Makefile rename to 0093_restore_ip_addresses/Makefile diff --git a/093_restore_ip_addresses/ip_addr.c b/0093_restore_ip_addresses/ip_addr.c similarity index 100% rename from 093_restore_ip_addresses/ip_addr.c rename to 0093_restore_ip_addresses/ip_addr.c diff --git a/094_binary_tree_inorder_traversal/Makefile b/0094_binary_tree_inorder_traversal/Makefile similarity index 100% rename from 094_binary_tree_inorder_traversal/Makefile rename to 0094_binary_tree_inorder_traversal/Makefile diff --git a/094_binary_tree_inorder_traversal/bst_inorder_traversal.c b/0094_binary_tree_inorder_traversal/bst_inorder_traversal.c similarity index 100% rename from 094_binary_tree_inorder_traversal/bst_inorder_traversal.c rename to 0094_binary_tree_inorder_traversal/bst_inorder_traversal.c diff --git a/095_unique_binary_search_trees_ii/Makefile b/0095_unique_binary_search_trees_ii/Makefile similarity index 100% rename from 095_unique_binary_search_trees_ii/Makefile rename to 0095_unique_binary_search_trees_ii/Makefile diff --git a/095_unique_binary_search_trees_ii/unique_bst.c b/0095_unique_binary_search_trees_ii/unique_bst.c similarity index 100% rename from 095_unique_binary_search_trees_ii/unique_bst.c rename to 0095_unique_binary_search_trees_ii/unique_bst.c diff --git a/096_unique_binary_search_trees/Makefile b/0096_unique_binary_search_trees/Makefile similarity index 100% rename from 096_unique_binary_search_trees/Makefile rename to 0096_unique_binary_search_trees/Makefile diff --git a/096_unique_binary_search_trees/unique_bst.c b/0096_unique_binary_search_trees/unique_bst.c similarity index 100% rename from 096_unique_binary_search_trees/unique_bst.c rename to 0096_unique_binary_search_trees/unique_bst.c diff --git a/097_interleaving_string/Makefile b/0097_interleaving_string/Makefile similarity index 100% rename from 097_interleaving_string/Makefile rename to 0097_interleaving_string/Makefile diff --git a/097_interleaving_string/interleaving_string.c b/0097_interleaving_string/interleaving_string.c similarity index 100% rename from 097_interleaving_string/interleaving_string.c rename to 0097_interleaving_string/interleaving_string.c diff --git a/098_validate_binary_search_tree/Makefile b/0098_validate_binary_search_tree/Makefile similarity index 100% rename from 098_validate_binary_search_tree/Makefile rename to 0098_validate_binary_search_tree/Makefile diff --git a/098_validate_binary_search_tree/valid_bst.c b/0098_validate_binary_search_tree/valid_bst.c similarity index 100% rename from 098_validate_binary_search_tree/valid_bst.c rename to 0098_validate_binary_search_tree/valid_bst.c diff --git a/098_validate_binary_search_tree/valid_bst.cc b/0098_validate_binary_search_tree/valid_bst.cc similarity index 100% rename from 098_validate_binary_search_tree/valid_bst.cc rename to 0098_validate_binary_search_tree/valid_bst.cc diff --git a/099_recover_binary_search_tree/Makefile b/0099_recover_binary_search_tree/Makefile similarity index 100% rename from 099_recover_binary_search_tree/Makefile rename to 0099_recover_binary_search_tree/Makefile diff --git a/099_recover_binary_search_tree/recover_bst.c b/0099_recover_binary_search_tree/recover_bst.c similarity index 100% rename from 099_recover_binary_search_tree/recover_bst.c rename to 0099_recover_binary_search_tree/recover_bst.c diff --git a/100_same_tree/Makefile b/0100_same_tree/Makefile similarity index 100% rename from 100_same_tree/Makefile rename to 0100_same_tree/Makefile diff --git a/100_same_tree/same_tree.c b/0100_same_tree/same_tree.c similarity index 100% rename from 100_same_tree/same_tree.c rename to 0100_same_tree/same_tree.c diff --git a/100_same_tree/same_tree.cc b/0100_same_tree/same_tree.cc similarity index 100% rename from 100_same_tree/same_tree.cc rename to 0100_same_tree/same_tree.cc diff --git a/101_symmetric_tree/Makefile b/0101_symmetric_tree/Makefile similarity index 100% rename from 101_symmetric_tree/Makefile rename to 0101_symmetric_tree/Makefile diff --git a/101_symmetric_tree/symmetric_tree.c b/0101_symmetric_tree/symmetric_tree.c similarity index 100% rename from 101_symmetric_tree/symmetric_tree.c rename to 0101_symmetric_tree/symmetric_tree.c diff --git a/101_symmetric_tree/symmetric_tree.cc b/0101_symmetric_tree/symmetric_tree.cc similarity index 100% rename from 101_symmetric_tree/symmetric_tree.cc rename to 0101_symmetric_tree/symmetric_tree.cc diff --git a/102_binary_tree_level_order_traversal/Makefile b/0102_binary_tree_level_order_traversal/Makefile similarity index 100% rename from 102_binary_tree_level_order_traversal/Makefile rename to 0102_binary_tree_level_order_traversal/Makefile diff --git a/102_binary_tree_level_order_traversal/bst_bfs.c b/0102_binary_tree_level_order_traversal/bst_bfs.c similarity index 100% rename from 102_binary_tree_level_order_traversal/bst_bfs.c rename to 0102_binary_tree_level_order_traversal/bst_bfs.c diff --git a/102_binary_tree_level_order_traversal/bst_bfs.cc b/0102_binary_tree_level_order_traversal/bst_bfs.cc similarity index 100% rename from 102_binary_tree_level_order_traversal/bst_bfs.cc rename to 0102_binary_tree_level_order_traversal/bst_bfs.cc diff --git a/103_binary_tree_zigzag_level_order_traversal/Makefile b/0103_binary_tree_zigzag_level_order_traversal/Makefile similarity index 100% rename from 103_binary_tree_zigzag_level_order_traversal/Makefile rename to 0103_binary_tree_zigzag_level_order_traversal/Makefile diff --git a/103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c b/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c similarity index 100% rename from 103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c rename to 0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c diff --git a/104_maximum_depth_of_binary_tree/Makefile b/0104_maximum_depth_of_binary_tree/Makefile similarity index 100% rename from 104_maximum_depth_of_binary_tree/Makefile rename to 0104_maximum_depth_of_binary_tree/Makefile diff --git a/104_maximum_depth_of_binary_tree/bst_depth.c b/0104_maximum_depth_of_binary_tree/bst_depth.c similarity index 100% rename from 104_maximum_depth_of_binary_tree/bst_depth.c rename to 0104_maximum_depth_of_binary_tree/bst_depth.c diff --git a/104_maximum_depth_of_binary_tree/bst_depth.cc b/0104_maximum_depth_of_binary_tree/bst_depth.cc similarity index 100% rename from 104_maximum_depth_of_binary_tree/bst_depth.cc rename to 0104_maximum_depth_of_binary_tree/bst_depth.cc diff --git a/105_construct_binary_tree_from_preorder_and_inorder_traversal/Makefile b/0105_construct_binary_tree_from_preorder_and_inorder_traversal/Makefile similarity index 100% rename from 105_construct_binary_tree_from_preorder_and_inorder_traversal/Makefile rename to 0105_construct_binary_tree_from_preorder_and_inorder_traversal/Makefile diff --git a/105_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 similarity index 100% rename from 105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c rename to 0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.c diff --git a/106_construct_binary_tree_from_inorder_and_postorder_traversal/Makefile b/0106_construct_binary_tree_from_inorder_and_postorder_traversal/Makefile similarity index 100% rename from 106_construct_binary_tree_from_inorder_and_postorder_traversal/Makefile rename to 0106_construct_binary_tree_from_inorder_and_postorder_traversal/Makefile diff --git a/106_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 similarity index 100% rename from 106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c rename to 0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.c diff --git a/107_binary_tree_level_order_traversal_ii/Makefile b/0107_binary_tree_level_order_traversal_ii/Makefile similarity index 100% rename from 107_binary_tree_level_order_traversal_ii/Makefile rename to 0107_binary_tree_level_order_traversal_ii/Makefile diff --git a/107_binary_tree_level_order_traversal_ii/bst_bfs.c b/0107_binary_tree_level_order_traversal_ii/bst_bfs.c similarity index 100% rename from 107_binary_tree_level_order_traversal_ii/bst_bfs.c rename to 0107_binary_tree_level_order_traversal_ii/bst_bfs.c diff --git a/107_binary_tree_level_order_traversal_ii/bst_bfs.cc b/0107_binary_tree_level_order_traversal_ii/bst_bfs.cc similarity index 100% rename from 107_binary_tree_level_order_traversal_ii/bst_bfs.cc rename to 0107_binary_tree_level_order_traversal_ii/bst_bfs.cc diff --git a/108_convert_sorted_array_to_binary_search_tree/Makefile b/0108_convert_sorted_array_to_binary_search_tree/Makefile similarity index 100% rename from 108_convert_sorted_array_to_binary_search_tree/Makefile rename to 0108_convert_sorted_array_to_binary_search_tree/Makefile diff --git a/108_convert_sorted_array_to_binary_search_tree/bst_convert.c b/0108_convert_sorted_array_to_binary_search_tree/bst_convert.c similarity index 100% rename from 108_convert_sorted_array_to_binary_search_tree/bst_convert.c rename to 0108_convert_sorted_array_to_binary_search_tree/bst_convert.c diff --git a/108_convert_sorted_array_to_binary_search_tree/bst_convert.cc b/0108_convert_sorted_array_to_binary_search_tree/bst_convert.cc similarity index 100% rename from 108_convert_sorted_array_to_binary_search_tree/bst_convert.cc rename to 0108_convert_sorted_array_to_binary_search_tree/bst_convert.cc diff --git a/109_convert_sorted_list_to_binary_search_tree/Makefile b/0109_convert_sorted_list_to_binary_search_tree/Makefile similarity index 100% rename from 109_convert_sorted_list_to_binary_search_tree/Makefile rename to 0109_convert_sorted_list_to_binary_search_tree/Makefile diff --git a/109_convert_sorted_list_to_binary_search_tree/bst_convert.c b/0109_convert_sorted_list_to_binary_search_tree/bst_convert.c similarity index 100% rename from 109_convert_sorted_list_to_binary_search_tree/bst_convert.c rename to 0109_convert_sorted_list_to_binary_search_tree/bst_convert.c diff --git a/110_balanced_binary_tree/Makefile b/0110_balanced_binary_tree/Makefile similarity index 100% rename from 110_balanced_binary_tree/Makefile rename to 0110_balanced_binary_tree/Makefile diff --git a/110_balanced_binary_tree/balanced_bst.c b/0110_balanced_binary_tree/balanced_bst.c similarity index 100% rename from 110_balanced_binary_tree/balanced_bst.c rename to 0110_balanced_binary_tree/balanced_bst.c diff --git a/110_balanced_binary_tree/balanced_bst.cc b/0110_balanced_binary_tree/balanced_bst.cc similarity index 100% rename from 110_balanced_binary_tree/balanced_bst.cc rename to 0110_balanced_binary_tree/balanced_bst.cc diff --git a/111_minimum_depth_of_binary_tree/Makefile b/0111_minimum_depth_of_binary_tree/Makefile similarity index 100% rename from 111_minimum_depth_of_binary_tree/Makefile rename to 0111_minimum_depth_of_binary_tree/Makefile diff --git a/111_minimum_depth_of_binary_tree/bst_depth.c b/0111_minimum_depth_of_binary_tree/bst_depth.c similarity index 100% rename from 111_minimum_depth_of_binary_tree/bst_depth.c rename to 0111_minimum_depth_of_binary_tree/bst_depth.c diff --git a/111_minimum_depth_of_binary_tree/bst_depth.cc b/0111_minimum_depth_of_binary_tree/bst_depth.cc similarity index 100% rename from 111_minimum_depth_of_binary_tree/bst_depth.cc rename to 0111_minimum_depth_of_binary_tree/bst_depth.cc diff --git a/112_path_sum/Makefile b/0112_path_sum/Makefile similarity index 100% rename from 112_path_sum/Makefile rename to 0112_path_sum/Makefile diff --git a/112_path_sum/path_sum.c b/0112_path_sum/path_sum.c similarity index 100% rename from 112_path_sum/path_sum.c rename to 0112_path_sum/path_sum.c diff --git a/112_path_sum/path_sum.cc b/0112_path_sum/path_sum.cc similarity index 100% rename from 112_path_sum/path_sum.cc rename to 0112_path_sum/path_sum.cc diff --git a/113_path_sum_ii/Makefile b/0113_path_sum_ii/Makefile similarity index 100% rename from 113_path_sum_ii/Makefile rename to 0113_path_sum_ii/Makefile diff --git a/113_path_sum_ii/path_sum.c b/0113_path_sum_ii/path_sum.c similarity index 100% rename from 113_path_sum_ii/path_sum.c rename to 0113_path_sum_ii/path_sum.c diff --git a/114_flatten_binary_tree_to_linked_list/Makefile b/0114_flatten_binary_tree_to_linked_list/Makefile similarity index 100% rename from 114_flatten_binary_tree_to_linked_list/Makefile rename to 0114_flatten_binary_tree_to_linked_list/Makefile diff --git a/114_flatten_binary_tree_to_linked_list/flatten.c b/0114_flatten_binary_tree_to_linked_list/flatten.c similarity index 100% rename from 114_flatten_binary_tree_to_linked_list/flatten.c rename to 0114_flatten_binary_tree_to_linked_list/flatten.c diff --git a/115_distinct_subsequences/Makefile b/0115_distinct_subsequences/Makefile similarity index 100% rename from 115_distinct_subsequences/Makefile rename to 0115_distinct_subsequences/Makefile diff --git a/115_distinct_subsequences/distinct_subseq.c b/0115_distinct_subsequences/distinct_subseq.c similarity index 100% rename from 115_distinct_subsequences/distinct_subseq.c rename to 0115_distinct_subsequences/distinct_subseq.c diff --git a/116_populating_next_right_pointers_in_each_node/Makefile b/0116_populating_next_right_pointers_in_each_node/Makefile similarity index 100% rename from 116_populating_next_right_pointers_in_each_node/Makefile rename to 0116_populating_next_right_pointers_in_each_node/Makefile diff --git a/116_populating_next_right_pointers_in_each_node/connect.c b/0116_populating_next_right_pointers_in_each_node/connect.c similarity index 100% rename from 116_populating_next_right_pointers_in_each_node/connect.c rename to 0116_populating_next_right_pointers_in_each_node/connect.c diff --git a/117_populating_next_right_pointers_in_each_node_ii/Makefile b/0117_populating_next_right_pointers_in_each_node_ii/Makefile similarity index 100% rename from 117_populating_next_right_pointers_in_each_node_ii/Makefile rename to 0117_populating_next_right_pointers_in_each_node_ii/Makefile diff --git a/117_populating_next_right_pointers_in_each_node_ii/connect.c b/0117_populating_next_right_pointers_in_each_node_ii/connect.c similarity index 100% rename from 117_populating_next_right_pointers_in_each_node_ii/connect.c rename to 0117_populating_next_right_pointers_in_each_node_ii/connect.c diff --git a/118_pascal_triangle/Makefile b/0118_pascal_triangle/Makefile similarity index 100% rename from 118_pascal_triangle/Makefile rename to 0118_pascal_triangle/Makefile diff --git a/118_pascal_triangle/pascal_triangle.c b/0118_pascal_triangle/pascal_triangle.c similarity index 100% rename from 118_pascal_triangle/pascal_triangle.c rename to 0118_pascal_triangle/pascal_triangle.c diff --git a/119_pascal_triangle_ii/Makefile b/0119_pascal_triangle_ii/Makefile similarity index 100% rename from 119_pascal_triangle_ii/Makefile rename to 0119_pascal_triangle_ii/Makefile diff --git a/119_pascal_triangle_ii/pascal_triangle.c b/0119_pascal_triangle_ii/pascal_triangle.c similarity index 100% rename from 119_pascal_triangle_ii/pascal_triangle.c rename to 0119_pascal_triangle_ii/pascal_triangle.c diff --git a/120_triangle/Makefile b/0120_triangle/Makefile similarity index 100% rename from 120_triangle/Makefile rename to 0120_triangle/Makefile diff --git a/120_triangle/triangle.c b/0120_triangle/triangle.c similarity index 100% rename from 120_triangle/triangle.c rename to 0120_triangle/triangle.c diff --git a/121_best_time_to_buy_and_sell_stock/Makefile b/0121_best_time_to_buy_and_sell_stock/Makefile similarity index 100% rename from 121_best_time_to_buy_and_sell_stock/Makefile rename to 0121_best_time_to_buy_and_sell_stock/Makefile diff --git a/121_best_time_to_buy_and_sell_stock/stock.c b/0121_best_time_to_buy_and_sell_stock/stock.c similarity index 100% rename from 121_best_time_to_buy_and_sell_stock/stock.c rename to 0121_best_time_to_buy_and_sell_stock/stock.c diff --git a/121_best_time_to_buy_and_sell_stock/stock.cc b/0121_best_time_to_buy_and_sell_stock/stock.cc similarity index 100% rename from 121_best_time_to_buy_and_sell_stock/stock.cc rename to 0121_best_time_to_buy_and_sell_stock/stock.cc diff --git a/122_best_time_to_buy_and_sell_stock_ii/Makefile b/0122_best_time_to_buy_and_sell_stock_ii/Makefile similarity index 100% rename from 122_best_time_to_buy_and_sell_stock_ii/Makefile rename to 0122_best_time_to_buy_and_sell_stock_ii/Makefile diff --git a/122_best_time_to_buy_and_sell_stock_ii/stock.c b/0122_best_time_to_buy_and_sell_stock_ii/stock.c similarity index 100% rename from 122_best_time_to_buy_and_sell_stock_ii/stock.c rename to 0122_best_time_to_buy_and_sell_stock_ii/stock.c diff --git a/122_best_time_to_buy_and_sell_stock_ii/stock.cc b/0122_best_time_to_buy_and_sell_stock_ii/stock.cc similarity index 100% rename from 122_best_time_to_buy_and_sell_stock_ii/stock.cc rename to 0122_best_time_to_buy_and_sell_stock_ii/stock.cc diff --git a/123_best_time_to_buy_and_sell_stock_iii/Makefile b/0123_best_time_to_buy_and_sell_stock_iii/Makefile similarity index 100% rename from 123_best_time_to_buy_and_sell_stock_iii/Makefile rename to 0123_best_time_to_buy_and_sell_stock_iii/Makefile diff --git a/123_best_time_to_buy_and_sell_stock_iii/stock.c b/0123_best_time_to_buy_and_sell_stock_iii/stock.c similarity index 100% rename from 123_best_time_to_buy_and_sell_stock_iii/stock.c rename to 0123_best_time_to_buy_and_sell_stock_iii/stock.c diff --git a/124_binary_tree_maximum_path_sum/Makefile b/0124_binary_tree_maximum_path_sum/Makefile similarity index 100% rename from 124_binary_tree_maximum_path_sum/Makefile rename to 0124_binary_tree_maximum_path_sum/Makefile diff --git a/124_binary_tree_maximum_path_sum/bst_max_path.c b/0124_binary_tree_maximum_path_sum/bst_max_path.c similarity index 100% rename from 124_binary_tree_maximum_path_sum/bst_max_path.c rename to 0124_binary_tree_maximum_path_sum/bst_max_path.c diff --git a/124_binary_tree_maximum_path_sum/bst_max_path.cc b/0124_binary_tree_maximum_path_sum/bst_max_path.cc similarity index 100% rename from 124_binary_tree_maximum_path_sum/bst_max_path.cc rename to 0124_binary_tree_maximum_path_sum/bst_max_path.cc diff --git a/125_valid_palindrome/Makefile b/0125_valid_palindrome/Makefile similarity index 100% rename from 125_valid_palindrome/Makefile rename to 0125_valid_palindrome/Makefile diff --git a/125_valid_palindrome/valid_palindrome.c b/0125_valid_palindrome/valid_palindrome.c similarity index 100% rename from 125_valid_palindrome/valid_palindrome.c rename to 0125_valid_palindrome/valid_palindrome.c diff --git a/126_word_ladder_ii/Makefile b/0126_word_ladder_ii/Makefile similarity index 100% rename from 126_word_ladder_ii/Makefile rename to 0126_word_ladder_ii/Makefile diff --git a/126_word_ladder_ii/word_ladder.c b/0126_word_ladder_ii/word_ladder.c similarity index 100% rename from 126_word_ladder_ii/word_ladder.c rename to 0126_word_ladder_ii/word_ladder.c diff --git a/127_word_ladder/Makefile b/0127_word_ladder/Makefile similarity index 100% rename from 127_word_ladder/Makefile rename to 0127_word_ladder/Makefile diff --git a/127_word_ladder/word_ladder.c b/0127_word_ladder/word_ladder.c similarity index 100% rename from 127_word_ladder/word_ladder.c rename to 0127_word_ladder/word_ladder.c diff --git a/128_longest_consecutive_sequence/Makefile b/0128_longest_consecutive_sequence/Makefile similarity index 100% rename from 128_longest_consecutive_sequence/Makefile rename to 0128_longest_consecutive_sequence/Makefile diff --git a/128_longest_consecutive_sequence/consec_seq.c b/0128_longest_consecutive_sequence/consec_seq.c similarity index 100% rename from 128_longest_consecutive_sequence/consec_seq.c rename to 0128_longest_consecutive_sequence/consec_seq.c diff --git a/129_sum_root_to_leaf_numbers/Makefile b/0129_sum_root_to_leaf_numbers/Makefile similarity index 100% rename from 129_sum_root_to_leaf_numbers/Makefile rename to 0129_sum_root_to_leaf_numbers/Makefile diff --git a/129_sum_root_to_leaf_numbers/sum_tree.c b/0129_sum_root_to_leaf_numbers/sum_tree.c similarity index 100% rename from 129_sum_root_to_leaf_numbers/sum_tree.c rename to 0129_sum_root_to_leaf_numbers/sum_tree.c diff --git a/130_surrounded_regions/Makefile b/0130_surrounded_regions/Makefile similarity index 100% rename from 130_surrounded_regions/Makefile rename to 0130_surrounded_regions/Makefile diff --git a/130_surrounded_regions/surrounded_regions.c b/0130_surrounded_regions/surrounded_regions.c similarity index 100% rename from 130_surrounded_regions/surrounded_regions.c rename to 0130_surrounded_regions/surrounded_regions.c diff --git a/131_palindrome_patitioning/Makefile b/0131_palindrome_patitioning/Makefile similarity index 100% rename from 131_palindrome_patitioning/Makefile rename to 0131_palindrome_patitioning/Makefile diff --git a/131_palindrome_patitioning/palindrome_partition.c b/0131_palindrome_patitioning/palindrome_partition.c similarity index 100% rename from 131_palindrome_patitioning/palindrome_partition.c rename to 0131_palindrome_patitioning/palindrome_partition.c diff --git a/132_palindrome_patitioning_ii/Makefile b/0132_palindrome_patitioning_ii/Makefile similarity index 100% rename from 132_palindrome_patitioning_ii/Makefile rename to 0132_palindrome_patitioning_ii/Makefile diff --git a/132_palindrome_patitioning_ii/palindrome_partition.c b/0132_palindrome_patitioning_ii/palindrome_partition.c similarity index 100% rename from 132_palindrome_patitioning_ii/palindrome_partition.c rename to 0132_palindrome_patitioning_ii/palindrome_partition.c diff --git a/133_clone_graph/Makefile b/0133_clone_graph/Makefile similarity index 100% rename from 133_clone_graph/Makefile rename to 0133_clone_graph/Makefile diff --git a/133_clone_graph/clone_graph.c b/0133_clone_graph/clone_graph.c similarity index 100% rename from 133_clone_graph/clone_graph.c rename to 0133_clone_graph/clone_graph.c diff --git a/134_gas_station/Makefile b/0134_gas_station/Makefile similarity index 100% rename from 134_gas_station/Makefile rename to 0134_gas_station/Makefile diff --git a/134_gas_station/gas_station.c b/0134_gas_station/gas_station.c similarity index 100% rename from 134_gas_station/gas_station.c rename to 0134_gas_station/gas_station.c diff --git a/135_candy/Makefile b/0135_candy/Makefile similarity index 100% rename from 135_candy/Makefile rename to 0135_candy/Makefile diff --git a/135_candy/candy.c b/0135_candy/candy.c similarity index 100% rename from 135_candy/candy.c rename to 0135_candy/candy.c diff --git a/136_single_number/Makefile b/0136_single_number/Makefile similarity index 100% rename from 136_single_number/Makefile rename to 0136_single_number/Makefile diff --git a/136_single_number/single_number.c b/0136_single_number/single_number.c similarity index 100% rename from 136_single_number/single_number.c rename to 0136_single_number/single_number.c diff --git a/136_single_number/single_number.cc b/0136_single_number/single_number.cc similarity index 100% rename from 136_single_number/single_number.cc rename to 0136_single_number/single_number.cc diff --git a/137_single_number_ii/Makefile b/0137_single_number_ii/Makefile similarity index 100% rename from 137_single_number_ii/Makefile rename to 0137_single_number_ii/Makefile diff --git a/137_single_number_ii/single_number.c b/0137_single_number_ii/single_number.c similarity index 100% rename from 137_single_number_ii/single_number.c rename to 0137_single_number_ii/single_number.c diff --git a/138_copy_list_with_random_pointer/Makefile b/0138_copy_list_with_random_pointer/Makefile similarity index 100% rename from 138_copy_list_with_random_pointer/Makefile rename to 0138_copy_list_with_random_pointer/Makefile diff --git a/138_copy_list_with_random_pointer/copy_list.c b/0138_copy_list_with_random_pointer/copy_list.c similarity index 100% rename from 138_copy_list_with_random_pointer/copy_list.c rename to 0138_copy_list_with_random_pointer/copy_list.c diff --git a/138_copy_list_with_random_pointer/copy_list.cc b/0138_copy_list_with_random_pointer/copy_list.cc similarity index 100% rename from 138_copy_list_with_random_pointer/copy_list.cc rename to 0138_copy_list_with_random_pointer/copy_list.cc diff --git a/139_word_break/Makefile b/0139_word_break/Makefile similarity index 100% rename from 139_word_break/Makefile rename to 0139_word_break/Makefile diff --git a/139_word_break/word_break.c b/0139_word_break/word_break.c similarity index 100% rename from 139_word_break/word_break.c rename to 0139_word_break/word_break.c diff --git a/140_word_break_ii/Makefile b/0140_word_break_ii/Makefile similarity index 100% rename from 140_word_break_ii/Makefile rename to 0140_word_break_ii/Makefile diff --git a/140_word_break_ii/word_break.c b/0140_word_break_ii/word_break.c similarity index 100% rename from 140_word_break_ii/word_break.c rename to 0140_word_break_ii/word_break.c diff --git a/141_linked_list_cycle/Makefile b/0141_linked_list_cycle/Makefile similarity index 100% rename from 141_linked_list_cycle/Makefile rename to 0141_linked_list_cycle/Makefile diff --git a/141_linked_list_cycle/list_cycle.c b/0141_linked_list_cycle/list_cycle.c similarity index 100% rename from 141_linked_list_cycle/list_cycle.c rename to 0141_linked_list_cycle/list_cycle.c diff --git a/141_linked_list_cycle/list_cycle.cc b/0141_linked_list_cycle/list_cycle.cc similarity index 100% rename from 141_linked_list_cycle/list_cycle.cc rename to 0141_linked_list_cycle/list_cycle.cc diff --git a/142_linked_list_cycle_ii/Makefile b/0142_linked_list_cycle_ii/Makefile similarity index 100% rename from 142_linked_list_cycle_ii/Makefile rename to 0142_linked_list_cycle_ii/Makefile diff --git a/142_linked_list_cycle_ii/list_cycle.c b/0142_linked_list_cycle_ii/list_cycle.c similarity index 100% rename from 142_linked_list_cycle_ii/list_cycle.c rename to 0142_linked_list_cycle_ii/list_cycle.c diff --git a/142_linked_list_cycle_ii/list_cycle.cc b/0142_linked_list_cycle_ii/list_cycle.cc similarity index 100% rename from 142_linked_list_cycle_ii/list_cycle.cc rename to 0142_linked_list_cycle_ii/list_cycle.cc diff --git a/143_reorder_list/Makefile b/0143_reorder_list/Makefile similarity index 100% rename from 143_reorder_list/Makefile rename to 0143_reorder_list/Makefile diff --git a/143_reorder_list/reorder_list.c b/0143_reorder_list/reorder_list.c similarity index 100% rename from 143_reorder_list/reorder_list.c rename to 0143_reorder_list/reorder_list.c diff --git a/144_binary_tree_preorder_traversal/Makefile b/0144_binary_tree_preorder_traversal/Makefile similarity index 100% rename from 144_binary_tree_preorder_traversal/Makefile rename to 0144_binary_tree_preorder_traversal/Makefile diff --git a/144_binary_tree_preorder_traversal/bst_preorder.c b/0144_binary_tree_preorder_traversal/bst_preorder.c similarity index 100% rename from 144_binary_tree_preorder_traversal/bst_preorder.c rename to 0144_binary_tree_preorder_traversal/bst_preorder.c diff --git a/144_binary_tree_preorder_traversal/bst_preorder.cc b/0144_binary_tree_preorder_traversal/bst_preorder.cc similarity index 100% rename from 144_binary_tree_preorder_traversal/bst_preorder.cc rename to 0144_binary_tree_preorder_traversal/bst_preorder.cc diff --git a/145_binary_tree_postorder_traversal/Makefile b/0145_binary_tree_postorder_traversal/Makefile similarity index 100% rename from 145_binary_tree_postorder_traversal/Makefile rename to 0145_binary_tree_postorder_traversal/Makefile diff --git a/145_binary_tree_postorder_traversal/bst_postorder.c b/0145_binary_tree_postorder_traversal/bst_postorder.c similarity index 100% rename from 145_binary_tree_postorder_traversal/bst_postorder.c rename to 0145_binary_tree_postorder_traversal/bst_postorder.c diff --git a/145_binary_tree_postorder_traversal/bst_postorder.cc b/0145_binary_tree_postorder_traversal/bst_postorder.cc similarity index 100% rename from 145_binary_tree_postorder_traversal/bst_postorder.cc rename to 0145_binary_tree_postorder_traversal/bst_postorder.cc diff --git a/146_lru_cache/Makefile b/0146_lru_cache/Makefile similarity index 100% rename from 146_lru_cache/Makefile rename to 0146_lru_cache/Makefile diff --git a/146_lru_cache/lru_cache.c b/0146_lru_cache/lru_cache.c similarity index 100% rename from 146_lru_cache/lru_cache.c rename to 0146_lru_cache/lru_cache.c diff --git a/146_lru_cache/lru_cache.cc b/0146_lru_cache/lru_cache.cc similarity index 100% rename from 146_lru_cache/lru_cache.cc rename to 0146_lru_cache/lru_cache.cc diff --git a/147_insertion_sort_list/Makefile b/0147_insertion_sort_list/Makefile similarity index 100% rename from 147_insertion_sort_list/Makefile rename to 0147_insertion_sort_list/Makefile diff --git a/147_insertion_sort_list/insert_sort_list.c b/0147_insertion_sort_list/insert_sort_list.c similarity index 100% rename from 147_insertion_sort_list/insert_sort_list.c rename to 0147_insertion_sort_list/insert_sort_list.c diff --git a/148_sort_list/Makefile b/0148_sort_list/Makefile similarity index 100% rename from 148_sort_list/Makefile rename to 0148_sort_list/Makefile diff --git a/148_sort_list/sort_list.c b/0148_sort_list/sort_list.c similarity index 100% rename from 148_sort_list/sort_list.c rename to 0148_sort_list/sort_list.c diff --git a/149_max_points_on_a_line/Makefile b/0149_max_points_on_a_line/Makefile similarity index 100% rename from 149_max_points_on_a_line/Makefile rename to 0149_max_points_on_a_line/Makefile diff --git a/149_max_points_on_a_line/points_on_line.c b/0149_max_points_on_a_line/points_on_line.c similarity index 100% rename from 149_max_points_on_a_line/points_on_line.c rename to 0149_max_points_on_a_line/points_on_line.c diff --git a/150_evaluate_reverse_polish_notation/Makefile b/0150_evaluate_reverse_polish_notation/Makefile similarity index 100% rename from 150_evaluate_reverse_polish_notation/Makefile rename to 0150_evaluate_reverse_polish_notation/Makefile diff --git a/150_evaluate_reverse_polish_notation/eval_rpn.c b/0150_evaluate_reverse_polish_notation/eval_rpn.c similarity index 100% rename from 150_evaluate_reverse_polish_notation/eval_rpn.c rename to 0150_evaluate_reverse_polish_notation/eval_rpn.c diff --git a/151_reverse_words_in_a_string/Makefile b/0151_reverse_words_in_a_string/Makefile similarity index 100% rename from 151_reverse_words_in_a_string/Makefile rename to 0151_reverse_words_in_a_string/Makefile diff --git a/151_reverse_words_in_a_string/reverse.c b/0151_reverse_words_in_a_string/reverse.c similarity index 100% rename from 151_reverse_words_in_a_string/reverse.c rename to 0151_reverse_words_in_a_string/reverse.c diff --git a/152_maximum_product_subarray/Makefile b/0152_maximum_product_subarray/Makefile similarity index 100% rename from 152_maximum_product_subarray/Makefile rename to 0152_maximum_product_subarray/Makefile diff --git a/152_maximum_product_subarray/subarray.c b/0152_maximum_product_subarray/subarray.c similarity index 100% rename from 152_maximum_product_subarray/subarray.c rename to 0152_maximum_product_subarray/subarray.c diff --git a/153_find_minimum_in_rotated_sorted_array/Makefile b/0153_find_minimum_in_rotated_sorted_array/Makefile similarity index 100% rename from 153_find_minimum_in_rotated_sorted_array/Makefile rename to 0153_find_minimum_in_rotated_sorted_array/Makefile diff --git a/153_find_minimum_in_rotated_sorted_array/minimum.c b/0153_find_minimum_in_rotated_sorted_array/minimum.c similarity index 100% rename from 153_find_minimum_in_rotated_sorted_array/minimum.c rename to 0153_find_minimum_in_rotated_sorted_array/minimum.c diff --git a/154_find_minimum_in_rotated_sorted_array_ii/Makefile b/0154_find_minimum_in_rotated_sorted_array_ii/Makefile similarity index 100% rename from 154_find_minimum_in_rotated_sorted_array_ii/Makefile rename to 0154_find_minimum_in_rotated_sorted_array_ii/Makefile diff --git a/154_find_minimum_in_rotated_sorted_array_ii/minimum.c b/0154_find_minimum_in_rotated_sorted_array_ii/minimum.c similarity index 100% rename from 154_find_minimum_in_rotated_sorted_array_ii/minimum.c rename to 0154_find_minimum_in_rotated_sorted_array_ii/minimum.c diff --git a/155_min_stack/Makefile b/0155_min_stack/Makefile similarity index 100% rename from 155_min_stack/Makefile rename to 0155_min_stack/Makefile diff --git a/155_min_stack/stack.c b/0155_min_stack/stack.c similarity index 100% rename from 155_min_stack/stack.c rename to 0155_min_stack/stack.c diff --git a/160_intersection_of_two_linked_list/Makefile b/0160_intersection_of_two_linked_list/Makefile similarity index 100% rename from 160_intersection_of_two_linked_list/Makefile rename to 0160_intersection_of_two_linked_list/Makefile diff --git a/160_intersection_of_two_linked_list/intersection.c b/0160_intersection_of_two_linked_list/intersection.c similarity index 100% rename from 160_intersection_of_two_linked_list/intersection.c rename to 0160_intersection_of_two_linked_list/intersection.c diff --git a/162_find_peak_element/Makefile b/0162_find_peak_element/Makefile similarity index 100% rename from 162_find_peak_element/Makefile rename to 0162_find_peak_element/Makefile diff --git a/162_find_peak_element/peak.c b/0162_find_peak_element/peak.c similarity index 100% rename from 162_find_peak_element/peak.c rename to 0162_find_peak_element/peak.c diff --git a/164_maximum_gap/Makefile b/0164_maximum_gap/Makefile similarity index 100% rename from 164_maximum_gap/Makefile rename to 0164_maximum_gap/Makefile diff --git a/164_maximum_gap/max_gap.c b/0164_maximum_gap/max_gap.c similarity index 100% rename from 164_maximum_gap/max_gap.c rename to 0164_maximum_gap/max_gap.c diff --git a/164_maximum_gap/max_gap.cc b/0164_maximum_gap/max_gap.cc similarity index 100% rename from 164_maximum_gap/max_gap.cc rename to 0164_maximum_gap/max_gap.cc diff --git a/165_compare_version_numbers/Makefile b/0165_compare_version_numbers/Makefile similarity index 100% rename from 165_compare_version_numbers/Makefile rename to 0165_compare_version_numbers/Makefile diff --git a/165_compare_version_numbers/version.c b/0165_compare_version_numbers/version.c similarity index 100% rename from 165_compare_version_numbers/version.c rename to 0165_compare_version_numbers/version.c diff --git a/166_fraction_to_recurring_decimal/Makefile b/0166_fraction_to_recurring_decimal/Makefile similarity index 100% rename from 166_fraction_to_recurring_decimal/Makefile rename to 0166_fraction_to_recurring_decimal/Makefile diff --git a/166_fraction_to_recurring_decimal/fraction.c b/0166_fraction_to_recurring_decimal/fraction.c similarity index 100% rename from 166_fraction_to_recurring_decimal/fraction.c rename to 0166_fraction_to_recurring_decimal/fraction.c diff --git a/167_two_sum_ii/Makefile b/0167_two_sum_ii/Makefile similarity index 100% rename from 167_two_sum_ii/Makefile rename to 0167_two_sum_ii/Makefile diff --git a/167_two_sum_ii/two_sum.c b/0167_two_sum_ii/two_sum.c similarity index 100% rename from 167_two_sum_ii/two_sum.c rename to 0167_two_sum_ii/two_sum.c diff --git a/167_two_sum_ii/two_sum.cc b/0167_two_sum_ii/two_sum.cc similarity index 100% rename from 167_two_sum_ii/two_sum.cc rename to 0167_two_sum_ii/two_sum.cc diff --git a/168_excel_sheet_column_title/Makefile b/0168_excel_sheet_column_title/Makefile similarity index 100% rename from 168_excel_sheet_column_title/Makefile rename to 0168_excel_sheet_column_title/Makefile diff --git a/168_excel_sheet_column_title/sheet_column.c b/0168_excel_sheet_column_title/sheet_column.c similarity index 100% rename from 168_excel_sheet_column_title/sheet_column.c rename to 0168_excel_sheet_column_title/sheet_column.c diff --git a/169_majority_element/Makefile b/0169_majority_element/Makefile similarity index 100% rename from 169_majority_element/Makefile rename to 0169_majority_element/Makefile diff --git a/169_majority_element/majority.c b/0169_majority_element/majority.c similarity index 100% rename from 169_majority_element/majority.c rename to 0169_majority_element/majority.c diff --git a/169_majority_element/majority.cc b/0169_majority_element/majority.cc similarity index 100% rename from 169_majority_element/majority.cc rename to 0169_majority_element/majority.cc diff --git a/171_excel_sheet_column_number/Makefile b/0171_excel_sheet_column_number/Makefile similarity index 100% rename from 171_excel_sheet_column_number/Makefile rename to 0171_excel_sheet_column_number/Makefile diff --git a/171_excel_sheet_column_number/sheet_column.c b/0171_excel_sheet_column_number/sheet_column.c similarity index 100% rename from 171_excel_sheet_column_number/sheet_column.c rename to 0171_excel_sheet_column_number/sheet_column.c diff --git a/172_factorial_trailing_zeros/Makefile b/0172_factorial_trailing_zeros/Makefile similarity index 100% rename from 172_factorial_trailing_zeros/Makefile rename to 0172_factorial_trailing_zeros/Makefile diff --git a/172_factorial_trailing_zeros/zeroes.c b/0172_factorial_trailing_zeros/zeroes.c similarity index 100% rename from 172_factorial_trailing_zeros/zeroes.c rename to 0172_factorial_trailing_zeros/zeroes.c diff --git a/172_factorial_trailing_zeros/zeroes.cc b/0172_factorial_trailing_zeros/zeroes.cc similarity index 100% rename from 172_factorial_trailing_zeros/zeroes.cc rename to 0172_factorial_trailing_zeros/zeroes.cc diff --git a/173_binary_search_tree_iterator/Makefile b/0173_binary_search_tree_iterator/Makefile similarity index 100% rename from 173_binary_search_tree_iterator/Makefile rename to 0173_binary_search_tree_iterator/Makefile diff --git a/173_binary_search_tree_iterator/bst_iter.c b/0173_binary_search_tree_iterator/bst_iter.c similarity index 100% rename from 173_binary_search_tree_iterator/bst_iter.c rename to 0173_binary_search_tree_iterator/bst_iter.c diff --git a/174_dungeon_game/Makefile b/0174_dungeon_game/Makefile similarity index 100% rename from 174_dungeon_game/Makefile rename to 0174_dungeon_game/Makefile diff --git a/174_dungeon_game/dungeon.c b/0174_dungeon_game/dungeon.c similarity index 100% rename from 174_dungeon_game/dungeon.c rename to 0174_dungeon_game/dungeon.c diff --git a/179_largest_number/Makefile b/0179_largest_number/Makefile similarity index 100% rename from 179_largest_number/Makefile rename to 0179_largest_number/Makefile diff --git a/179_largest_number/largest_number.c b/0179_largest_number/largest_number.c similarity index 100% rename from 179_largest_number/largest_number.c rename to 0179_largest_number/largest_number.c diff --git a/179_largest_number/largest_number.cc b/0179_largest_number/largest_number.cc similarity index 100% rename from 179_largest_number/largest_number.cc rename to 0179_largest_number/largest_number.cc diff --git a/188_best_time_to_buy_and_sell_stock_iv/Makefile b/0188_best_time_to_buy_and_sell_stock_iv/Makefile similarity index 100% rename from 188_best_time_to_buy_and_sell_stock_iv/Makefile rename to 0188_best_time_to_buy_and_sell_stock_iv/Makefile diff --git a/188_best_time_to_buy_and_sell_stock_iv/stock.c b/0188_best_time_to_buy_and_sell_stock_iv/stock.c similarity index 100% rename from 188_best_time_to_buy_and_sell_stock_iv/stock.c rename to 0188_best_time_to_buy_and_sell_stock_iv/stock.c diff --git a/189_rotate_array/Makefile b/0189_rotate_array/Makefile similarity index 100% rename from 189_rotate_array/Makefile rename to 0189_rotate_array/Makefile diff --git a/189_rotate_array/rotate_array.c b/0189_rotate_array/rotate_array.c similarity index 100% rename from 189_rotate_array/rotate_array.c rename to 0189_rotate_array/rotate_array.c diff --git a/189_rotate_array/rotate_array.cc b/0189_rotate_array/rotate_array.cc similarity index 100% rename from 189_rotate_array/rotate_array.cc rename to 0189_rotate_array/rotate_array.cc diff --git a/190_reverse_bits/Makefile b/0190_reverse_bits/Makefile similarity index 100% rename from 190_reverse_bits/Makefile rename to 0190_reverse_bits/Makefile diff --git a/190_reverse_bits/reverse_bits.c b/0190_reverse_bits/reverse_bits.c similarity index 100% rename from 190_reverse_bits/reverse_bits.c rename to 0190_reverse_bits/reverse_bits.c diff --git a/191_number_of_one_bits/Makefile b/0191_number_of_one_bits/Makefile similarity index 100% rename from 191_number_of_one_bits/Makefile rename to 0191_number_of_one_bits/Makefile diff --git a/191_number_of_one_bits/hamming_weight.c b/0191_number_of_one_bits/hamming_weight.c similarity index 100% rename from 191_number_of_one_bits/hamming_weight.c rename to 0191_number_of_one_bits/hamming_weight.c diff --git a/198_house_robber/Makefile b/0198_house_robber/Makefile similarity index 100% rename from 198_house_robber/Makefile rename to 0198_house_robber/Makefile diff --git a/198_house_robber/robber.c b/0198_house_robber/robber.c similarity index 100% rename from 198_house_robber/robber.c rename to 0198_house_robber/robber.c diff --git a/198_house_robber/robber.cc b/0198_house_robber/robber.cc similarity index 100% rename from 198_house_robber/robber.cc rename to 0198_house_robber/robber.cc diff --git a/199_binary_tree_right_side_view/Makefile b/0199_binary_tree_right_side_view/Makefile similarity index 100% rename from 199_binary_tree_right_side_view/Makefile rename to 0199_binary_tree_right_side_view/Makefile diff --git a/199_binary_tree_right_side_view/bst_right.c b/0199_binary_tree_right_side_view/bst_right.c similarity index 100% rename from 199_binary_tree_right_side_view/bst_right.c rename to 0199_binary_tree_right_side_view/bst_right.c diff --git a/200_number_of_islands/Makefile b/0200_number_of_islands/Makefile similarity index 100% rename from 200_number_of_islands/Makefile rename to 0200_number_of_islands/Makefile diff --git a/200_number_of_islands/islands.c b/0200_number_of_islands/islands.c similarity index 100% rename from 200_number_of_islands/islands.c rename to 0200_number_of_islands/islands.c diff --git a/201_bitwise_and_of_numbers_range/Makefile b/0201_bitwise_and_of_numbers_range/Makefile similarity index 100% rename from 201_bitwise_and_of_numbers_range/Makefile rename to 0201_bitwise_and_of_numbers_range/Makefile diff --git a/201_bitwise_and_of_numbers_range/and.c b/0201_bitwise_and_of_numbers_range/and.c similarity index 100% rename from 201_bitwise_and_of_numbers_range/and.c rename to 0201_bitwise_and_of_numbers_range/and.c diff --git a/202_happy_number/Makefile b/0202_happy_number/Makefile similarity index 100% rename from 202_happy_number/Makefile rename to 0202_happy_number/Makefile diff --git a/202_happy_number/happy_number.c b/0202_happy_number/happy_number.c similarity index 100% rename from 202_happy_number/happy_number.c rename to 0202_happy_number/happy_number.c diff --git a/203_remove_linked_list_element/Makefile b/0203_remove_linked_list_element/Makefile similarity index 100% rename from 203_remove_linked_list_element/Makefile rename to 0203_remove_linked_list_element/Makefile diff --git a/203_remove_linked_list_element/rm_elem.c b/0203_remove_linked_list_element/rm_elem.c similarity index 100% rename from 203_remove_linked_list_element/rm_elem.c rename to 0203_remove_linked_list_element/rm_elem.c diff --git a/204_count_primes/Makefile b/0204_count_primes/Makefile similarity index 100% rename from 204_count_primes/Makefile rename to 0204_count_primes/Makefile diff --git a/204_count_primes/count_primes.c b/0204_count_primes/count_primes.c similarity index 100% rename from 204_count_primes/count_primes.c rename to 0204_count_primes/count_primes.c diff --git a/205_isomorphic_strings/Makefile b/0205_isomorphic_strings/Makefile similarity index 100% rename from 205_isomorphic_strings/Makefile rename to 0205_isomorphic_strings/Makefile diff --git a/205_isomorphic_strings/isomorphic_strings.c b/0205_isomorphic_strings/isomorphic_strings.c similarity index 100% rename from 205_isomorphic_strings/isomorphic_strings.c rename to 0205_isomorphic_strings/isomorphic_strings.c diff --git a/206_reverse_linked_list/Makefile b/0206_reverse_linked_list/Makefile similarity index 100% rename from 206_reverse_linked_list/Makefile rename to 0206_reverse_linked_list/Makefile diff --git a/206_reverse_linked_list/reverse_list.c b/0206_reverse_linked_list/reverse_list.c similarity index 100% rename from 206_reverse_linked_list/reverse_list.c rename to 0206_reverse_linked_list/reverse_list.c diff --git a/207_course_schedule/Makefile b/0207_course_schedule/Makefile similarity index 100% rename from 207_course_schedule/Makefile rename to 0207_course_schedule/Makefile diff --git a/207_course_schedule/course_schedule.c b/0207_course_schedule/course_schedule.c similarity index 100% rename from 207_course_schedule/course_schedule.c rename to 0207_course_schedule/course_schedule.c diff --git a/208_implement_trie/Makefile b/0208_implement_trie/Makefile similarity index 100% rename from 208_implement_trie/Makefile rename to 0208_implement_trie/Makefile diff --git a/208_implement_trie/trie.c b/0208_implement_trie/trie.c similarity index 100% rename from 208_implement_trie/trie.c rename to 0208_implement_trie/trie.c diff --git a/209_minimum_size_subarray_sum/Makefile b/0209_minimum_size_subarray_sum/Makefile similarity index 100% rename from 209_minimum_size_subarray_sum/Makefile rename to 0209_minimum_size_subarray_sum/Makefile diff --git a/209_minimum_size_subarray_sum/mini_size.c b/0209_minimum_size_subarray_sum/mini_size.c similarity index 100% rename from 209_minimum_size_subarray_sum/mini_size.c rename to 0209_minimum_size_subarray_sum/mini_size.c diff --git a/210_course_schedule_ii/Makefile b/0210_course_schedule_ii/Makefile similarity index 100% rename from 210_course_schedule_ii/Makefile rename to 0210_course_schedule_ii/Makefile diff --git a/210_course_schedule_ii/course_schedule.c b/0210_course_schedule_ii/course_schedule.c similarity index 100% rename from 210_course_schedule_ii/course_schedule.c rename to 0210_course_schedule_ii/course_schedule.c diff --git a/211_add_and_search_word/Makefile b/0211_add_and_search_word/Makefile similarity index 100% rename from 211_add_and_search_word/Makefile rename to 0211_add_and_search_word/Makefile diff --git a/211_add_and_search_word/word_dict.c b/0211_add_and_search_word/word_dict.c similarity index 100% rename from 211_add_and_search_word/word_dict.c rename to 0211_add_and_search_word/word_dict.c diff --git a/212_word_search_ii/Makefile b/0212_word_search_ii/Makefile similarity index 100% rename from 212_word_search_ii/Makefile rename to 0212_word_search_ii/Makefile diff --git a/212_word_search_ii/word_search.c b/0212_word_search_ii/word_search.c similarity index 100% rename from 212_word_search_ii/word_search.c rename to 0212_word_search_ii/word_search.c diff --git a/213_house_robber_ii/Makefile b/0213_house_robber_ii/Makefile similarity index 100% rename from 213_house_robber_ii/Makefile rename to 0213_house_robber_ii/Makefile diff --git a/213_house_robber_ii/robber.c b/0213_house_robber_ii/robber.c similarity index 100% rename from 213_house_robber_ii/robber.c rename to 0213_house_robber_ii/robber.c diff --git a/213_house_robber_ii/robber.cc b/0213_house_robber_ii/robber.cc similarity index 100% rename from 213_house_robber_ii/robber.cc rename to 0213_house_robber_ii/robber.cc diff --git a/214_shortest_palindrome/Makefile b/0214_shortest_palindrome/Makefile similarity index 100% rename from 214_shortest_palindrome/Makefile rename to 0214_shortest_palindrome/Makefile diff --git a/214_shortest_palindrome/shortest_palindrome.c b/0214_shortest_palindrome/shortest_palindrome.c similarity index 100% rename from 214_shortest_palindrome/shortest_palindrome.c rename to 0214_shortest_palindrome/shortest_palindrome.c diff --git a/215_kth_largest_element_in_an_array/Makefile b/0215_kth_largest_element_in_an_array/Makefile similarity index 100% rename from 215_kth_largest_element_in_an_array/Makefile rename to 0215_kth_largest_element_in_an_array/Makefile diff --git a/215_kth_largest_element_in_an_array/kth_elem.c b/0215_kth_largest_element_in_an_array/kth_elem.c similarity index 100% rename from 215_kth_largest_element_in_an_array/kth_elem.c rename to 0215_kth_largest_element_in_an_array/kth_elem.c diff --git a/215_kth_largest_element_in_an_array/kth_elem.cc b/0215_kth_largest_element_in_an_array/kth_elem.cc similarity index 100% rename from 215_kth_largest_element_in_an_array/kth_elem.cc rename to 0215_kth_largest_element_in_an_array/kth_elem.cc diff --git a/216_combination_sum_iii/Makefile b/0216_combination_sum_iii/Makefile similarity index 100% rename from 216_combination_sum_iii/Makefile rename to 0216_combination_sum_iii/Makefile diff --git a/216_combination_sum_iii/combination_sum.c b/0216_combination_sum_iii/combination_sum.c similarity index 100% rename from 216_combination_sum_iii/combination_sum.c rename to 0216_combination_sum_iii/combination_sum.c diff --git a/221_maximal_square/Makefile b/0221_maximal_square/Makefile similarity index 100% rename from 221_maximal_square/Makefile rename to 0221_maximal_square/Makefile diff --git a/221_maximal_square/maximal_square.c b/0221_maximal_square/maximal_square.c similarity index 100% rename from 221_maximal_square/maximal_square.c rename to 0221_maximal_square/maximal_square.c diff --git a/224_basic_calculator/Makefile b/0224_basic_calculator/Makefile similarity index 100% rename from 224_basic_calculator/Makefile rename to 0224_basic_calculator/Makefile diff --git a/224_basic_calculator/calculator.c b/0224_basic_calculator/calculator.c similarity index 100% rename from 224_basic_calculator/calculator.c rename to 0224_basic_calculator/calculator.c diff --git a/226_invert_binary_tree/Makefile b/0226_invert_binary_tree/Makefile similarity index 100% rename from 226_invert_binary_tree/Makefile rename to 0226_invert_binary_tree/Makefile diff --git a/226_invert_binary_tree/invert_binary_tree.c b/0226_invert_binary_tree/invert_binary_tree.c similarity index 100% rename from 226_invert_binary_tree/invert_binary_tree.c rename to 0226_invert_binary_tree/invert_binary_tree.c diff --git a/226_invert_binary_tree/invert_binary_tree.cc b/0226_invert_binary_tree/invert_binary_tree.cc similarity index 100% rename from 226_invert_binary_tree/invert_binary_tree.cc rename to 0226_invert_binary_tree/invert_binary_tree.cc diff --git a/227_basic_calculator_ii/Makefile b/0227_basic_calculator_ii/Makefile similarity index 100% rename from 227_basic_calculator_ii/Makefile rename to 0227_basic_calculator_ii/Makefile diff --git a/227_basic_calculator_ii/calculator.c b/0227_basic_calculator_ii/calculator.c similarity index 100% rename from 227_basic_calculator_ii/calculator.c rename to 0227_basic_calculator_ii/calculator.c diff --git a/229_majority_element_ii/Makefile b/0229_majority_element_ii/Makefile similarity index 100% rename from 229_majority_element_ii/Makefile rename to 0229_majority_element_ii/Makefile diff --git a/229_majority_element_ii/majority.c b/0229_majority_element_ii/majority.c similarity index 100% rename from 229_majority_element_ii/majority.c rename to 0229_majority_element_ii/majority.c diff --git a/230_kth_smallest_element_in_a_bst/Makefile b/0230_kth_smallest_element_in_a_bst/Makefile similarity index 100% rename from 230_kth_smallest_element_in_a_bst/Makefile rename to 0230_kth_smallest_element_in_a_bst/Makefile diff --git a/230_kth_smallest_element_in_a_bst/kth_bst.c b/0230_kth_smallest_element_in_a_bst/kth_bst.c similarity index 100% rename from 230_kth_smallest_element_in_a_bst/kth_bst.c rename to 0230_kth_smallest_element_in_a_bst/kth_bst.c diff --git a/230_kth_smallest_element_in_a_bst/kth_bst.cc b/0230_kth_smallest_element_in_a_bst/kth_bst.cc similarity index 100% rename from 230_kth_smallest_element_in_a_bst/kth_bst.cc rename to 0230_kth_smallest_element_in_a_bst/kth_bst.cc diff --git a/235_lowest_common_ancestor_of_a_binary_search_tree/Makefile b/0235_lowest_common_ancestor_of_a_binary_search_tree/Makefile similarity index 100% rename from 235_lowest_common_ancestor_of_a_binary_search_tree/Makefile rename to 0235_lowest_common_ancestor_of_a_binary_search_tree/Makefile diff --git a/235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c b/0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c similarity index 100% rename from 235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c rename to 0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c diff --git a/236_lowest_common_ancestor_of_a_binary_tree/Makefile b/0236_lowest_common_ancestor_of_a_binary_tree/Makefile similarity index 100% rename from 236_lowest_common_ancestor_of_a_binary_tree/Makefile rename to 0236_lowest_common_ancestor_of_a_binary_tree/Makefile diff --git a/236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c b/0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c similarity index 100% rename from 236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c rename to 0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c diff --git a/239_sliding_window_maximum/Makefile b/0239_sliding_window_maximum/Makefile similarity index 100% rename from 239_sliding_window_maximum/Makefile rename to 0239_sliding_window_maximum/Makefile diff --git a/239_sliding_window_maximum/slide_window.c b/0239_sliding_window_maximum/slide_window.c similarity index 100% rename from 239_sliding_window_maximum/slide_window.c rename to 0239_sliding_window_maximum/slide_window.c diff --git a/239_sliding_window_maximum/slide_window.cc b/0239_sliding_window_maximum/slide_window.cc similarity index 100% rename from 239_sliding_window_maximum/slide_window.cc rename to 0239_sliding_window_maximum/slide_window.cc diff --git a/337_house_robber_iii/robber.cc b/0337_house_robber_iii/robber.cc similarity index 100% rename from 337_house_robber_iii/robber.cc rename to 0337_house_robber_iii/robber.cc diff --git a/416_partition_equal_subset_sum/partition.cc b/0416_partition_equal_subset_sum/partition.cc similarity index 100% rename from 416_partition_equal_subset_sum/partition.cc rename to 0416_partition_equal_subset_sum/partition.cc diff --git a/460_lfu_cache/Makefile b/0460_lfu_cache/Makefile similarity index 100% rename from 460_lfu_cache/Makefile rename to 0460_lfu_cache/Makefile diff --git a/460_lfu_cache/lfu_cache.c b/0460_lfu_cache/lfu_cache.c similarity index 100% rename from 460_lfu_cache/lfu_cache.c rename to 0460_lfu_cache/lfu_cache.c diff --git a/460_lfu_cache/lfu_cache.cc b/0460_lfu_cache/lfu_cache.cc similarity index 100% rename from 460_lfu_cache/lfu_cache.cc rename to 0460_lfu_cache/lfu_cache.cc diff --git a/543_diameter_of_binary_tree/diameter_bst.cc b/0543_diameter_of_binary_tree/diameter_bst.cc similarity index 100% rename from 543_diameter_of_binary_tree/diameter_bst.cc rename to 0543_diameter_of_binary_tree/diameter_bst.cc diff --git a/563_binary_tree_tilt/tilt.cc b/0563_binary_tree_tilt/tilt.cc similarity index 100% rename from 563_binary_tree_tilt/tilt.cc rename to 0563_binary_tree_tilt/tilt.cc From 6b360fe01a77dfebd96580f9bb2d632fa3653cee Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 30 Dec 2020 18:11:16 +0800 Subject: [PATCH 125/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../binary_tree_build.c | 11 +----- .../binary_tree_build.cc | 39 +++++++++++++++++++ .../binary_tree_build.c | 25 ++++-------- .../binary_tree_build.cc | 39 +++++++++++++++++++ .../bst_max_path.c | 8 ++-- 5 files changed, 91 insertions(+), 31 deletions(-) create mode 100644 0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.cc create mode 100644 0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.cc 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 87bd48c..6162f06 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 @@ -73,15 +73,6 @@ static int find(int num, int size, struct hlist_head *heads) return -1; } -static struct TreeNode *node_new(int val) -{ - struct TreeNode *tn = malloc(sizeof(*tn)); - tn->val = val; - tn->left = NULL; - tn->right = NULL; - return tn; -} - static struct TreeNode *dfs(int *preorder, int pre_low, int pre_high, int *inorder, int in_low, int in_high, struct hlist_head *in_heads, int size) { @@ -107,7 +98,7 @@ static void node_add(int val, int index, int size, struct hlist_head *heads) static struct TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize) { - int i, j; + int i; struct hlist_head *in_heads = malloc(inorderSize * sizeof(*in_heads)); for (i = 0; i < inorderSize; i++) { INIT_HLIST_HEAD(&in_heads[i]); diff --git a/0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.cc b/0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.cc new file mode 100644 index 0000000..c3e9af6 --- /dev/null +++ b/0105_construct_binary_tree_from_preorder_and_inorder_traversal/binary_tree_build.cc @@ -0,0 +1,39 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* buildTree(vector& preorder, vector& inorder) { + for (int i = 0; i < inorder.size(); i++) { + map_[inorder[i]] = i; + } + int size = inorder.size(); + return dfs(preorder, 0, size - 1, inorder, 0, size - 1); + } + +private: + unordered_map map_; + TreeNode* dfs(vector& preorder, int pre_lo, int pre_hi, vector& inorder, int in_lo, int in_hi) { + if (pre_lo > pre_hi || in_lo > in_hi) { + return nullptr; + } + int value = preorder[pre_lo]; + TreeNode *root = new TreeNode(value); + int index = map_[value]; + root->left = dfs(preorder, pre_lo + 1, pre_lo + (index - in_lo), inorder, in_lo, index - 1); + root->right = dfs(preorder, pre_hi - (in_hi - index) + 1, pre_hi, inorder, index + 1, in_hi); + return root; + } +}; 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 60c9b62..2edb121 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 @@ -73,15 +73,6 @@ static int find(int num, int size, struct hlist_head *heads) return -1; } -static struct TreeNode *node_new(int val) -{ - struct TreeNode *tn = malloc(sizeof(*tn)); - tn->val = val; - tn->left = NULL; - tn->right = NULL; - return tn; -} - static void node_add(int val, int index, int size, struct hlist_head *heads) { struct order_node *on = malloc(sizeof(*on)); @@ -91,23 +82,23 @@ static void node_add(int val, int index, int size, struct hlist_head *heads) hlist_add_head(&on->node, &heads[hash]); } -static struct TreeNode *dfs(int *inorder, int in_low, int in_high, int *postorder, - int post_low, int post_high, struct hlist_head *in_heads, int size) +static struct TreeNode *dfs(int *inorder, int in_lo, int in_hi, int *postorder, + int post_lo, int post_hi, struct hlist_head *in_heads, int size) { - if (in_low > in_high || post_low > post_high) { + if (in_lo > in_hi || post_lo > post_hi) { return NULL; } struct TreeNode *tn = malloc(sizeof(*tn)); - tn->val = postorder[post_high]; - int index = find(postorder[post_high], size, in_heads); - tn->left = dfs(inorder, in_low, index - 1, postorder, post_low, post_low + (index - 1 - in_low), in_heads, size); - tn->right = dfs(inorder, index + 1, in_high, postorder, post_high - (in_high - index), post_high - 1, in_heads, size); + tn->val = postorder[post_hi]; + int index = find(postorder[post_hi], size, in_heads); + tn->left = dfs(inorder, in_lo, index - 1, postorder, post_lo, post_lo + (index - 1 - in_lo), in_heads, size); + tn->right = dfs(inorder, index + 1, in_hi, postorder, post_hi - (in_hi - index), post_hi - 1, in_heads, size); return tn; } static struct TreeNode *buildTree(int *inorder, int inorderSize, int *postorder, int postorderSize) { - int i, j; + int i; struct hlist_head *in_heads = malloc(inorderSize * sizeof(*in_heads)); for (i = 0; i < inorderSize; i++) { INIT_HLIST_HEAD(&in_heads[i]); diff --git a/0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.cc b/0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.cc new file mode 100644 index 0000000..b947275 --- /dev/null +++ b/0106_construct_binary_tree_from_inorder_and_postorder_traversal/binary_tree_build.cc @@ -0,0 +1,39 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* buildTree(vector& inorder, vector& postorder) { + for (int i = 0; i < inorder.size(); i++) { + map_[inorder[i]] = i; + } + int size = inorder.size(); + return dfs(inorder, 0, size - 1, postorder, 0, size - 1); + } + +private: + unordered_map map_; + TreeNode* dfs(vector& inorder, int in_lo, int in_hi, vector& postorder, int post_lo, int post_hi) { + if (in_lo > in_hi || post_lo > post_hi) { + return nullptr; + } + int value = postorder[post_hi]; + TreeNode *root = new TreeNode(value); + int index = map_[value]; + root->left = dfs(inorder, in_lo, index - 1, postorder, post_lo, post_lo + (index - in_lo - 1)); + root->right = dfs(inorder, index + 1, in_hi, postorder, post_hi - (in_hi - index), post_hi - 1); + return root; + } +}; diff --git a/0124_binary_tree_maximum_path_sum/bst_max_path.c b/0124_binary_tree_maximum_path_sum/bst_max_path.c index e3ecad1..ff35b9a 100644 --- a/0124_binary_tree_maximum_path_sum/bst_max_path.c +++ b/0124_binary_tree_maximum_path_sum/bst_max_path.c @@ -20,10 +20,10 @@ static int dfs(struct TreeNode *root, int *max) } /* In case of negative node value */ - int l = maximum(dfs(root->left, max), 0); - int r = maximum(dfs(root->right, max), 0); + int subl = maximum(dfs(root->left, max), 0); + int subr = maximum(dfs(root->right, max), 0); - int sum = root->val + l + r; + int sum = root->val + subl + subr; if (sum > *max) { *max = sum; } @@ -31,7 +31,7 @@ static int dfs(struct TreeNode *root, int *max) /* The return value does not equal the sum value * since we need to return path through the root node */ - return root->val + maximum(l, r); + return root->val + maximum(subl, subr); } static int maxPathSum(struct TreeNode* root) From a90b53dc979a67096632a842fa2c1550379f14f0 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 31 Dec 2020 11:27:37 +0800 Subject: [PATCH 126/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0099_recover_binary_search_tree/recover_bst.c | 5 +- .../recover_bst.cc | 50 +++++++++++++++++++ 0322_coin_change/Makefile | 2 + 0322_coin_change/coin_change.c | 43 ++++++++++++++++ 0322_coin_change/coin_change.cc | 47 +++++++++++++++++ 5 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 0099_recover_binary_search_tree/recover_bst.cc create mode 100644 0322_coin_change/Makefile create mode 100644 0322_coin_change/coin_change.c create mode 100644 0322_coin_change/coin_change.cc diff --git a/0099_recover_binary_search_tree/recover_bst.c b/0099_recover_binary_search_tree/recover_bst.c index 6fb720b..5274c88 100644 --- a/0099_recover_binary_search_tree/recover_bst.c +++ b/0099_recover_binary_search_tree/recover_bst.c @@ -18,14 +18,15 @@ static void dfs(struct TreeNode *node, struct TreeNode **prev, dfs(node->left, prev, p1, p2, wrong); - /* We must use pointer to pointer for previous object in recursion */ + /* We must use pointer to pointer to previous object for backward recursion */ if (*prev != NULL && node->val < (*prev)->val) { (*wrong)++; if (*wrong == 1) { *p1 = *prev; - /* p2 should be recorded here in some cases */ + /* p2 frist to be recorded here */ *p2 = node; } else if (*wrong == 2) { + /* update p2 location */ *p2 = node; } } diff --git a/0099_recover_binary_search_tree/recover_bst.cc b/0099_recover_binary_search_tree/recover_bst.cc new file mode 100644 index 0000000..7985386 --- /dev/null +++ b/0099_recover_binary_search_tree/recover_bst.cc @@ -0,0 +1,50 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void recoverTree(TreeNode* root) { + dfs(root); + int tmp = p0_->val; + p0_->val = p1_->val; + p1_->val = tmp; + } + +private: + int wrong_ = 0; + TreeNode *prev_ = nullptr; + TreeNode *p0_ = nullptr; + TreeNode *p1_ = nullptr; + + void dfs(TreeNode* root) { + if (root == nullptr || wrong_ == 2) { + return; + } + + dfs(root->left); + if (prev_ != nullptr && prev_->val > root->val) { + if (++wrong_ == 1) { + p0_ = prev_; + // p1 first to be recorded here + p1_ = root; + } else if (wrong_ == 2) { + // update p1 location + p1_ = root; + } + } + prev_ = root; + dfs(root->right); + } +}; diff --git a/0322_coin_change/Makefile b/0322_coin_change/Makefile new file mode 100644 index 0000000..a766ed4 --- /dev/null +++ b/0322_coin_change/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test coin_change.c diff --git a/0322_coin_change/coin_change.c b/0322_coin_change/coin_change.c new file mode 100644 index 0000000..10c8244 --- /dev/null +++ b/0322_coin_change/coin_change.c @@ -0,0 +1,43 @@ +#include +#include + + +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; + } + + dp[0] = 0; + for (i = 1; i <= amount; i++) { + for (j = 0; j < coinsSize; j++) { + if (i - coins[j] >= 0) { + int tmp = 1 + dp[i - coins[j]]; + dp[i] = tmp < dp[i] ? tmp : dp[i]; + } + } + } + + return dp[amount] == amount + 1 ? -1 : dp[amount]; +} + +int main(int argc, char **argv) +{ + if (argc < 3) { + fprintf(stderr, "Usage: ./test 11 1 2 5"); + exit(-1); + } + + int amount = atoi(argv[1]); + int i, size = argc - 2; + int *coins = malloc(size * sizeof(int)); + for (i = 0; i < size; i++) { + coins[i] = atoi(argv[i + 2]); + } + printf("%d\n", coinChange(coins, size, amount)); + + return 0; +} diff --git a/0322_coin_change/coin_change.cc b/0322_coin_change/coin_change.cc new file mode 100644 index 0000000..4b2fa6e --- /dev/null +++ b/0322_coin_change/coin_change.cc @@ -0,0 +1,47 @@ +#include + +using namespace std; + +class Solution { +public: + int coinChange(vector& coins, int amount) { +#if 1 + vector dp(amount + 1, amount + 1); + dp[0] = 0; + for (int i = 1; i <= amount; i++) { + for (int coin : coins) { + if (i - coin >= 0) { + dp[i] = min(dp[i], 1 + dp[i - coin]); + } + } + } + return dp[amount] == amount + 1 ? -1 : dp[amount]; +#else + // BFS solution is slow... + queue q; + unordered_set s; + int step = 0; + q.push(amount); + while (!q.empty()) { + int size = q.size(); + for (int i = 0; i < size; i++) { + if (q.front() == 0) { + return step; + } + for (int coin : coins) { + int n = q.front() - coin; + if (n >= 0) { + if (s.count(n) == 0) { + s.insert(n); + q.push(n); + } + } + } + q.pop(); + } + step++; + } + return -1; +#endif + } +}; From 579c7682c46111d2e0c42093944e7c3acd3ed36e Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 2 Jan 2021 23:45:32 +0800 Subject: [PATCH 127/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../Makefile | 2 + .../tree_serdes.c | 114 ++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 0297_serialize_and_deserialize_binary_tree/Makefile create mode 100644 0297_serialize_and_deserialize_binary_tree/tree_serdes.c diff --git a/0297_serialize_and_deserialize_binary_tree/Makefile b/0297_serialize_and_deserialize_binary_tree/Makefile new file mode 100644 index 0000000..cc0d8b0 --- /dev/null +++ b/0297_serialize_and_deserialize_binary_tree/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test tree_serdes.c diff --git a/0297_serialize_and_deserialize_binary_tree/tree_serdes.c b/0297_serialize_and_deserialize_binary_tree/tree_serdes.c new file mode 100644 index 0000000..4ee15d7 --- /dev/null +++ b/0297_serialize_and_deserialize_binary_tree/tree_serdes.c @@ -0,0 +1,114 @@ +#include +#include +#include +#include + + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +static void ser(struct TreeNode *root, char **str, int *len) { + if (root == NULL) { + (*str)[(*len)++] = '#'; + (*str)[(*len)++] = ','; + } else { + int v = root->val; + if (v < 0) { + v = -v; + (*str)[(*len)++] = '-'; + } + while (v > 0) { + (*str)[(*len)++] = v % 10 + '0'; + v /= 10; + } + (*str)[(*len)++] = ','; + ser(root->left, str, len); + ser(root->right, str, len); + } +} + +static struct TreeNode *des(char **str) { + if (**str == '\0') { + return NULL; + } + if (**str == '#') { + (*str)++; + (*str)++; + return NULL; + } + + int i; + bool sign = false; + struct TreeNode *node = malloc(sizeof(struct TreeNode)); + node->val = 0; + if (**str == '-') { + sign = true; + (*str)++; + } + for (i = 1; **str != ','; i *= 10) { + node->val += i * ((**str) - '0'); + (*str)++; + } + if (sign) { + node->val = -node->val; + } + (*str)++; + node->left = des(str); + node->right = des(str); + return node; +} + +/** Encodes a tree to a single string. */ +char* serialize(struct TreeNode* root) { + int len = 0; + char *str = malloc(40000); + memset(str, '\0', 40000); + ser(root, &str, &len); + return str; +} + +/** Decodes your encoded data to tree. */ +struct TreeNode* deserialize(char* data) { + return des(&data); +} + +int main(void) +{ + struct TreeNode root; + root.val = 3; + + struct TreeNode node1[2]; + node1[0].val = 9; + node1[1].val = 20; + + struct TreeNode node2[4]; + node2[2].val = 15; + node2[3].val = 7; + + root.left = &node1[0]; + root.right = &node1[1]; + + node1[0].left = NULL; + node1[0].right = NULL; + node1[1].left = &node2[2]; + node1[1].right = &node2[3]; + + node2[0].left = NULL; + node2[0].right = NULL; + node2[1].left = NULL; + node2[1].right = NULL; + node2[2].left = NULL; + node2[2].right = NULL; + node2[3].left = NULL; + node2[3].right = NULL; + + /* Your functions will be called as such */ + char* data = serialize(&root); + printf("%s\n", data); + deserialize(data); + + return 0; +} From bdc54502b530270947fcc1c636df724fde044b4e Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 3 Jan 2021 00:54:10 +0800 Subject: [PATCH 128/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../bst_bfs.c | 125 +++++++++++++++--- .../bst_zigzag.c | 112 ++++++---------- .../bst_zigzag.cc | 50 +++++++ 3 files changed, 203 insertions(+), 84 deletions(-) create mode 100644 0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.cc diff --git a/0102_binary_tree_level_order_traversal/bst_bfs.c b/0102_binary_tree_level_order_traversal/bst_bfs.c index b12c5ce..62bfca2 100644 --- a/0102_binary_tree_level_order_traversal/bst_bfs.c +++ b/0102_binary_tree_level_order_traversal/bst_bfs.c @@ -2,34 +2,96 @@ #include #include + #define BST_MAX_LEVEL 800 +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) +#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) + struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; -static void bfs(struct TreeNode *root, int **results, int *count, int *col_sizes, int *size, int level) +struct list_head { + struct list_head *next, *prev; +}; + +struct queue_node { + struct TreeNode *node; + struct list_head link; +}; + +static inline void INIT_LIST_HEAD(struct list_head *list) { - if (root == NULL) { - return; - } + list->next = list->prev = list; +} - *count = level + 1 > *count ? level + 1 : *count; - if (col_sizes[level] == 0) { - *size = *size > 256 ? 256 : *size * 2; - results[level] = malloc(*size * sizeof(int)); +static inline int list_empty(const struct list_head *head) +{ + return head->next == head; +} + +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +static inline void list_add(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head, head->next); +} + +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} + +static inline void __list_del(struct list_head *entry) +{ + entry->next->prev = entry->prev; + entry->prev->next = entry->next; +} + +static inline void list_del(struct list_head *entry) +{ + __list_del(entry); + entry->next = entry->prev = NULL; +} + +static struct queue_node *node_new(struct list_head *free_list, struct TreeNode *node) +{ + struct queue_node *new; + if (list_empty(free_list)) { + new = malloc(sizeof(*new)); + } else { + new = list_first_entry(free_list, struct queue_node, link); + list_del(&new->link); } - results[level][col_sizes[level]++] = root->val; - bfs(root->left, results, count, col_sizes, size, level + 1); - bfs(root->right, results, count, col_sizes, size, level + 1); + new->node = node; + return new; +} + +static void node_free(struct list_head *free_list, struct queue_node *node) +{ + list_del(&node->link); + list_add(&node->link, 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 *columnSizes array must be malloced, assume caller calls free(). + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ static int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) { @@ -38,12 +100,45 @@ static int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColu return NULL; } - int size = 1; - *returnSize = 0; + struct list_head free_list; + struct list_head q; + INIT_LIST_HEAD(&free_list); + INIT_LIST_HEAD(&q); + int **results = malloc(BST_MAX_LEVEL * sizeof(int *)); *returnColumnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); memset(*returnColumnSizes, 0, BST_MAX_LEVEL * sizeof(int)); - bfs(root, results, returnSize, *returnColumnSizes, &size, 0); + + /* Add root node */ + struct queue_node *new = node_new(&free_list, root); + list_add_tail(&new->link, &q); + + int i, level = 0; + (*returnColumnSizes)[level]++; + while (!list_empty(&q)) { + int size = (*returnColumnSizes)[level]; + results[level] = malloc(size * sizeof(int)); + for (i = 0; i < size; i++) { + struct queue_node *n = list_first_entry(&q, struct queue_node, link); + results[level][i] = n->node->val; + + if (n->node->left != NULL) { + new = node_new(&free_list, n->node->left); + list_add_tail(&new->link, &q); + (*returnColumnSizes)[level + 1]++; + } + if (n->node->right != NULL) { + new = node_new(&free_list, n->node->right); + list_add_tail(&new->link, &q); + (*returnColumnSizes)[level + 1]++; + } + + node_free(&free_list, n); + } + level++; + } + + *returnSize = level; return results; } diff --git a/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c b/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c index 3e7c28d..0898168 100644 --- a/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c +++ b/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c @@ -13,18 +13,6 @@ #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) #define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_reverse(p, head) \ - for (p = (head)->prev; p != (head); p = p->prev) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - -#define list_for_each_safe_reverse(p, n, head) \ - for (p = (head)->prev, n = p->prev; p != (head); p = n, n = p->prev) - struct TreeNode { int val; struct TreeNode *left; @@ -35,6 +23,11 @@ struct list_head { struct list_head *next, *prev; }; +struct queue_node { + struct TreeNode *node; + struct list_head link; +}; + static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; @@ -75,66 +68,29 @@ static inline void list_del(struct list_head *entry) entry->next = entry->prev = NULL; } -struct bfs_node { - struct TreeNode *node; - struct list_head link; -}; - -static struct bfs_node *node_new(struct list_head *free_list, struct TreeNode *node) +static struct queue_node *node_new(struct list_head *free_list, struct TreeNode *node) { - struct bfs_node *new; + struct queue_node *new; if (list_empty(free_list)) { new = malloc(sizeof(*new)); } else { - new = list_first_entry(free_list, struct bfs_node, link); + new = list_first_entry(free_list, struct queue_node, link); list_del(&new->link); } new->node = node; return new; } -static void queue(struct list_head *parents, struct list_head *children, int reverse, - struct list_head *free_list, int **results, int *col_sizes, int level) +static void node_free(struct list_head *free_list, struct queue_node *node) { - struct list_head *p, *n; - struct bfs_node *new, *parent; - - list_for_each(p, parents) { - parent = list_entry(p, struct bfs_node, link); - if (parent->node->left != NULL) { - new = node_new(free_list, parent->node->left); - list_add_tail(&new->link, children); - } - if (parent->node->right != NULL) { - new = node_new(free_list, parent->node->right); - list_add_tail(&new->link, children); - } - col_sizes[level]++; - } - - int i = 0; - results[level] = malloc(col_sizes[level] * sizeof(int)); - if (reverse) { - list_for_each_safe_reverse(p, n, parents) { - parent = list_entry(p, struct bfs_node, link); - results[level][i++] = parent->node->val; - list_del(p); - list_add(p, free_list); - } - } else { - list_for_each_safe(p, n, parents) { - parent = list_entry(p, struct bfs_node, link); - results[level][i++] = parent->node->val; - list_del(p); - list_add(p, free_list); - } - } + list_del(&node->link); + list_add(&node->link, 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 *columnSizes array must be malloced, assume caller calls free(). + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ static int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) { @@ -144,25 +100,43 @@ static int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** retu } struct list_head free_list; - struct list_head q0; - struct list_head q1; + struct list_head q; INIT_LIST_HEAD(&free_list); - INIT_LIST_HEAD(&q0); - INIT_LIST_HEAD(&q1); + INIT_LIST_HEAD(&q); int **results = malloc(BST_MAX_LEVEL * sizeof(int *)); *returnColumnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); memset(*returnColumnSizes, 0, BST_MAX_LEVEL * sizeof(int)); - int level = 0; - struct bfs_node *new = node_new(&free_list, root); - list_add_tail(&new->link, &q0); - - while (!list_empty(&q0) || !list_empty(&q1)) { - if (level & 0x1) { - queue(&q1, &q0, 1, &free_list, results, *returnColumnSizes, level); - } else { - queue(&q0, &q1, 0, &free_list, results, *returnColumnSizes, level); + /* Add root node */ + struct queue_node *new = node_new(&free_list, root); + list_add_tail(&new->link, &q); + + int i, level = 0; + (*returnColumnSizes)[level]++; + while (!list_empty(&q)) { + int size = (*returnColumnSizes)[level]; + results[level] = malloc(size * sizeof(int)); + for (i = 0; i < size; i++) { + struct queue_node *n = list_first_entry(&q, struct queue_node, link); + if (level & 0x1) { + results[level][size - i - 1] = n->node->val; + } else { + results[level][i] = n->node->val; + } + + if (n->node->left != NULL) { + new = node_new(&free_list, n->node->left); + list_add_tail(&new->link, &q); + (*returnColumnSizes)[level + 1]++; + } + if (n->node->right != NULL) { + new = node_new(&free_list, n->node->right); + list_add_tail(&new->link, &q); + (*returnColumnSizes)[level + 1]++; + } + + node_free(&free_list, n); } level++; } diff --git a/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.cc b/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.cc new file mode 100644 index 0000000..026205b --- /dev/null +++ b/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.cc @@ -0,0 +1,50 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> res; + if (root == nullptr) { + return res; + } + + bool reversed = false; + queue q; + q.push(root); + while (!q.empty()) { + vector level; + int size = q.size(); + for (int i = 0; i < size; i++) { + TreeNode *node = q.front(); + q.pop(); + level.push_back(node->val); + if (node->left != nullptr) { + q.push(node->left); + } + if (node->right != nullptr) { + q.push(node->right); + } + } + if (reversed) { + reverse(level.begin(), level.end()); + } + res.push_back(level); + reversed = !reversed; + } + + return res; + } +}; From e09b73cc141eb98fd764694f7add8d1736111372 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 4 Jan 2021 23:59:55 +0800 Subject: [PATCH 129/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../window_substring.cc | 34 ++++ .../bst_bfs.c | 36 ++-- .../bst_zigzag.c | 38 ++--- .../connect.c | 155 ++++++++++-------- .../connect.cc | 53 ++++++ 0199_binary_tree_right_side_view/bst_right.c | 104 +++++------- 0199_binary_tree_right_side_view/bst_right.cc | 44 +++++ 7 files changed, 295 insertions(+), 169 deletions(-) create mode 100644 0076_minimum_window_substring/window_substring.cc create mode 100644 0117_populating_next_right_pointers_in_each_node_ii/connect.cc create mode 100644 0199_binary_tree_right_side_view/bst_right.cc diff --git a/0076_minimum_window_substring/window_substring.cc b/0076_minimum_window_substring/window_substring.cc new file mode 100644 index 0000000..d419221 --- /dev/null +++ b/0076_minimum_window_substring/window_substring.cc @@ -0,0 +1,34 @@ +#include + +using namespace std; + +class Solution { +public: + string minWindow(string s, string t) { + vector count(128); + for (char c : t) { + count[c]++; + } + + int l = 0, r = 0; + int need_to_meet = t.length(); + int start, min_len = INT_MAX; + while (r < s.length()) { + if (--count[s[r++]] >= 0) { + need_to_meet--; + } + + while (need_to_meet == 0) { + if (r - l < min_len) { + start = l; + min_len = r - l; + } + if (++count[s[l++]] > 0) { + need_to_meet++; + } + } + } + + return min_len == INT_MAX ? "" : s.substr(start, min_len); + } +}; diff --git a/0102_binary_tree_level_order_traversal/bst_bfs.c b/0102_binary_tree_level_order_traversal/bst_bfs.c index 62bfca2..9275ffe 100644 --- a/0102_binary_tree_level_order_traversal/bst_bfs.c +++ b/0102_binary_tree_level_order_traversal/bst_bfs.c @@ -69,23 +69,23 @@ static inline void list_del(struct list_head *entry) entry->next = entry->prev = NULL; } -static struct queue_node *node_new(struct list_head *free_list, struct TreeNode *node) +static struct queue_node *node_new(struct TreeNode *node, struct list_head *free_list) { - struct queue_node *new; + struct queue_node *qn; if (list_empty(free_list)) { - new = malloc(sizeof(*new)); + qn = malloc(sizeof(*qn)); } else { - new = list_first_entry(free_list, struct queue_node, link); - list_del(&new->link); + qn = list_first_entry(free_list, struct queue_node, link); + list_del(&qn->link); } - new->node = node; - return new; + qn->node = node; + return qn; } -static void node_free(struct list_head *free_list, struct queue_node *node) +static void node_free(struct queue_node *qn, struct list_head *free_list) { - list_del(&node->link); - list_add(&node->link, free_list); + list_del(&qn->link); + list_add(&qn->link, free_list); } /** @@ -110,7 +110,7 @@ static int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColu memset(*returnColumnSizes, 0, BST_MAX_LEVEL * sizeof(int)); /* Add root node */ - struct queue_node *new = node_new(&free_list, root); + struct queue_node *new = node_new(root, &free_list); list_add_tail(&new->link, &q); int i, level = 0; @@ -119,21 +119,21 @@ static int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColu int size = (*returnColumnSizes)[level]; results[level] = malloc(size * sizeof(int)); for (i = 0; i < size; i++) { - struct queue_node *n = list_first_entry(&q, struct queue_node, link); - results[level][i] = n->node->val; + struct queue_node *qn = list_first_entry(&q, struct queue_node, link); + results[level][i] = qn->node->val; - if (n->node->left != NULL) { - new = node_new(&free_list, n->node->left); + if (qn->node->left != NULL) { + new = node_new(qn->node->left, &free_list); list_add_tail(&new->link, &q); (*returnColumnSizes)[level + 1]++; } - if (n->node->right != NULL) { - new = node_new(&free_list, n->node->right); + if (qn->node->right != NULL) { + new = node_new(qn->node->right, &free_list); list_add_tail(&new->link, &q); (*returnColumnSizes)[level + 1]++; } - node_free(&free_list, n); + node_free(qn, &free_list); } level++; } diff --git a/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c b/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c index 0898168..08b8924 100644 --- a/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c +++ b/0103_binary_tree_zigzag_level_order_traversal/bst_zigzag.c @@ -68,23 +68,23 @@ static inline void list_del(struct list_head *entry) entry->next = entry->prev = NULL; } -static struct queue_node *node_new(struct list_head *free_list, struct TreeNode *node) +static struct queue_node *node_new(struct TreeNode *node, struct list_head *free_list) { - struct queue_node *new; + struct queue_node *qn; if (list_empty(free_list)) { - new = malloc(sizeof(*new)); + qn = malloc(sizeof(*qn)); } else { - new = list_first_entry(free_list, struct queue_node, link); - list_del(&new->link); + qn = list_first_entry(free_list, struct queue_node, link); + list_del(&qn->link); } - new->node = node; - return new; + qn->node = node; + return qn; } -static void node_free(struct list_head *free_list, struct queue_node *node) +static void node_free(struct queue_node *qn, struct list_head *free_list) { - list_del(&node->link); - list_add(&node->link, free_list); + list_del(&qn->link); + list_add(&qn->link, free_list); } /** @@ -109,7 +109,7 @@ static int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** retu memset(*returnColumnSizes, 0, BST_MAX_LEVEL * sizeof(int)); /* Add root node */ - struct queue_node *new = node_new(&free_list, root); + struct queue_node *new = node_new(root, &free_list); list_add_tail(&new->link, &q); int i, level = 0; @@ -118,25 +118,25 @@ static int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** retu int size = (*returnColumnSizes)[level]; results[level] = malloc(size * sizeof(int)); for (i = 0; i < size; i++) { - struct queue_node *n = list_first_entry(&q, struct queue_node, link); + struct queue_node *qn = list_first_entry(&q, struct queue_node, link); if (level & 0x1) { - results[level][size - i - 1] = n->node->val; + results[level][size - i - 1] = qn->node->val; } else { - results[level][i] = n->node->val; + results[level][i] = qn->node->val; } - if (n->node->left != NULL) { - new = node_new(&free_list, n->node->left); + if (qn->node->left != NULL) { + new = node_new(qn->node->left, &free_list); list_add_tail(&new->link, &q); (*returnColumnSizes)[level + 1]++; } - if (n->node->right != NULL) { - new = node_new(&free_list, n->node->right); + if (qn->node->right != NULL) { + new = node_new(qn->node->right, &free_list); list_add_tail(&new->link, &q); (*returnColumnSizes)[level + 1]++; } - node_free(&free_list, n); + node_free(qn, &free_list); } level++; } diff --git a/0117_populating_next_right_pointers_in_each_node_ii/connect.c b/0117_populating_next_right_pointers_in_each_node_ii/connect.c index 2cd5086..f5fb11d 100644 --- a/0117_populating_next_right_pointers_in_each_node_ii/connect.c +++ b/0117_populating_next_right_pointers_in_each_node_ii/connect.c @@ -1,12 +1,6 @@ #include #include -struct TreeLinkNode { - int val; - struct TreeLinkNode *left; - struct TreeLinkNode *right; - struct TreeLinkNode *next; -}; #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) @@ -17,16 +11,22 @@ struct TreeLinkNode { #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) #define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct list_head { struct list_head *next, *prev; }; +struct Node { + int val; + struct Node *left; + struct Node *right; + struct Node *next; +}; + +struct queue_node { + struct Node *node; + struct list_head link; +}; + static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; @@ -67,87 +67,72 @@ static inline void list_del(struct list_head *entry) entry->next = entry->prev = NULL; } -struct bfs_node { - struct TreeLinkNode *node; - struct list_head link; -}; - -static struct bfs_node *node_fetch(struct list_head *free_list, struct TreeLinkNode *node) +static struct queue_node *node_new(struct Node *node, struct list_head *free_list) { - struct bfs_node *bn = list_first_entry(free_list, struct bfs_node, link); - list_del(&bn->link); - bn->node = node; - return bn; + struct queue_node *qn; + if (list_empty(free_list)) { + qn = malloc(sizeof(*qn)); + } else { + qn = list_first_entry(free_list, struct queue_node, link); + list_del(&qn->link); + } + qn->node = node; + return qn; } -static void queue(struct list_head *parents, struct list_head *children, struct list_head *free_list) +static void node_free(struct queue_node *qn, struct list_head *free_list) { - struct list_head *p, *n; - struct TreeLinkNode *prev = NULL; - list_for_each_safe(p, n, parents) { - struct bfs_node *new; - struct bfs_node *parent = list_entry(p, struct bfs_node, link); - struct TreeLinkNode *lch = parent->node->left; - struct TreeLinkNode *rch = parent->node->right; - if (lch != NULL) { - if (prev != NULL) { - prev->next = lch; - } - prev = lch; - new = node_fetch(free_list, lch); - list_add_tail(&new->link, children); - } - if (rch != NULL) { - if (prev != NULL) { - prev->next = rch; - } - prev = rch; - new = node_fetch(free_list, rch); - list_add_tail(&new->link, children); - } - - /* return */ - list_del(p); - list_add(p, free_list); - } + list_del(&qn->link); + list_add_tail(&qn->link, free_list); } -static void connect(struct TreeLinkNode *root) +struct Node *connect(struct Node *root) { if (root == NULL) { - return; + return root; } struct list_head free_list; - struct list_head q0; - struct list_head q1; - struct bfs_node nodes[4096]; + struct list_head q; INIT_LIST_HEAD(&free_list); - INIT_LIST_HEAD(&q0); - INIT_LIST_HEAD(&q1); + INIT_LIST_HEAD(&q); - int i; - for (i = 0; i < 4096; i++) { - list_add(&nodes[i].link, &free_list); - } + int i, level_size = 1; + struct queue_node *new = node_new(root, &free_list); + list_add_tail(&new->link, &q); + + while (!list_empty(&q)) { + struct Node *prev = NULL; + int size = level_size; + for (i = 0; i < size; i++) { + struct queue_node *qn = list_first_entry(&q, struct queue_node, link); + if (prev != NULL) { + prev->next = qn->node; + } + prev = qn->node; - int level = 0; - struct bfs_node *new = node_fetch(&free_list, root); - list_add_tail(&new->link, &q0); + if (qn->node->left != NULL) { + new = node_new(qn->node->left, &free_list); + list_add_tail(&new->link, &q); + level_size++; + } + if (qn->node->right != NULL) { + new = node_new(qn->node->right, &free_list); + list_add_tail(&new->link, &q); + level_size++; + } - while (!list_empty(&q0) || !list_empty(&q1)) { - if (level & 0x1) { - queue(&q1, &q0, &free_list); - } else { - queue(&q0, &q1, &free_list); + node_free(qn, &free_list); } - level++; } + + return root; } int main(int argc, char **argv) { - struct TreeLinkNode root, n1[2], n2[4], n3[8]; + struct Node root, n1[2], n2[4], n3[8]; +#if 0 root.val = 5; n1[0].val = 4; n1[1].val = 8; @@ -188,6 +173,32 @@ int main(int argc, char **argv) n3[7].left = NULL; n3[7].right = NULL; n3[7].next = NULL; +#else + root.val = 1; + n1[0].val = 2; + n1[1].val = 3; + n2[0].val = 4; + n2[1].val = 5; + n2[3].val = 7; + + root.left = &n1[0]; + root.right = &n1[1]; + n1[0].left = &n2[0]; + n1[0].right = &n2[1]; + n1[0].next = NULL; + n1[1].left = NULL; + n1[1].right = &n2[3]; + n1[1].next = NULL; + n2[0].left = NULL; + n2[0].right = NULL; + n2[0].next = NULL; + n2[1].left = NULL; + n2[1].right = NULL; + n2[1].next = NULL; + n2[3].left = NULL; + n2[3].right = NULL; + n2[3].next = NULL; +#endif connect(&root); return 0; diff --git a/0117_populating_next_right_pointers_in_each_node_ii/connect.cc b/0117_populating_next_right_pointers_in_each_node_ii/connect.cc new file mode 100644 index 0000000..8408a8a --- /dev/null +++ b/0117_populating_next_right_pointers_in_each_node_ii/connect.cc @@ -0,0 +1,53 @@ +#include + +using namespace std; + +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (root == nullptr) { + return root; + } + + queue q; + q.push(root); + while (!q.empty()) { + int size = q.size(); + Node *prev = nullptr; + for (int i = 0; i < size; i++) { + Node *node = q.front(); + q.pop(); + if (prev != nullptr) { + prev->next = node; + } + prev = node; + if (node->left != nullptr) { + q.push(node->left); + } + if (node->right != nullptr) { + q.push(node->right); + } + } + } + + return root; + } +}; diff --git a/0199_binary_tree_right_side_view/bst_right.c b/0199_binary_tree_right_side_view/bst_right.c index 4993d08..f8fdbf4 100644 --- a/0199_binary_tree_right_side_view/bst_right.c +++ b/0199_binary_tree_right_side_view/bst_right.c @@ -2,6 +2,7 @@ #include #include + #define BST_MAX_LEVEL 800 #define container_of(ptr, type, member) \ @@ -13,12 +14,6 @@ #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) #define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) -#define list_for_each(p, head) \ - for (p = (head)->prev; p != (head); p = p->prev) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->prev, n = p->prev; p != (head); p = n, n = p->prev) - struct TreeNode { int val; struct TreeNode *left; @@ -29,6 +24,11 @@ struct list_head { struct list_head *next, *prev; }; +struct queue_node { + struct TreeNode *node; + struct list_head link; +}; + static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; @@ -69,58 +69,30 @@ static inline void list_del(struct list_head *entry) entry->next = entry->prev = NULL; } -struct bfs_node { - struct TreeNode *node; - struct list_head link; -}; - -static struct bfs_node *node_new(struct list_head *free_list, struct TreeNode *node) +static struct queue_node *node_new(struct TreeNode *node, struct list_head *free_list) { /* Reusage in free node pool */ - struct bfs_node *new; + struct queue_node *qn; if (list_empty(free_list)) { - new = malloc(sizeof(*new)); + qn = malloc(sizeof(*qn)); } else { - new = list_first_entry(free_list, struct bfs_node, link); - list_del(&new->link); + qn = list_first_entry(free_list, struct queue_node, link); + list_del(&qn->link); } - new->node = node; - return new; + qn->node = node; + return qn; } -static void bfs(struct list_head *parents, struct list_head *children, - struct list_head *free_list, int *results, int *count) +static void node_free(struct queue_node *qn, struct list_head *free_list) { - struct list_head *p, *n; - list_for_each(p, parents) { - struct bfs_node *new; - struct bfs_node *parent = list_entry(p, struct bfs_node, link); - if (parent->node->right != NULL) { - new = node_new(free_list, parent->node->right); - list_add(&new->link, children); - } - if (parent->node->left != NULL) { - new = node_new(free_list, parent->node->left); - list_add(&new->link, children); - } - } - - int first = 1; - list_for_each_safe(p, n, parents) { - struct bfs_node *parent = list_entry(p, struct bfs_node, link); - if (first) { - first = 0; - results[(*count)++] = parent->node->val; - } - list_del(p); - list_add(p, free_list); - } + list_del(&qn->link); + list_add(&qn->link, free_list); } /** ** Return an array of arrays of size *returnSize. - ** The sizes of the arrays are returned as *columnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** The sizes of the arrays are returned as *returnColumnSizes array. + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ static int* rightSideView(struct TreeNode* root, int* returnSize) { @@ -129,29 +101,41 @@ static int* rightSideView(struct TreeNode* root, int* returnSize) return NULL; } - struct list_head q0; - struct list_head q1; + struct list_head q; struct list_head free_list; - INIT_LIST_HEAD(&q0); - INIT_LIST_HEAD(&q1); + INIT_LIST_HEAD(&q); INIT_LIST_HEAD(&free_list); - int level = 0; + int i, level = 0, level_size = 1; *returnSize = 0; int *results = malloc(BST_MAX_LEVEL * sizeof(int)); - struct bfs_node *new = node_new(&free_list, root); - list_add_tail(&new->link, &q0); - - /* Interleaving parent and children FIFO queues */ - while (!list_empty(&q0) || !list_empty(&q1)) { - if (level & 0x1) { - bfs(&q1, &q0, &free_list, results, returnSize); - } else { - bfs(&q0, &q1, &free_list, results, returnSize); + + /* Add root node */ + struct queue_node *new = node_new(root, &free_list); + list_add_tail(&new->link, &q); + + while (!list_empty(&q)) { + int size = level_size; + level_size = 0; + for (i = 0; i < size; i++) { + struct queue_node *qn = list_first_entry(&q, struct queue_node, link); + results[level] = qn->node->val; + if (qn->node->left != NULL) { + new = node_new(qn->node->left, &free_list); + list_add_tail(&new->link, &q); + level_size++; + } + if (qn->node->right != NULL) { + new = node_new(qn->node->right, &free_list); + list_add_tail(&new->link, &q); + level_size++; + } + node_free(qn, &free_list); } level++; } + *returnSize = level; return results; } diff --git a/0199_binary_tree_right_side_view/bst_right.cc b/0199_binary_tree_right_side_view/bst_right.cc new file mode 100644 index 0000000..20490cb --- /dev/null +++ b/0199_binary_tree_right_side_view/bst_right.cc @@ -0,0 +1,44 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + vector res; + if (root == nullptr) { + return res; + } + + queue q; + q.push(root); + while (!q.empty()) { + int rightest; + int size = q.size(); + for (int i = 0; i < size; i++) { + TreeNode *node = q.front(); + q.pop(); + rightest = node->val; + if (node->left != nullptr) { + q.push(node->left); + } + if (node->right != nullptr) { + q.push(node->right); + } + } + res.push_back(rightest); + } + return res; + } +}; From 5b8b6568d7e95ad91805029d0e05df72d18efde2 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 5 Jan 2021 13:37:18 +0800 Subject: [PATCH 130/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../tree_serdes.c | 53 +++++--------- .../tree_serdes.cc | 73 +++++++++++++++++++ 2 files changed, 92 insertions(+), 34 deletions(-) create mode 100644 0297_serialize_and_deserialize_binary_tree/tree_serdes.cc diff --git a/0297_serialize_and_deserialize_binary_tree/tree_serdes.c b/0297_serialize_and_deserialize_binary_tree/tree_serdes.c index 4ee15d7..e1e3f12 100644 --- a/0297_serialize_and_deserialize_binary_tree/tree_serdes.c +++ b/0297_serialize_and_deserialize_binary_tree/tree_serdes.c @@ -1,4 +1,4 @@ -#include +#include #include #include #include @@ -10,52 +10,37 @@ struct TreeNode { struct TreeNode *right; }; +static int count = 0; +static int SYM_NULL = INT_MIN; + static void ser(struct TreeNode *root, char **str, int *len) { if (root == NULL) { - (*str)[(*len)++] = '#'; - (*str)[(*len)++] = ','; + memcpy(str + *len, &SYM_NULL, sizeof(int)); + (*len) += sizeof(int); } else { - int v = root->val; - if (v < 0) { - v = -v; - (*str)[(*len)++] = '-'; - } - while (v > 0) { - (*str)[(*len)++] = v % 10 + '0'; - v /= 10; - } - (*str)[(*len)++] = ','; + memcpy(str + *len, &root->val, sizeof(int)); + (*len) += sizeof(int); ser(root->left, str, len); ser(root->right, str, len); } + count++; } -static struct TreeNode *des(char **str) { - if (**str == '\0') { +static struct TreeNode *des(char **str) +{ + if (count == 0) { return NULL; } - if (**str == '#') { - (*str)++; - (*str)++; + count--; + + int value; + memcpy(&value, *str, sizeof(int)); + (*str) += sizeof(int); + if (value == SYM_NULL) { return NULL; } - - int i; - bool sign = false; struct TreeNode *node = malloc(sizeof(struct TreeNode)); - node->val = 0; - if (**str == '-') { - sign = true; - (*str)++; - } - for (i = 1; **str != ','; i *= 10) { - node->val += i * ((**str) - '0'); - (*str)++; - } - if (sign) { - node->val = -node->val; - } - (*str)++; + node->val = value; node->left = des(str); node->right = des(str); return node; diff --git a/0297_serialize_and_deserialize_binary_tree/tree_serdes.cc b/0297_serialize_and_deserialize_binary_tree/tree_serdes.cc new file mode 100644 index 0000000..08b9898 --- /dev/null +++ b/0297_serialize_and_deserialize_binary_tree/tree_serdes.cc @@ -0,0 +1,73 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + string res; + ser(root, res); + return res; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + int len = data.length(); + return des(data.c_str(), &len); + } + +private: + void ser(TreeNode* root, string& res) { + if (root == nullptr) { + res.push_back((char) 0x80); + res.push_back((char) 0x00); + res.push_back((char) 0x00); + res.push_back((char) 0x00); + return; + } + + ser(root->left, res); + ser(root->right, res); + + for (int i = sizeof(int) - 1; i >= 0; i--) { + res.push_back(((char *)&root->val)[i]); + } + } + + TreeNode* des(const char *data, int *len) { + if (*len == 0) { + return nullptr; + } + + int value; + const char *s = data + *len - 1; + for (int i = 0; i < sizeof(int); i++) { + ((char *)&value)[i] = *s--; + } + if (value == INT_MIN) { + (*len) -= sizeof(int); + return nullptr; + } + (*len) -= sizeof(int); + + TreeNode *root = new TreeNode(value); + root->right = des(data, len); + root->left = des(data, len); + return root; + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec ser, deser; +// TreeNode* ans = deser.deserialize(ser.serialize(root)); From ced1a264aac17216b88a258e0c734d6c8064c588 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 10 Jan 2021 18:56:00 +0800 Subject: [PATCH 131/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../intersection.c | 24 +++++----- .../intersection.cc | 44 +++++++++++++++++++ 2 files changed, 58 insertions(+), 10 deletions(-) create mode 100644 0160_intersection_of_two_linked_list/intersection.cc diff --git a/0160_intersection_of_two_linked_list/intersection.c b/0160_intersection_of_two_linked_list/intersection.c index d33de4f..def9953 100644 --- a/0160_intersection_of_two_linked_list/intersection.c +++ b/0160_intersection_of_two_linked_list/intersection.c @@ -9,23 +9,27 @@ struct ListNode { static struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { + if (headA == NULL || headB == NULL) { + return NULL; + } + struct ListNode *p; for (p = headA; p->next != NULL; p = p->next) {} p->next = headB; - bool first = true; - struct ListNode *p0, *p1; - for (p0 = headA, p1 = headA; p1 != NULL && p1->next != NULL; p0 = p0->next, p1 = p1->next->next) { - if (p0 == p1 && !first) { - p0 = headA; - while (p0 != p1) { - p0 = p0->next; - p1 = p1->next; + struct ListNode *slow = headA, *fast = headA; + while (fast != NULL && fast->next != NULL) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + slow = headA; + while (slow != fast) { + slow = slow->next; + fast = fast->next; } p->next = NULL; - return p0; + return slow; } - first = false; } p->next = NULL; diff --git a/0160_intersection_of_two_linked_list/intersection.cc b/0160_intersection_of_two_linked_list/intersection.cc new file mode 100644 index 0000000..0d4c957 --- /dev/null +++ b/0160_intersection_of_two_linked_list/intersection.cc @@ -0,0 +1,44 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + int lenA = getListLength(headA); + int lenB = getListLength(headB); + if (lenA > lenB) { + for (int i = 0; i < lenA - lenB; i++) { + headA = headA->next; + } + } else { + for (int i = 0; i < lenB - lenA; i++) { + headB = headB->next; + } + } + + while (headA != nullptr && headB != nullptr && headA != headB) { + headA = headA->next; + headB = headB->next; + } + + return headA; + } +private: + int getListLength(ListNode *h) { + int len = 0; + while (h != nullptr) { + len++; + h = h->next; + } + return len; + } +}; From dec7504fc3c5e3fb962738880fb17b9116e45a1b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 11 Jan 2021 16:15:43 +0800 Subject: [PATCH 132/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0096_unique_binary_search_trees/unique_bst.cc | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 0096_unique_binary_search_trees/unique_bst.cc diff --git a/0096_unique_binary_search_trees/unique_bst.cc b/0096_unique_binary_search_trees/unique_bst.cc new file mode 100644 index 0000000..5aa3a55 --- /dev/null +++ b/0096_unique_binary_search_trees/unique_bst.cc @@ -0,0 +1,20 @@ +#include + +using namespace std; + +/* + * f(n) = f(0)f(n-1) + f(1)f(n-2) + ... + f(n-2)f(1) + f(n-1)f(0) + */ +class Solution { +public: + int numTrees(int n) { + vector sum(n + 1); + sum[0] = 1; + for (int i = 1; i <= n; i++) { + for (int j = 0; j < i; j++) { + sum[i] += sum[j] * sum[i - j - 1]; + } + } + return sum[n]; + } +} From 158c1ffe150bbc68f6e68c4e6712997babf33eea Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 12 Jan 2021 10:53:36 +0800 Subject: [PATCH 133/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0039_combination_sum/combination_sum.cc | 8 +++--- 0040_combination_sum_ii/combination_sum.c | 2 +- 0040_combination_sum_ii/combination_sum.cc | 10 ++++---- 0046_permutations/permutations.cc | 8 +++--- 0047_permutations_ii/permutations.c | 3 ++- 0047_permutations_ii/permutations.cc | 13 +++++----- 0077_combinations/combinations.c | 13 +++++++--- 0077_combinations/combinations.cc | 8 +++--- 0078_subsets/subsets.cc | 8 +++--- 0090_subsets_ii/subsets.cc | 10 ++++---- 0216_combination_sum_iii/combination_sum.cc | 27 +++++++++++++++++++++ 11 files changed, 72 insertions(+), 38 deletions(-) create mode 100644 0216_combination_sum_iii/combination_sum.cc diff --git a/0039_combination_sum/combination_sum.cc b/0039_combination_sum/combination_sum.cc index 11afede..a45abf8 100644 --- a/0039_combination_sum/combination_sum.cc +++ b/0039_combination_sum/combination_sum.cc @@ -5,14 +5,14 @@ using namespace std; class Solution { public: vector> combinationSum(vector& candidates, int target) { - vector stack; vector> res; - dfs(candidates, 0, target, stack, res); + dfs(candidates, 0, target, res); return res; } private: - void dfs(vector& candidates, int start, int target, vector& stack, vector>& res) { + vector stack; + void dfs(vector& candidates, int start, int target, vector>& res) { if (target < 0) { return; } else if (target == 0) { @@ -21,7 +21,7 @@ class Solution { 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 */ - dfs(candidates, i, target - candidates[i], stack, res); + dfs(candidates, i, target - candidates[i], res); stack.pop_back(); } } diff --git a/0040_combination_sum_ii/combination_sum.c b/0040_combination_sum_ii/combination_sum.c index b49ea54..13ffe7d 100644 --- a/0040_combination_sum_ii/combination_sum.c +++ b/0040_combination_sum_ii/combination_sum.c @@ -25,7 +25,7 @@ static void dfs(int *nums, int size, int start, int target, int *solution, int last = INT_MIN; for (i = start; i < size; i++) { if (last != nums[i]) { - /* No duplicate combinations in different order */ + /* No duplicate combinations in the same level position */ solution[len] = nums[i]; /* i + 1 limits the candidate range in next levels */ dfs(nums, size, i + 1, target - nums[i], solution, len + 1, results, count, column_sizes); diff --git a/0040_combination_sum_ii/combination_sum.cc b/0040_combination_sum_ii/combination_sum.cc index c74461f..277b432 100644 --- a/0040_combination_sum_ii/combination_sum.cc +++ b/0040_combination_sum_ii/combination_sum.cc @@ -5,15 +5,15 @@ using namespace std; class Solution { public: vector> combinationSum2(vector& candidates, int target) { - vector stack; vector> res; sort(candidates.begin(), candidates.end()); - dfs(candidates, 0, target, stack, res); + dfs(candidates, 0, target, res); return res; } private: - void dfs(vector& candidates, int start, int target, vector& stack, vector>& res) { + vector stack; + void dfs(vector& candidates, int start, int target, vector>& res) { if (target < 0) { return; } else if (target == 0) { @@ -22,10 +22,10 @@ class Solution { int last = INT_MIN; for (int i = start; i < candidates.size(); i++) { if (last != candidates[i]) { - /* No duplicate combinations in different order */ + /* No duplicate combinations in the same level position */ stack.push_back(candidates[i]); /* i + 1 limits the candidate range in next levels */ - dfs(candidates, i + 1, target - candidates[i], stack, res); + dfs(candidates, i + 1, target - candidates[i], res); stack.pop_back(); } last = candidates[i]; diff --git a/0046_permutations/permutations.cc b/0046_permutations/permutations.cc index 2f33cab..acef735 100644 --- a/0046_permutations/permutations.cc +++ b/0046_permutations/permutations.cc @@ -6,14 +6,14 @@ class Solution { public: vector> permute(vector& nums) { vector> res; - vector stack; vector used(nums.size()); - dfs(nums, used, stack, res); + dfs(nums, used, res); return res; } private: - void dfs(vector& nums, vector& used, vector& stack, vector>& res) { + vector stack; + void dfs(vector& nums, vector& used, vector>& res) { if (stack.size() == nums.size()) { res.push_back(stack); } else { @@ -23,7 +23,7 @@ class Solution { // Used marks only allows remaining elements in DFS levels used[i] = true; stack.push_back(nums[i]); - dfs(nums, used, stack, res); + 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 a666bdc..13d2fe4 100644 --- a/0047_permutations_ii/permutations.c +++ b/0047_permutations_ii/permutations.c @@ -23,7 +23,8 @@ static void dfs(int *nums, int size, bool *used, int *stack, /* 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 that duplicate permutation with same elemements but in different postions */ + /* In case duplicate permutation with same elemements in the same postion */ + /* used[i - 1] == true means different level position */ continue; } used[i] = true; diff --git a/0047_permutations_ii/permutations.cc b/0047_permutations_ii/permutations.cc index 389df2b..70c3e46 100644 --- a/0047_permutations_ii/permutations.cc +++ b/0047_permutations_ii/permutations.cc @@ -6,15 +6,15 @@ class Solution { public: vector> permuteUnique(vector& nums) { vector> res; - vector stack; vector used(nums.size()); sort(nums.begin(), nums.end()); - dfs(nums, used, stack, res); + dfs(nums, used, res); return res; } private: - void dfs(vector& nums, vector& used, vector& stack, vector>& res) { + vector stack; + void dfs(vector& nums, vector& used, vector>& res) { if (stack.size() == nums.size()) { res.push_back(stack); } else { @@ -22,12 +22,13 @@ class Solution { // 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 that duplicate permutation with same elemements but in different postions + // In case duplicate permutation with same elemements in the same postion + // used[i - 1] == true means different level position continue; } - used[i] = true; stack.push_back(nums[i]); - dfs(nums, used, stack, res); + used[i] = true; + dfs(nums, used, res); stack.pop_back(); used[i] = false; } diff --git a/0077_combinations/combinations.c b/0077_combinations/combinations.c index d184521..fcf614c 100644 --- a/0077_combinations/combinations.c +++ b/0077_combinations/combinations.c @@ -27,12 +27,10 @@ static void dfs(int n, int k, int start, int *stack, int len, */ int** combine(int n, int k, int* returnSize, int** returnColumnSizes) { int capacity = 10000; - int count = 0; int **results = malloc(capacity * sizeof(int *)); int *stack = malloc(k * sizeof(int)); *returnColumnSizes = malloc(capacity * sizeof(int)); - dfs(n, k, 1, stack, 0, results, &count, *returnColumnSizes); - *returnSize = count; + dfs(n, k, 1, stack, 0, results, returnSize, *returnColumnSizes); return results; } @@ -43,8 +41,15 @@ int main(int argc, char **argv) exit(-1); } + int n = atoi(argv[1]); + int k = atoi(argv[2]); + if (k > n) { + fprintf(stderr, "n(=%d) must larger than k(=%d)\n", n, k); + exit(-1); + } + int i, j, *col_sizes, count = 0; - int **lists = combine(atoi(argv[1]), atoi(argv[2]), &count, &col_sizes); + int **lists = combine(n, k, &count, &col_sizes); for (i = 0; i < count; i++) { for (j = 0; j < col_sizes[i]; j++) { printf("%d ", lists[i][j]); diff --git a/0077_combinations/combinations.cc b/0077_combinations/combinations.cc index 7687061..1aabf42 100644 --- a/0077_combinations/combinations.cc +++ b/0077_combinations/combinations.cc @@ -6,19 +6,19 @@ class Solution { public: vector> combine(int n, int k) { vector> res; - vector stack; - dfs(n, k, 1, stack, res); + dfs(n, k, 1, res); return res; } private: - void dfs(int n, int k, int start, vector& stack, vector>& res) { + vector stack; + void dfs(int n, int k, int start, vector>& res) { if (stack.size() == k) { res.push_back(stack); } else { for (int i = start; i <= n; i++) { stack.push_back(i); - dfs(n, k, i + 1, stack, res); + dfs(n, k, i + 1, res); stack.pop_back(); } } diff --git a/0078_subsets/subsets.cc b/0078_subsets/subsets.cc index 5d10d7e..c6593d2 100644 --- a/0078_subsets/subsets.cc +++ b/0078_subsets/subsets.cc @@ -6,17 +6,17 @@ class Solution { public: vector> subsets(vector& nums) { vector> res; - vector stack; - dfs(nums, 0, stack, res); + dfs(nums, 0, res); return res; } private: - void dfs(vector& nums, int start, vector& stack, vector>& res) { + vector stack; + void dfs(vector& nums, int start, vector>& res) { res.push_back(stack); for (int i = start; i < nums.size(); i++) { stack.push_back(nums[i]); - dfs(nums, i + 1, stack, res); + dfs(nums, i + 1, res); stack.pop_back(); } } diff --git a/0090_subsets_ii/subsets.cc b/0090_subsets_ii/subsets.cc index f5ae3e9..d6ee1da 100644 --- a/0090_subsets_ii/subsets.cc +++ b/0090_subsets_ii/subsets.cc @@ -6,21 +6,21 @@ class Solution { public: vector> subsetsWithDup(vector& nums) { vector> res; - vector stack; sort(nums.begin(), nums.end()); - dfs(nums, 0, stack, res); + dfs(nums, 0, res); return res; } private: - void dfs(vector& nums, int start, vector& stack, vector>& res) { + vector stack; + void dfs(vector& nums, int start, vector>& res) { res.push_back(stack); int last = INT_MIN; for (int i = start; i < nums.size(); i++) { if (last != nums[i]) { - /* No duplicate candidate elements at same level position */ + /* No duplicate candidate elements in the same level position */ stack.push_back(nums[i]); - dfs(nums, i + 1, stack, res); + dfs(nums, i + 1, res); stack.pop_back(); } last = nums[i]; diff --git a/0216_combination_sum_iii/combination_sum.cc b/0216_combination_sum_iii/combination_sum.cc new file mode 100644 index 0000000..40189b1 --- /dev/null +++ b/0216_combination_sum_iii/combination_sum.cc @@ -0,0 +1,27 @@ +#include + +using namespace std; + +class Solution { +public: + vector> combinationSum3(int k, int n) { + vector> res; + dfs(1, 9, k, n, res); + return res; + } +private: + vector stack; + void dfs(int start, int size, int k, int target, vector>& res) { + if (stack.size() == k) { + if (target == 0) { + res.push_back(stack); + } + } else { + for (int i = start; i <= size; i++) { + stack.push_back(i); + dfs(i + 1, size, k, target - i, res); + stack.pop_back(); + } + } + } +}; From 3796b8afa06f45826ca163881a6761621f62dc90 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 13 Jan 2021 09:54:19 +0800 Subject: [PATCH 134/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0022_generate_parathesis/young_tableau.cc | 60 +++++++++++++++++++++++ 0048_rotate_image/rotate.cc | 2 +- 0322_coin_change/coin_change.cc | 6 +-- 3 files changed, 64 insertions(+), 4 deletions(-) create mode 100644 0022_generate_parathesis/young_tableau.cc diff --git a/0022_generate_parathesis/young_tableau.cc b/0022_generate_parathesis/young_tableau.cc new file mode 100644 index 0000000..04ffc7d --- /dev/null +++ b/0022_generate_parathesis/young_tableau.cc @@ -0,0 +1,60 @@ +#include +#include +#include + + +using namespace std; + +class Solution { +public: + vector> young_tableau(int n) { + vector> res; + dfs(n, 0, 0, res); + return res; + } + +private: + vector stack; + + void dfs(int n, int l, int r, vector>& res) { + if (stack.size() == 2 * n) { + vector sol(2 * n); + for (int i = 0, j = 0, k = n; i < 2 * n; i++) { + if (stack[i] == '(') { + sol[j++] = i + 1; + } else { + sol[k++] = i + 1; + } + } + res.push_back(sol); + } else { + if (l < n) { + stack.push_back('('); + dfs(n, l + 1, r, res); + stack.pop_back(); + } + + if (r < l) { + stack.push_back(')'); + dfs(n, l, r + 1, res); + stack.pop_back(); + } + } + } +}; + +int main(int argc, char **argv) +{ + int n = atoi(argv[1]); + Solution *solution = new Solution(); + vector> res = solution->young_tableau(n); + for (auto& v : res) { + for (int i = 0; i < 2 * n; i++) { + if (i == n) cout << endl; + cout << v[i] << ' '; + } + cout << endl; + } + + return 0; +} diff --git a/0048_rotate_image/rotate.cc b/0048_rotate_image/rotate.cc index e1e9950..806e151 100644 --- a/0048_rotate_image/rotate.cc +++ b/0048_rotate_image/rotate.cc @@ -15,6 +15,6 @@ class Solution { matrix[size - 1 - i][size - 1 - j] = matrix[j][size - 1 - i]; matrix[j][size - 1 - i] = tmp; } - } + } } }; diff --git a/0322_coin_change/coin_change.cc b/0322_coin_change/coin_change.cc index 4b2fa6e..31ddb51 100644 --- a/0322_coin_change/coin_change.cc +++ b/0322_coin_change/coin_change.cc @@ -19,7 +19,7 @@ class Solution { #else // BFS solution is slow... queue q; - unordered_set s; + unordered_set visited; int step = 0; q.push(amount); while (!q.empty()) { @@ -31,8 +31,8 @@ class Solution { for (int coin : coins) { int n = q.front() - coin; if (n >= 0) { - if (s.count(n) == 0) { - s.insert(n); + if (visited.count(n) == 0) { + visited.insert(n); q.push(n); } } From 63381085bdca1d16d7a9e0aea02b015f3df7e8b8 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 14 Jan 2021 23:56:49 +0800 Subject: [PATCH 135/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0567_permutation_in_string/Makefile | 2 + .../permutation_in_string.c | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 0567_permutation_in_string/Makefile create mode 100644 0567_permutation_in_string/permutation_in_string.c diff --git a/0567_permutation_in_string/Makefile b/0567_permutation_in_string/Makefile new file mode 100644 index 0000000..34c55c8 --- /dev/null +++ b/0567_permutation_in_string/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test permutation_in_string.c diff --git a/0567_permutation_in_string/permutation_in_string.c b/0567_permutation_in_string/permutation_in_string.c new file mode 100644 index 0000000..a20fa55 --- /dev/null +++ b/0567_permutation_in_string/permutation_in_string.c @@ -0,0 +1,44 @@ +#include +#include +#include +#include + + +bool checkInclusion(char * s1, char * s2) +{ + int i, count[128] = { -1 }, pat_len = 0; + for (i = 0; s1[i] != '\0'; i++) { + count[s1[i]]++; + pat_len++; + } + + 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) { + return true; + } + if (++count[s2[l++]] > 0) { + len--; + } + } + } + + return false; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test string pattern\n"); + exit(-1); + } + + char *t = argv[1]; + char *s = argv[2]; + printf("%s\n", checkInclusion(t, s) ? "true" : "false"); + return 0; +} From 97ff3afdbee3ba321ab6fff536e929028d091087 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 15 Jan 2021 20:06:36 +0800 Subject: [PATCH 136/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0438_find_all_anagrams_in_a_string/Makefile | 2 + .../anagrams_in_string.c | 53 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 0438_find_all_anagrams_in_a_string/Makefile create mode 100644 0438_find_all_anagrams_in_a_string/anagrams_in_string.c diff --git a/0438_find_all_anagrams_in_a_string/Makefile b/0438_find_all_anagrams_in_a_string/Makefile new file mode 100644 index 0000000..99bb57e --- /dev/null +++ b/0438_find_all_anagrams_in_a_string/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test anagrams_in_string.c 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 new file mode 100644 index 0000000..9a3ec67 --- /dev/null +++ b/0438_find_all_anagrams_in_a_string/anagrams_in_string.c @@ -0,0 +1,53 @@ +#include +#include + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +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 }; + 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) { + res[(*returnSize)++] = l; + } + if (++count[s[l++]] > 0) { + len--; + } + } + } + + return res; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test string pattern\n"); + exit(-1); + } + + char *t = argv[1]; + char *s = argv[2]; + int i, count; + int *results = findAnagrams(s, t, &count); + for (i = 0; i < count; i++) { + printf("%d ", results[i]); + } + printf("\n"); + + return 0; +} From 5fd56b75db29a67a39bcfb439886b1bd2b79fbdf Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 16 Jan 2021 23:33:01 +0800 Subject: [PATCH 137/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../anagrams_in_string.cc | 32 +++++++++++++++++++ .../permutation_in_string.cc | 31 ++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 0438_find_all_anagrams_in_a_string/anagrams_in_string.cc create mode 100644 0567_permutation_in_string/permutation_in_string.cc diff --git a/0438_find_all_anagrams_in_a_string/anagrams_in_string.cc b/0438_find_all_anagrams_in_a_string/anagrams_in_string.cc new file mode 100644 index 0000000..7a50a3c --- /dev/null +++ b/0438_find_all_anagrams_in_a_string/anagrams_in_string.cc @@ -0,0 +1,32 @@ +#include + +using namespace std; + +class Solution { +public: + vector findAnagrams(string s, string p) { + int count[128] = { 0 }; + for (char c : p) { + count[c]++; + } + + vector res; + int l = 0, r = 0, len = 0; + while (r < s.length()) { + if (--count[s[r++]] >= 0) { + len++; + } + + if (r - l >= p.length()) { + if (len == p.length()) { + res.push_back(l); + } + if (++count[s[l++]] > 0) { + len--; + } + } + } + + return res; + } +}; diff --git a/0567_permutation_in_string/permutation_in_string.cc b/0567_permutation_in_string/permutation_in_string.cc new file mode 100644 index 0000000..541b1cb --- /dev/null +++ b/0567_permutation_in_string/permutation_in_string.cc @@ -0,0 +1,31 @@ +#include + +using namespace std; + +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int count[128] = { 0 }; + for (char c : s1) { + count[c]++; + } + + int l = 0, r = 0, len = 0; + while (r < s2.length()) { + if (--count[s2[r++]] >= 0) { + len++; + } + + if (r - l >= s1.length()) { + if (len == s1.length()) { + return true; + } + if (++count[s2[l++]] > 0) { + len--; + } + } + } + + return false; + } +}; From 668052ecc3360da226d065bccd76d1e11b670ea0 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 17 Jan 2021 22:44:17 +0800 Subject: [PATCH 138/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../connect.c | 20 +++++---- .../connect.cc | 41 +++++++++++++++++++ 2 files changed, 52 insertions(+), 9 deletions(-) create mode 100644 0116_populating_next_right_pointers_in_each_node/connect.cc diff --git a/0116_populating_next_right_pointers_in_each_node/connect.c b/0116_populating_next_right_pointers_in_each_node/connect.c index 728a0be..16fbfe3 100644 --- a/0116_populating_next_right_pointers_in_each_node/connect.c +++ b/0116_populating_next_right_pointers_in_each_node/connect.c @@ -1,33 +1,35 @@ #include #include -struct TreeLinkNode { + +struct Node { int val; - struct TreeLinkNode *left; - struct TreeLinkNode *right; - struct TreeLinkNode *next; + struct Node *left; + struct Node *right; + struct Node *next; }; -static void connect(struct TreeLinkNode *root) +struct Node* connect(struct Node *root) { if (root == NULL) { - return; + return root; } - struct TreeLinkNode *head = root; + struct Node *head = root; while (head->left != NULL) { - struct TreeLinkNode *p; + struct Node *p; for (p = head; p != NULL; p = p->next) { p->left->next = p->right; p->right->next = p->next == NULL ? NULL : p->next->left; } head = head->left; } + return root; } int main(int argc, char **argv) { - struct TreeLinkNode root, n1[2], n2[4], n3[8]; + struct Node root, n1[2], n2[4], n3[8]; root.val = 5; n1[0].val = 4; n1[1].val = 8; diff --git a/0116_populating_next_right_pointers_in_each_node/connect.cc b/0116_populating_next_right_pointers_in_each_node/connect.cc new file mode 100644 index 0000000..1222b9d --- /dev/null +++ b/0116_populating_next_right_pointers_in_each_node/connect.cc @@ -0,0 +1,41 @@ +#include + +using namespace std; + +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (root == nullptr) { + return root; + } + + if (root->left != nullptr) { + root->left->next = root->right; + } + Node *next = root->next; + if (root->right != nullptr && next != nullptr) { + root->right->next = next->left; + } + connect(root->left); + connect(root->right); + return root; + } +}; From d5f5f9794207fec964168750996cdec604d14b06 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 18 Jan 2021 21:18:38 +0800 Subject: [PATCH 139/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0204_count_primes/count_primes.c | 10 ++++++---- 0204_count_primes/count_primes.cc | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 0204_count_primes/count_primes.cc diff --git a/0204_count_primes/count_primes.c b/0204_count_primes/count_primes.c index f64c6e6..69b4bef 100644 --- a/0204_count_primes/count_primes.c +++ b/0204_count_primes/count_primes.c @@ -1,12 +1,14 @@ #include #include #include -#include -static int countPrimes(int n) + +int countPrimes(int n) { - if (n < 3) return 0; - + if (n < 3) { + return 0; + } + int i, j; bool *marked = malloc(n); memset(marked, false, n); diff --git a/0204_count_primes/count_primes.cc b/0204_count_primes/count_primes.cc new file mode 100644 index 0000000..20b752c --- /dev/null +++ b/0204_count_primes/count_primes.cc @@ -0,0 +1,26 @@ +#include + +using namespace std; + +class Solution { +public: + int countPrimes(int n) { + if (n < 3) { + return 0; + } + + vector marked(n); + int count = n >> 1; + for (int i = 3; i * i <= n; i += 2) { + if (!marked[i]) { + for (int j = i * i; j < n; j += (i << 1)) { + if (!marked[j]) { + marked[j] = true; + --count; + } + } + } + } + return count; + } +}; From e838cd23fa4d101effb2c1de823305806d98a9b9 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 19 Jan 2021 22:28:31 +0800 Subject: [PATCH 140/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../stock.cc | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 0123_best_time_to_buy_and_sell_stock_iii/stock.cc diff --git a/0123_best_time_to_buy_and_sell_stock_iii/stock.cc b/0123_best_time_to_buy_and_sell_stock_iii/stock.cc new file mode 100644 index 0000000..3be2669 --- /dev/null +++ b/0123_best_time_to_buy_and_sell_stock_iii/stock.cc @@ -0,0 +1,42 @@ +#include + +using namespace std; + +class Solution { +public: + int maxProfit(vector& prices) { + if (prices.size() == 0) { + return 0; + } + + int max_diff = 0; + int min_price = prices[0]; + vector left_profits(prices.size()); + for (int i = 1; i < prices.size(); i++) { + if (prices[i] < min_price) { + min_price = prices[i]; + } else { + int diff = prices[i] - min_price; + max_diff = max(diff, max_diff); + } + left_profits[i] = max_diff; + } + + int total = 0; + max_diff = 0; + int right_profit = 0; + int max_price = prices[prices.size() - 1]; + for (int i = prices.size() - 2; i >= 0; i--) { + if (prices[i] > max_price) { + max_price = prices[i]; + } else { + int diff = max_price - prices[i]; + right_profit = max(diff, right_profit); + } + int profit = left_profits[i] + right_profit; + total = max(profit, total); + } + + return total; + } +}; From 60b83886ca0ed7a66f2e13f132f0f1c7f125ca22 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 20 Jan 2021 21:49:04 +0800 Subject: [PATCH 141/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../bst_lca.c | 2 +- .../bst_lca.cc | 28 +++++++++++++++++++ .../bst_lca.c | 2 +- .../bst_lca.cc | 28 +++++++++++++++++++ 4 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.cc create mode 100644 0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.cc diff --git a/0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c b/0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c index 502863a..aecdf1c 100644 --- a/0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c +++ b/0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.c @@ -8,7 +8,7 @@ struct TreeNode { struct TreeNode *right; }; -static struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) +struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { if (root == NULL || root->val == p->val || root->val == q->val) { return root; diff --git a/0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.cc b/0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.cc new file mode 100644 index 0000000..82fbf71 --- /dev/null +++ b/0235_lowest_common_ancestor_of_a_binary_search_tree/bst_lca.cc @@ -0,0 +1,28 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == nullptr || root->val == p->val || root->val == q->val) { + return root; + } else if (root->val < p->val && root->val < q->val) { + return lowestCommonAncestor(root->right, p, q); + } else if (root->val > p->val && root->val > q->val) { + return lowestCommonAncestor(root->left, p, q); + } else { + return root; + } + } +}; diff --git a/0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c b/0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c index 30afec2..4eefea8 100644 --- a/0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c +++ b/0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.c @@ -9,7 +9,7 @@ struct TreeNode { struct TreeNode *right; }; -static struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) +struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { if (root == NULL || root == p || root == q) { /* edge cases: if return NULL then no p or q node in this path */ diff --git a/0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.cc b/0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.cc new file mode 100644 index 0000000..96caff4 --- /dev/null +++ b/0236_lowest_common_ancestor_of_a_binary_tree/bst_lca.cc @@ -0,0 +1,28 @@ +#include + +using namespace std; + /** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == nullptr || root == p || root == q) { + return root; + } + + TreeNode *l = lowestCommonAncestor(root->left, p, q); + TreeNode *r = lowestCommonAncestor(root->right, p, q); + if (l != nullptr && r != nullptr) { + return root; + } else { + return l != nullptr ? l : r; + } + } +}; From a1c864996f6e2107b2f11517c1c284682bc8fe25 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 21 Jan 2021 23:05:45 +0800 Subject: [PATCH 142/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0054_spiral_matrix/spiral_matrix.c | 3 +- 0054_spiral_matrix/spiral_matrix.cc | 11 ++---- 0059_spiral_matrix_ii/spiral_matrix.c | 2 +- 0059_spiral_matrix_ii/spiral_matrix.cc | 47 ++++++++++++++++++++++++++ 4 files changed, 53 insertions(+), 10 deletions(-) create mode 100644 0059_spiral_matrix_ii/spiral_matrix.cc diff --git a/0054_spiral_matrix/spiral_matrix.c b/0054_spiral_matrix/spiral_matrix.c index be53988..5ae413f 100644 --- a/0054_spiral_matrix/spiral_matrix.c +++ b/0054_spiral_matrix/spiral_matrix.c @@ -1,10 +1,11 @@ #include #include + /** ** Note: The returned array must be malloced, assume caller calls free(). **/ -static int* spiralOrder(int** matrix, int matrixSize, int *matrixColSize, int *returnSize) +int* spiralOrder(int** matrix, int matrixSize, int *matrixColSize, int *returnSize) { if (matrixSize == 0) { *returnSize = 0; diff --git a/0054_spiral_matrix/spiral_matrix.cc b/0054_spiral_matrix/spiral_matrix.cc index f155dc3..b411d33 100644 --- a/0054_spiral_matrix/spiral_matrix.cc +++ b/0054_spiral_matrix/spiral_matrix.cc @@ -5,17 +5,12 @@ using namespace std; class Solution { public: vector spiralOrder(vector>& matrix) { - if (matrix.empty()) { - return vector(); - } - + vector res; int hor_top = 0; - int hor_bottom = matrix.size(); + int hor_bottom = matrix.size() - 1; int ver_left = 0; - int ver_right = matrix[0].size(); + int ver_right = matrix[0].size() - 1; int direction = 0; - vector res; - while (hor_top <= hor_bottom && ver_left <= ver_right) { switch (direction) { case 0: diff --git a/0059_spiral_matrix_ii/spiral_matrix.c b/0059_spiral_matrix_ii/spiral_matrix.c index 18da9e0..d85769f 100644 --- a/0059_spiral_matrix_ii/spiral_matrix.c +++ b/0059_spiral_matrix_ii/spiral_matrix.c @@ -7,7 +7,7 @@ * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ -static int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) +int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) { int i; int **matrix = malloc(n * sizeof(int *)); diff --git a/0059_spiral_matrix_ii/spiral_matrix.cc b/0059_spiral_matrix_ii/spiral_matrix.cc new file mode 100644 index 0000000..47d658a --- /dev/null +++ b/0059_spiral_matrix_ii/spiral_matrix.cc @@ -0,0 +1,47 @@ +#include + +using namespace std; + +class Solution { +public: + vector> generateMatrix(int n) { + vector> matrix(n, vector(n)); + int direction = 0; + int hor_top = 0; + int hor_bottom = n - 1; + int ver_left = 0; + int ver_right = n - 1; + int num = 0; + while (num < n * n) { + switch (direction) { + case 0: + for (int i = ver_left; i <= ver_right; i++) { + matrix[hor_top][i] = ++num; + } + hor_top++; + break; + case 1: + for (int i = hor_top; i <= hor_bottom; i++) { + matrix[i][ver_right] = ++num; + } + ver_right--; + break; + case 2: + for (int i = ver_right; i >= ver_left; i--) { + matrix[hor_bottom][i] = ++num; + } + hor_bottom--; + break; + case 3: + for (int i = hor_bottom; i >= hor_top; i--) { + matrix[i][ver_left] = ++num; + } + ver_left++; + break; + } + direction++; + direction %= 4; + } + return matrix; + } +}; From a50284190a7ba94fac5131c0ee8a42e0220b6abc Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 22 Jan 2021 23:13:31 +0800 Subject: [PATCH 143/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0061_rotate_list/rotate_list.c | 31 ++++++++++----------- 0061_rotate_list/rotate_list.cc | 48 +++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 17 deletions(-) create mode 100644 0061_rotate_list/rotate_list.cc diff --git a/0061_rotate_list/rotate_list.c b/0061_rotate_list/rotate_list.c index 9f8eb56..ae77398 100644 --- a/0061_rotate_list/rotate_list.c +++ b/0061_rotate_list/rotate_list.c @@ -1,31 +1,29 @@ #include #include + struct ListNode { int val; struct ListNode *next; }; -static struct ListNode* rotateRight(struct ListNode* head, int k) +struct ListNode* rotateRight(struct ListNode* head, int k) { - if (head == NULL || k <= 0) { + if (head == NULL) { return head; } + int len = 0; struct ListNode dummy; dummy.next = head; - struct ListNode *prev = &dummy; - struct ListNode *p = head; - int len = 0; - while (p != NULL) { - prev = p; - p = p->next; + struct ListNode *tail = &dummy; + while (tail->next != NULL) { + tail = tail->next; len++; } - struct ListNode *last = prev; - prev = &dummy; - p = head; + struct ListNode *prev = &dummy; + struct ListNode *p = head; len = len - (k % len); while (len-- > 0) { prev = p; @@ -36,23 +34,22 @@ static struct ListNode* rotateRight(struct ListNode* head, int k) /* deletion */ prev->next = NULL; /* insertion */ - last->next = dummy.next; - dummy.next = p; + tail->next = head; + head = p; } - return dummy.next; + return head; } int main(int argc, char **argv) { - int i; - struct ListNode *p, *prev, dummy, *list; - if (argc < 2) { fprintf(stderr, "Usage: ./test k n1 n2...\n"); exit(-1); } + int i; + struct ListNode *p, *prev, dummy, *list; dummy.next = NULL; prev = &dummy; for (i = 2; i < argc; i++) { diff --git a/0061_rotate_list/rotate_list.cc b/0061_rotate_list/rotate_list.cc new file mode 100644 index 0000000..e533c21 --- /dev/null +++ b/0061_rotate_list/rotate_list.cc @@ -0,0 +1,48 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* rotateRight(ListNode* head, int k) { + if (head == nullptr) { + return head; + } + + int len = 0; + ListNode dummy; + dummy.next = head; + ListNode *tail = &dummy; + while (tail->next != nullptr) { + len++; + tail = tail->next; + } + + ListNode *prev = &dummy; + ListNode *p = head; + k = k % len; + for (int i = 0; i < len - k; i++) { + prev = p; + p = p->next; + } + + if (p != nullptr) { + /* deletion */ + prev->next = tail->next; + /* insertion */ + tail->next = head; + head = p; + } + return head; + } +}; From c69b910b1e37bd1e019673ebd730c39fe6aa2757 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 23 Jan 2021 21:36:47 +0800 Subject: [PATCH 144/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0162_find_peak_element/peak.c | 13 +++++++------ 0162_find_peak_element/peak.cc | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) create mode 100644 0162_find_peak_element/peak.cc diff --git a/0162_find_peak_element/peak.c b/0162_find_peak_element/peak.c index bb1d2f5..c936ae5 100644 --- a/0162_find_peak_element/peak.c +++ b/0162_find_peak_element/peak.c @@ -1,14 +1,15 @@ #include #include -static int findPeakElement(int* nums, int numsSize) -{ - if (numsSize == 1) { - return nums[0]; - } +int findPeakElement(int* nums, int numsSize) +{ int i; - for (i = 1; i < numsSize && nums[i] > nums[i - 1]; i++) {} + for (i = 1; i < numsSize; i++) { + if (nums[i] < nums[i - 1]) { + break; + } + } return i - 1; } diff --git a/0162_find_peak_element/peak.cc b/0162_find_peak_element/peak.cc new file mode 100644 index 0000000..c60724e --- /dev/null +++ b/0162_find_peak_element/peak.cc @@ -0,0 +1,16 @@ +#include + +using namespace std; + +class Solution { +public: + int findPeakElement(vector& nums) { + int i; + for (i = 1; i < nums.size(); i++) { + if (nums[i] < nums[i - 1]) { + break; + } + } + return i - 1; + } +}; From 5903b797e45209d5727b4c1e662d7bfb2e96dea5 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 24 Jan 2021 22:53:15 +0800 Subject: [PATCH 145/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../bst_convert.c | 7 +-- .../bst_convert.cc | 49 +++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 0109_convert_sorted_list_to_binary_search_tree/bst_convert.cc 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 c79f239..965fdc1 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 @@ -1,6 +1,7 @@ #include #include + struct ListNode { int val; struct ListNode *next; @@ -12,13 +13,13 @@ struct TreeNode { struct TreeNode *right; }; -static struct TreeNode *traverse(int *nums, int lo, int hi) +static struct TreeNode *dfs(int *nums, int lo, int hi) { int mid = lo + (hi - lo) / 2; struct TreeNode *node = malloc(sizeof(*node)); node->val = nums[mid]; - node->left = mid > lo ? traverse(nums, lo, mid - 1) : NULL; - node->right = mid < hi ? traverse(nums, mid + 1, hi) : NULL; + node->left = mid > lo ? dfs(nums, lo, mid - 1) : NULL; + node->right = mid < hi ? dfs(nums, mid + 1, hi) : NULL; return node; } diff --git a/0109_convert_sorted_list_to_binary_search_tree/bst_convert.cc b/0109_convert_sorted_list_to_binary_search_tree/bst_convert.cc new file mode 100644 index 0000000..8f840af --- /dev/null +++ b/0109_convert_sorted_list_to_binary_search_tree/bst_convert.cc @@ -0,0 +1,49 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode *sortedListToBST(ListNode* head) { + if (head == nullptr) { + return NULL; + } else if (head->next == nullptr) { + return new TreeNode(head->val); + } else { + ListNode *fast = head; + ListNode *slow = head; + ListNode *last = slow; + while (fast != nullptr && fast->next != nullptr) { + last = slow; + slow = slow->next; + fast = fast->next->next; + } + last->next = nullptr; + TreeNode *node = new TreeNode(slow->val); + node->left = sortedListToBST(head); + node->right = sortedListToBST(slow->next); + return node; + } + } +}; From e7da092e266602af2693837e6a7c68d311673a53 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 25 Jan 2021 21:57:53 +0800 Subject: [PATCH 146/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0206_reverse_linked_list/reverse_list.c | 7 +++--- 0206_reverse_linked_list/reverse_list.cc | 28 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 0206_reverse_linked_list/reverse_list.cc diff --git a/0206_reverse_linked_list/reverse_list.c b/0206_reverse_linked_list/reverse_list.c index c45ccc5..9031752 100644 --- a/0206_reverse_linked_list/reverse_list.c +++ b/0206_reverse_linked_list/reverse_list.c @@ -1,6 +1,7 @@ #include #include + struct ListNode { int val; struct ListNode *next; @@ -17,15 +18,15 @@ static struct ListNode *recursive(struct ListNode *prev, struct ListNode *p) return recursive(p, q); } -static struct ListNode *reverseList(struct ListNode *head) +struct ListNode *reverseList(struct ListNode *head) { return recursive(NULL, head); } -/* Iteration */ #if 0 -static struct ListNode *reverseList(struct ListNode *head) +/* Iteration */ +struct ListNode *reverseList(struct ListNode *head) { struct ListNode *prev = NULL; struct ListNode *p = head; diff --git a/0206_reverse_linked_list/reverse_list.cc b/0206_reverse_linked_list/reverse_list.cc new file mode 100644 index 0000000..212aee6 --- /dev/null +++ b/0206_reverse_linked_list/reverse_list.cc @@ -0,0 +1,28 @@ +#include + +using namespace std; + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + ListNode *prev = nullptr; + ListNode *p = head; + while (p != nullptr) { + ListNode *q = p->next; + p->next = prev; + prev = p; + p = q; + } + return prev; + } +}; From 034d95165bb646e9ba802b68370962b17cddec43 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 27 Jan 2021 22:56:27 +0800 Subject: [PATCH 147/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0135_candy/candy.c | 8 +++++--- 0135_candy/candy.cc | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 0135_candy/candy.cc diff --git a/0135_candy/candy.c b/0135_candy/candy.c index 20721bd..063797d 100644 --- a/0135_candy/candy.c +++ b/0135_candy/candy.c @@ -1,10 +1,12 @@ #include #include -static int candy(int* ratings, int ratingsSize) + +int candy(int* ratings, int ratingsSize) { - if (ratingsSize == 0) return 0; - if (ratingsSize == 1) return 1; + if (ratingsSize == 0) { + return 0; + } int i, *candies = malloc(ratingsSize * sizeof(int)); candies[0] = 1; diff --git a/0135_candy/candy.cc b/0135_candy/candy.cc new file mode 100644 index 0000000..931e407 --- /dev/null +++ b/0135_candy/candy.cc @@ -0,0 +1,24 @@ +#include + +using namespace std; + +class Solution { +public: + int candy(vector& ratings) { + vector candies(ratings.size(), 1); + for (int i = 1; i < ratings.size(); i++) { + if (ratings[i] > ratings[i - 1]) { + candies[i] = candies[i - 1] + 1; + } + } + + int sum = candies[ratings.size() - 1]; + for (int i = ratings.size() - 2; i >= 0; i--) { + if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) { + candies[i] = candies[i + 1] + 1; + } + sum += candies[i]; + } + return sum; + } +}; From 2be5ee97a17a0742356f22f7a29f14719373e3cf Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 28 Jan 2021 11:32:23 +0800 Subject: [PATCH 148/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0015_three_sum/three_sum.c | 3 ++- 0018_four_sum/four_sum.c | 19 ++++++++------- 0039_combination_sum/combination_sum.c | 4 ++-- 0040_combination_sum_ii/combination_sum.c | 8 +++---- 0046_permutations/permutations.c | 4 ++-- 0049_group_anagrams/anagrams.c | 8 +++---- 0049_group_anagrams/anagrams.cc | 8 +++---- 0051_n_queens/n_queens.c | 2 +- 0056_merge_intervals/merge_intervals.c | 2 +- 0057_insert_interval/insert_interval.c | 5 ++-- 0059_spiral_matrix_ii/spiral_matrix.c | 2 +- 0077_combinations/combinations.c | 3 ++- 0078_subsets/subsets.c | 15 ++++++------ .../bst_bfs.c | 11 ++++----- 0113_path_sum_ii/path_sum.c | 19 ++++++++++----- 0118_pascal_triangle/pascal_triangle.c | 24 +++++++++++-------- .../palindrome_partition.c | 5 ++-- 17 files changed, 79 insertions(+), 63 deletions(-) diff --git a/0015_three_sum/three_sum.c b/0015_three_sum/three_sum.c index 31bf395..7ce5dbd 100644 --- a/0015_three_sum/three_sum.c +++ b/0015_three_sum/three_sum.c @@ -1,6 +1,7 @@ #include #include + static int compare(const void *a, const void *b) { return *(int *) a - *(int *) b; @@ -30,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(). **/ -static int** threeSum(int* nums, int numsSize, int* returnSize) +int** threeSum(int* nums, int numsSize, int* returnSize) { if (numsSize < 3) { return NULL; diff --git a/0018_four_sum/four_sum.c b/0018_four_sum/four_sum.c index 87ce58b..ebeeabb 100644 --- a/0018_four_sum/four_sum.c +++ b/0018_four_sum/four_sum.c @@ -2,13 +2,14 @@ #include #include + 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 *columnSizes) + int *stack, int len, int **results, int *count, int *col_sizes) { int i; if (k == 2) { @@ -23,7 +24,7 @@ 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)); - columnSizes[*count] = total; + col_sizes[*count] = total; (*count)++; len -= 2; while (++low < high && nums[low] == nums[low - 1]) {} @@ -34,9 +35,8 @@ static void k_sum(int *nums, int low, int high, int target, int total, int k, /* k > 2 */ 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, results, count, columnSizes); - len--; + stack[len] = nums[i]; + k_sum(nums, i + 1, high, target - nums[i], 4, k - 1, stack, len + 1, results, count, col_sizes); } } } @@ -44,9 +44,10 @@ static void k_sum(int *nums, int low, int high, int target, int total, int k, /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + * Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). */ -int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes) { +int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes) +{ *returnSize = 0; int i, j, capacity = 50000; int **results = malloc(capacity * sizeof(int *)); @@ -62,11 +63,11 @@ int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** return int main(void) { - int i, count; + int i, 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), 11, &count); + 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]); } diff --git a/0039_combination_sum/combination_sum.c b/0039_combination_sum/combination_sum.c index 9bda0fc..0fcb96b 100644 --- a/0039_combination_sum/combination_sum.c +++ b/0039_combination_sum/combination_sum.c @@ -28,10 +28,10 @@ static void dfs(int *nums, int size, int start, int target, int *stack, ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int **returnColumnSizes) +int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int **returnColumnSizes) { int cap = 200; - int *stack = malloc(candidatesSize * sizeof(int)); + int *stack = malloc(cap * sizeof(int)); int **results = malloc(cap * sizeof(int *)); *returnColumnSizes = malloc(cap * sizeof(int)); *returnSize = 0; diff --git a/0040_combination_sum_ii/combination_sum.c b/0040_combination_sum_ii/combination_sum.c index 13ffe7d..4623149 100644 --- a/0040_combination_sum_ii/combination_sum.c +++ b/0040_combination_sum_ii/combination_sum.c @@ -11,7 +11,7 @@ static int compare(const void *a, const void *b) } static void dfs(int *nums, int size, int start, int target, int *solution, - int len, int **results, int *count, int *column_sizes) + int len, int **results, int *count, int *col_sizes) { int i; if (target < 0) { @@ -19,7 +19,7 @@ static void dfs(int *nums, int size, int start, int target, int *solution, } else if (target == 0) { results[*count] = malloc(len * sizeof(int)); memcpy(results[*count], solution, len * sizeof(int)); - column_sizes[*count] = len; + col_sizes[*count] = len; (*count)++; } else { int last = INT_MIN; @@ -28,7 +28,7 @@ static void dfs(int *nums, int size, int start, int target, int *solution, /* No duplicate combinations in the same level position */ solution[len] = nums[i]; /* i + 1 limits the candidate range in next levels */ - dfs(nums, size, i + 1, target - nums[i], solution, len + 1, results, count, column_sizes); + dfs(nums, size, i + 1, target - nums[i], solution, len + 1, results, count, col_sizes); } last = nums[i]; } @@ -40,7 +40,7 @@ static void dfs(int *nums, int size, int start, int target, int *solution, ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) +int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) { qsort(candidates, candidatesSize, sizeof(int), compare); diff --git a/0046_permutations/permutations.c b/0046_permutations/permutations.c index 38968d4..e901c03 100644 --- a/0046_permutations/permutations.c +++ b/0046_permutations/permutations.c @@ -58,9 +58,9 @@ static void dfs(int *nums, int size, bool *used, int *stack, /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + * Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). */ -static int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) +int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { int count = 0, cap = 5000; int **results = malloc(cap * sizeof(int *)); diff --git a/0049_group_anagrams/anagrams.c b/0049_group_anagrams/anagrams.c index 52d5bb0..fb9765f 100644 --- a/0049_group_anagrams/anagrams.c +++ b/0049_group_anagrams/anagrams.c @@ -29,7 +29,7 @@ static inline int BKDRHash(char *s, size_t size) ** The sizes of the arrays are returned as *returnColumnSizes array. ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** returnColumnSizes) +char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** returnColumnSizes) { int i, j, count = 0; int hash_size = strsSize; @@ -72,10 +72,10 @@ static char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** r int main(int argc, char **argv) { - int *column_sizes, count = 0, i, j; - char ***lists = groupAnagrams(argv + 1, argc - 1, &count, &column_sizes); + int *col_sizes, count = 0, i, j; + char ***lists = groupAnagrams(argv + 1, argc - 1, &count, &col_sizes); for (i = 0; i < count; i++) { - for (j = 0; j < column_sizes[i]; j++) { + for (j = 0; j < col_sizes[i]; j++) { printf("%s ", lists[i][j]); } printf("\n"); diff --git a/0049_group_anagrams/anagrams.cc b/0049_group_anagrams/anagrams.cc index c90a7f6..0090531 100644 --- a/0049_group_anagrams/anagrams.cc +++ b/0049_group_anagrams/anagrams.cc @@ -9,14 +9,14 @@ class Solution { unordered_map> ht; for (const auto& str : strs) { int counts[26] = { 0 }; - for (const auto& s : str) { - counts[s - 'a']++; + for (char c : str) { + counts[c - 'a']++; } string key; - for (const auto& c : counts) { + for (int i : counts) { key.push_back('#'); - key.push_back(c + '0'); + key.push_back(i + '0'); } ht[key].push_back(str); diff --git a/0051_n_queens/n_queens.c b/0051_n_queens/n_queens.c index e2ba9a3..5892c12 100644 --- a/0051_n_queens/n_queens.c +++ b/0051_n_queens/n_queens.c @@ -73,7 +73,7 @@ static void dfs(int n, int row, int *stack, char ***solutions, int *count, int * /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + * Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). */ char *** solveNQueens(int n, int* returnSize, int** returnColumnSizes) { diff --git a/0056_merge_intervals/merge_intervals.c b/0056_merge_intervals/merge_intervals.c index e9570d5..133a778 100644 --- a/0056_merge_intervals/merge_intervals.c +++ b/0056_merge_intervals/merge_intervals.c @@ -11,7 +11,7 @@ static int compare(const void *a, const void *b) /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + * Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). */ int** merge(int** intervals, int intervalsSize, int* intervalsColSize, int* returnSize, int** returnColumnSizes) { diff --git a/0057_insert_interval/insert_interval.c b/0057_insert_interval/insert_interval.c index c0f7c9d..b97da9a 100644 --- a/0057_insert_interval/insert_interval.c +++ b/0057_insert_interval/insert_interval.c @@ -10,9 +10,10 @@ static int compare(const void *a, const void *b) /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + * Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). */ -int** insert(int** intervals, int intervalsSize, int* intervalsColSize, int* newInterval, int newIntervalSize, int* returnSize, int** returnColumnSizes) +int** insert(int** intervals, int intervalsSize, int* intervalsColSize, int* newInterval, + int newIntervalSize, int* returnSize, int** returnColumnSizes) { int i, len = 0; int *tmp = malloc((intervalsSize + 1) * 2 * sizeof(int)); diff --git a/0059_spiral_matrix_ii/spiral_matrix.c b/0059_spiral_matrix_ii/spiral_matrix.c index d85769f..d4c5339 100644 --- a/0059_spiral_matrix_ii/spiral_matrix.c +++ b/0059_spiral_matrix_ii/spiral_matrix.c @@ -5,7 +5,7 @@ /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + * Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). */ int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) { diff --git a/0077_combinations/combinations.c b/0077_combinations/combinations.c index fcf614c..2ef84f7 100644 --- a/0077_combinations/combinations.c +++ b/0077_combinations/combinations.c @@ -3,6 +3,7 @@ #include #include + static void dfs(int n, int k, int start, int *stack, int len, int **results, int *count, int *col_sizes) { @@ -23,7 +24,7 @@ static void dfs(int n, int k, int start, int *stack, int len, /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + * Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). */ int** combine(int n, int k, int* returnSize, int** returnColumnSizes) { int capacity = 10000; diff --git a/0078_subsets/subsets.c b/0078_subsets/subsets.c index a98cfcf..aeb75b1 100644 --- a/0078_subsets/subsets.c +++ b/0078_subsets/subsets.c @@ -2,33 +2,34 @@ #include #include -static void dfs(int *nums, int size, int start, int *buf, + +static void dfs(int *nums, int size, int start, int *stack, int len, int **sets, int *count, int *sizes) { int i; sets[*count] = malloc(len * sizeof(int)); - memcpy(sets[*count], buf, len * sizeof(int)); + memcpy(sets[*count], stack, len * sizeof(int)); sizes[*count] = len; (*count)++; for (i = start; i < size; i++) { - buf[len] = nums[i]; - dfs(nums, size, i + 1, buf, len + 1, sets, count, sizes); + stack[len] = nums[i]; + dfs(nums, size, i + 1, stack, len + 1, sets, count, sizes); } } /** ** Return an array of arrays of size *returnSize. ** The sizes of the arrays are returned as *returnColumnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { int capacity = 5000; int **sets = malloc(capacity * sizeof(int *)); - int *buf = malloc(numsSize * sizeof(int)); + int *stack = malloc(numsSize * sizeof(int)); *returnColumnSizes = malloc(capacity * sizeof(int)); *returnSize = 0; - dfs(nums, numsSize, 0, buf, 0, sets, returnSize, *returnColumnSizes); + dfs(nums, numsSize, 0, stack, 0, sets, returnSize, *returnColumnSizes); return sets; } diff --git a/0107_binary_tree_level_order_traversal_ii/bst_bfs.c b/0107_binary_tree_level_order_traversal_ii/bst_bfs.c index 564ae71..2464fbf 100644 --- a/0107_binary_tree_level_order_traversal_ii/bst_bfs.c +++ b/0107_binary_tree_level_order_traversal_ii/bst_bfs.c @@ -2,7 +2,6 @@ #include #include -#define BST_MAX_LEVEL 800 struct TreeNode { int val; @@ -29,9 +28,9 @@ static void bfs(struct TreeNode *root, int **results, int *count, int *col_sizes /** ** Return an array of arrays of size *returnSize. ** The sizes of the arrays are returned as *returnColumnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes) +int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes) { if (root == NULL) { *returnSize = 0; @@ -40,9 +39,9 @@ static int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** retu int size = 1; *returnSize = 0; - int **results = malloc(BST_MAX_LEVEL * sizeof(int *)); - *returnColumnSizes = malloc(BST_MAX_LEVEL * sizeof(int)); - memset(*returnColumnSizes, 0, BST_MAX_LEVEL * sizeof(int)); + int **results = malloc(800 * sizeof(int *)); + *returnColumnSizes = malloc(800 * sizeof(int)); + memset(*returnColumnSizes, 0, 800 * sizeof(int)); bfs(root, results, returnSize, *returnColumnSizes, &size, 0); int i, j; diff --git a/0113_path_sum_ii/path_sum.c b/0113_path_sum_ii/path_sum.c index 43071cc..cb52c2f 100644 --- a/0113_path_sum_ii/path_sum.c +++ b/0113_path_sum_ii/path_sum.c @@ -2,6 +2,7 @@ #include #include + struct TreeNode { int val; struct TreeNode *left; @@ -25,7 +26,12 @@ static void dfs(struct TreeNode *node, int sum, int *stack, int len, int **resul } } -static int **pathSum(struct TreeNode *root, int sum, int **columnSizes, int *returnSize) +/** + * 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(). + */ +int **pathSum(struct TreeNode *root, int sum, int *returnSize, int **returnColumnSizes) { if (root == NULL) { *returnSize = 0; @@ -35,8 +41,8 @@ static int **pathSum(struct TreeNode *root, int sum, int **columnSizes, int *ret int level = 5000, cap = 1000; int *stack = malloc(level * sizeof(int)); int **results = malloc(cap * sizeof(int *)); - *columnSizes = malloc(cap * sizeof(int)); - dfs(root, sum, stack, 0, results, *columnSizes, returnSize); + *returnColumnSizes = malloc(cap * sizeof(int)); + dfs(root, sum, stack, 0, results, *returnColumnSizes, returnSize); return results; } @@ -76,13 +82,14 @@ int main(int argc, char **argv) n3[7].right = NULL; int i, j, count = 0; - int *sizes; - int **list = pathSum(&root, 22, &sizes, &count); + int *col_sizes, sum = 22; + int **list = pathSum(&root, sum, &count, &col_sizes); for (i = 0; i < count; i++) { - for (j = 0; j < sizes[i]; j++) { + for (j = 0; j < col_sizes[i]; j++) { printf("%d ", list[i][j]); } printf("\n"); } + return 0; } diff --git a/0118_pascal_triangle/pascal_triangle.c b/0118_pascal_triangle/pascal_triangle.c index 99de1c1..7dee4c4 100644 --- a/0118_pascal_triangle/pascal_triangle.c +++ b/0118_pascal_triangle/pascal_triangle.c @@ -1,19 +1,20 @@ #include #include + /** - ** Return an arrahi of arrahis. - ** The sizes of the arrahis are returned as *columnSizes arrahi. - ** Note: Both returned arrahi and *columnSizes arrahi must be malloced, assume caller calls free(). - **/ -static int** generate(int numRows, int** columnSizes) + * 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(). + */ +int** generate(int numRows, int *returnSize, int** returnColumnSizes) { int i, j; int **triangle = malloc(numRows * sizeof(int *)); - *columnSizes = malloc(numRows * sizeof(int *)); + *returnColumnSizes = malloc(numRows * sizeof(int *)); for (i = 0; i < numRows; i++) { int num = i + 1; - (*columnSizes)[i] = num; + (*returnColumnSizes)[i] = num; triangle[i] = malloc(num * sizeof(int)); triangle[i][0] = 1; triangle[i][num - 1] = 1; @@ -21,6 +22,7 @@ static int** generate(int numRows, int** columnSizes) triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]; } } + *returnSize = numRows; return triangle; } @@ -30,10 +32,12 @@ int main(int argc, char **argv) fprintf(stderr, "Usage: ./test n\n"); exit(-1); } - int i, j, *sizes, row = atoi(argv[1]); - int **triangle = generate(row, &sizes); + + int i, j, count, *col_sizes; + int row = atoi(argv[1]); + int **triangle = generate(row, &count, &col_sizes); for (i = 0; i < row; i++) { - for (j = 0; j < sizes[i]; j++) { + for (j = 0; j < col_sizes[i]; j++) { printf("%d ", triangle[i][j]); } printf("\n"); diff --git a/0131_palindrome_patitioning/palindrome_partition.c b/0131_palindrome_patitioning/palindrome_partition.c index cc83084..f871f19 100644 --- a/0131_palindrome_patitioning/palindrome_partition.c +++ b/0131_palindrome_patitioning/palindrome_partition.c @@ -3,6 +3,7 @@ #include #include + struct palindrome { int low; int high; @@ -49,9 +50,9 @@ static void dfs(struct palindrome *pal_set, int num, int start, /** ** Return an array of arrays of size *returnSize. ** The sizes of the arrays are returned as *returnColumnSizes array. - ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + ** Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free(). **/ -static char ***partition(char* s, int* returnSize, int** returnColumnSizes) +char ***partition(char* s, int* returnSize, int** returnColumnSizes) { int len = strlen(s); if (len == 0) { From f3b471c1520d3e4440025f8a745d90284341837d Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 29 Jan 2021 10:13:42 +0800 Subject: [PATCH 149/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0001_two_sum/two_sum.cc | 2 +- 0001_two_sum/two_sum.py | 11 ----------- 2 files changed, 1 insertion(+), 12 deletions(-) delete mode 100644 0001_two_sum/two_sum.py diff --git a/0001_two_sum/two_sum.cc b/0001_two_sum/two_sum.cc index c06f0b4..7dca0f0 100644 --- a/0001_two_sum/two_sum.cc +++ b/0001_two_sum/two_sum.cc @@ -9,7 +9,7 @@ class Solution { unordered_map ht; for (int i = 0; i < nums.size(); i++) { int other = target - nums[i]; - if (ht.find(other) != ht.end()) { + if (ht.count(other)) { /* Only one solution for purpose of this problem */ res.append(ht[other]); res.append(i); diff --git a/0001_two_sum/two_sum.py b/0001_two_sum/two_sum.py deleted file mode 100644 index 2606238..0000000 --- a/0001_two_sum/two_sum.py +++ /dev/null @@ -1,11 +0,0 @@ -class Solution: - def twoSum(self, nums, target): - h = {} - for i, n in enumerate(nums): - other = target - n - if other not in h: - h[n] = i - else: - return [h[other], i] - -print(Solution().twoSum([-1, -2, -3, -4, -5], -8)) From e52ea62756564789f59b581f38fa3e53c26c77f9 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 30 Jan 2021 22:40:52 +0800 Subject: [PATCH 150/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0120_triangle/triangle.c | 20 ++++++++++---------- 0120_triangle/triangle.cc | 30 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 10 deletions(-) create mode 100644 0120_triangle/triangle.cc diff --git a/0120_triangle/triangle.c b/0120_triangle/triangle.c index 7df14cc..bcf9875 100644 --- a/0120_triangle/triangle.c +++ b/0120_triangle/triangle.c @@ -5,33 +5,33 @@ static int dfs(int** triangle, int row_size, int *col_sizes, - int row, int col, int **sums, bool **passes) + int row, int col, int **sums, bool **passed) { if (row == row_size - 1) { return triangle[row][col]; - } else if (passes[row][col]) { + } else if (passed[row][col]) { return sums[row][col]; } else { - int s1 = dfs(triangle, row_size, col_sizes, row + 1, col, sums, passes); - int s2 = dfs(triangle, row_size, col_sizes, row + 1, col + 1, sums, passes); + int s1 = dfs(triangle, row_size, col_sizes, row + 1, col, sums, passed); + int s2 = dfs(triangle, row_size, col_sizes, row + 1, col + 1, sums, passed); sums[row][col] = triangle[row][col] + (s1 < s2 ? s1 : s2); /* Set pass marks in backtracing as the paths are overlapped */ - passes[row][col] = true; + passed[row][col] = true; return sums[row][col]; } } -static int minimumTotal(int** triangle, int triangleSize, int *triangleColSizes) +int minimumTotal(int** triangle, int triangleSize, int *triangleColSizes) { int i; int **sums = malloc(triangleSize * sizeof(int *)); - bool **passes = malloc(triangleSize * sizeof(bool *)); + bool **passed = malloc(triangleSize * sizeof(bool *)); for (i = 0; i < triangleSize; i++) { - passes[i] = malloc(triangleColSizes[i]); - memset(passes[i], false, triangleColSizes[i]); + passed[i] = malloc(triangleColSizes[i]); + memset(passed[i], false, triangleColSizes[i]); sums[i] = malloc(triangleColSizes[i] * sizeof(int)); } - return dfs(triangle, triangleSize, triangleColSizes, 0, 0, sums, passes); + return dfs(triangle, triangleSize, triangleColSizes, 0, 0, sums, passed); } int main(void) diff --git a/0120_triangle/triangle.cc b/0120_triangle/triangle.cc new file mode 100644 index 0000000..9ecd64b --- /dev/null +++ b/0120_triangle/triangle.cc @@ -0,0 +1,30 @@ +#include + +using namespace std; + +class Solution { +public: + int minimumTotal(vector>& triangle) { + for (auto & t : triangle) { + passed.push_back(vector(t.size(), false)); + sums.push_back(vector(t.size())); + } + return dfs(triangle, 0, 0); + } +private: + vector> passed; + vector> sums; + int dfs(vector>& triangle, int row, int col) { + if (row == triangle.size() - 1) { + return triangle[row][col]; + } else if (passed[row][col]) { + return sums[row][col]; + } else { + int s1 = dfs(triangle, row + 1, col); + int s2 = dfs(triangle, row + 1, col + 1); + sums[row][col] = triangle[row][col] + (s1 < s2 ? s1 : s2); + passed[row][col] = true; + return sums[row][col]; + } + } +}; From 9eed79a76b551373623fb7a5c27ae090ff688bd7 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 31 Jan 2021 17:54:35 +0800 Subject: [PATCH 151/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0069_sqrt/sqrt.c | 14 +++++++------- 0069_sqrt/sqrt.cc | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 7 deletions(-) create mode 100644 0069_sqrt/sqrt.cc diff --git a/0069_sqrt/sqrt.c b/0069_sqrt/sqrt.c index 08cc5bd..e4fdcd0 100644 --- a/0069_sqrt/sqrt.c +++ b/0069_sqrt/sqrt.c @@ -51,26 +51,26 @@ static double mySqrt(double n) } #endif -static int mySqrt(int x) +int mySqrt(int x) { if (x == 0) { return 0; } - unsigned int left = 1; - unsigned int right = (unsigned int) x; - unsigned int mid = left + (right - left) / 2; + unsigned int lo = 1; + unsigned int hi = (unsigned int) x; + unsigned int mid = lo + (hi - lo) / 2; for (; ;) { if (mid > x/mid) { - right = mid; + hi = mid; } else { if (mid + 1 > x/(mid + 1)) { break; } else { - left = mid; + lo = mid; } } - mid = left + (right - left) / 2; + mid = lo + (hi - lo) / 2; } return mid; diff --git a/0069_sqrt/sqrt.cc b/0069_sqrt/sqrt.cc new file mode 100644 index 0000000..8e47bf6 --- /dev/null +++ b/0069_sqrt/sqrt.cc @@ -0,0 +1,29 @@ +#include + +using namespace std; + +class Solution { +public: + int mySqrt(int x) { + if (x == 0) { + return 0; + } + + unsigned int lo = 1, hi = x; + unsigned int mid = (lo + hi) / 2; + for (; ;) { + if (mid > x / mid) { + hi = mid; + } else { + if (mid + 1 > x / (mid + 1)) { + break; + } else { + lo = mid; + } + } + mid = (lo + hi) / 2; + } + + return mid; + } +}; From 290291f5411755564d58555682147b1d4b5fd66e Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 1 Feb 2021 22:47:50 +0800 Subject: [PATCH 152/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0113_path_sum_ii/path_sum.cc | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 0113_path_sum_ii/path_sum.cc diff --git a/0113_path_sum_ii/path_sum.cc b/0113_path_sum_ii/path_sum.cc new file mode 100644 index 0000000..64b24a1 --- /dev/null +++ b/0113_path_sum_ii/path_sum.cc @@ -0,0 +1,39 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> pathSum(TreeNode* root, int targetSum) { + vector> res; + dfs(root, targetSum, res); + return res; + } +private: + vector stack; + void dfs(TreeNode* root, int sum, vector>& res) { + if (root == nullptr) { + return; + } else if (root->left == nullptr && root->right == nullptr && sum == root->val) { + stack.push_back(root->val); + res.push_back(stack); + stack.pop_back(); + } else { + stack.push_back(root->val); + dfs(root->left, sum - root->val, res); + dfs(root->right, sum - root->val, res); + stack.pop_back(); + } + } +}; From 018c98497623288da1857a74271135339a206a64 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 2 Feb 2021 16:11:26 +0800 Subject: [PATCH 153/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0075_sort_colors/sort_colors.c | 3 ++- 0075_sort_colors/sort_colors.cc | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 0075_sort_colors/sort_colors.cc diff --git a/0075_sort_colors/sort_colors.c b/0075_sort_colors/sort_colors.c index 0791746..290c02d 100644 --- a/0075_sort_colors/sort_colors.c +++ b/0075_sort_colors/sort_colors.c @@ -2,6 +2,7 @@ #include #include + static inline void swap(int *a, int *b) { int tmp = *a; @@ -9,7 +10,7 @@ static inline void swap(int *a, int *b) *b = tmp; } -static void sortColors(int* nums, int numsSize) +void sortColors(int* nums, int numsSize) { int i, j = 0; for (i = 0; i < numsSize; i++) { diff --git a/0075_sort_colors/sort_colors.cc b/0075_sort_colors/sort_colors.cc new file mode 100644 index 0000000..0d8ab5b --- /dev/null +++ b/0075_sort_colors/sort_colors.cc @@ -0,0 +1,34 @@ +#include + +using namespace std; + +class Solution { +public: + void sortColors(vector& nums) { + int i = 0, j = nums.size() - 1; + while (i < j) { + if (nums[i] == 0) { + i++; + continue; + } + if (nums[j] != 0) { + j--; + continue; + } + swap(nums[i], nums[j]); + } + + j = nums.size() - 1; + while (i < j) { + if (nums[i] == 1) { + i++; + continue; + } + if (nums[j] != 1) { + j--; + continue; + } + swap(nums[i], nums[j]); + } + } +}; From dfecd2a80a727990ba2ca1f9fd06d41805b84f5a Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 3 Feb 2021 15:55:26 +0800 Subject: [PATCH 154/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0300_longest_increasing_subsequence/Makefile | 2 + 0300_longest_increasing_subsequence/lis.c | 41 ++++++++++++++++++++ 0300_longest_increasing_subsequence/lis.cc | 25 ++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 0300_longest_increasing_subsequence/Makefile create mode 100644 0300_longest_increasing_subsequence/lis.c create mode 100644 0300_longest_increasing_subsequence/lis.cc diff --git a/0300_longest_increasing_subsequence/Makefile b/0300_longest_increasing_subsequence/Makefile new file mode 100644 index 0000000..ba1e9d7 --- /dev/null +++ b/0300_longest_increasing_subsequence/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test lis.c diff --git a/0300_longest_increasing_subsequence/lis.c b/0300_longest_increasing_subsequence/lis.c new file mode 100644 index 0000000..b9a05cd --- /dev/null +++ b/0300_longest_increasing_subsequence/lis.c @@ -0,0 +1,41 @@ +#include +#include + + +static int binary_search(int *nums, int lo, int hi, int target) +{ + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] < target) { + lo = mid; + } else { + hi = mid; + } + } + return hi; +} + +int lengthOfLIS(int* nums, int numsSize){ + int i, piles = 0; + int *tops = malloc(numsSize * sizeof(int)); + for (i = 0; i < numsSize; i++) { + int pos = binary_search(tops, -1, piles, nums[i]); + if (pos == piles) { + piles++; + } + tops[pos] = nums[i]; + } + return piles; +} + +int main(int argc, char **argv) +{ + int i; + int *nums = malloc((argc - 1) * sizeof(int)); + for (i = 0; i < argc - 1; i++) { + nums[i] = atoi(argv[i + 1]); + } + + printf("%d\n", lengthOfLIS(nums, argc - 1)); + return 0; +} diff --git a/0300_longest_increasing_subsequence/lis.cc b/0300_longest_increasing_subsequence/lis.cc new file mode 100644 index 0000000..9138ac2 --- /dev/null +++ b/0300_longest_increasing_subsequence/lis.cc @@ -0,0 +1,25 @@ +#include + +using namespace std; + +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector dp(nums.size(), 1); + for (int i = 0; i < nums.size(); i++) { + for (int j = 0; j < i; j++) { + if (nums[j] < nums[i] && dp[j] + 1 > dp[i]) { + dp[i] = dp[j] + 1; + } + } + } + + int res = 0; + for (int i : dp) { + if (i > res) { + res = i; + } + } + return res; + } +}; From 15eb04a96b2f139ae33d93c8a0cc59c3afa829f3 Mon Sep 17 00:00:00 2001 From: Carlos Date: Wed, 3 Feb 2021 12:06:46 -0300 Subject: [PATCH 155/211] feat: added solution for problem 704 --- 0704_binary_search/binary_search.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 0704_binary_search/binary_search.c diff --git a/0704_binary_search/binary_search.c b/0704_binary_search/binary_search.c new file mode 100644 index 0000000..23f4ef3 --- /dev/null +++ b/0704_binary_search/binary_search.c @@ -0,0 +1,23 @@ +#include + +int search(int* nums, int numsSize, int target){ + if(target > nums[numsSize-1] || target < nums[0])return -1; + int begin = -1 ,end = numsSize; + while(begin < end-1){ + int half = (begin+end)/2; + if(nums[half] Date: Fri, 5 Feb 2021 09:51:47 +0800 Subject: [PATCH 156/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0300_longest_increasing_subsequence/lis.cc | 1 + 0354_russian_doll_envelopes/Makefile | 2 + 0354_russian_doll_envelopes/russian_doll.c | 72 +++++++++++++++++++++ 0354_russian_doll_envelopes/russian_doll.cc | 39 +++++++++++ 4 files changed, 114 insertions(+) create mode 100644 0354_russian_doll_envelopes/Makefile create mode 100644 0354_russian_doll_envelopes/russian_doll.c create mode 100644 0354_russian_doll_envelopes/russian_doll.cc diff --git a/0300_longest_increasing_subsequence/lis.cc b/0300_longest_increasing_subsequence/lis.cc index 9138ac2..6dd9198 100644 --- a/0300_longest_increasing_subsequence/lis.cc +++ b/0300_longest_increasing_subsequence/lis.cc @@ -8,6 +8,7 @@ class Solution { vector dp(nums.size(), 1); for (int i = 0; i < nums.size(); i++) { for (int j = 0; j < i; j++) { + // nums[i] should be contained as the last element in subsequence. if (nums[j] < nums[i] && dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; } diff --git a/0354_russian_doll_envelopes/Makefile b/0354_russian_doll_envelopes/Makefile new file mode 100644 index 0000000..df77fea --- /dev/null +++ b/0354_russian_doll_envelopes/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test russian_doll.c diff --git a/0354_russian_doll_envelopes/russian_doll.c b/0354_russian_doll_envelopes/russian_doll.c new file mode 100644 index 0000000..389f389 --- /dev/null +++ b/0354_russian_doll_envelopes/russian_doll.c @@ -0,0 +1,72 @@ +#include +#include + + +static int compare(const void *a, const void *b) +{ + int wa = ((const int *)a)[0]; + int wb = ((const int *)b)[0]; + int ha = ((const int *)a)[1]; + int hb = ((const int *)b)[1]; + return wa == wb ? hb - ha : wa - wb; +} + +static int binary_search(int *nums, int lo, int hi, int target) +{ + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] < target) { + lo = mid; + } else { + hi = mid; + } + } + return hi; +} + +int maxEnvelopes(int** envelopes, int envelopesSize, int* envelopesColSize) +{ + if (envelopesSize == 0) { + return 0; + } + + int size = envelopesColSize[0]; + int i, *tmp = malloc(envelopesSize * size * sizeof(int)); + for (i = 0; i < envelopesSize; i++) { + tmp[i * size] = envelopes[i][0]; + tmp[i * size + 1] = envelopes[i][1]; + } + qsort(tmp, envelopesSize, size * sizeof(int), compare); + + int piles = 0; + int *heights = malloc(envelopesSize * sizeof(int)); + for (i = 0; i < envelopesSize; i++) { + int pos = binary_search(heights, -1, piles, tmp[i * size + 1]); + if (pos == piles) { + piles++; + } + heights[pos] = tmp[i * size + 1]; + } + return piles; +} + +int main(int argc, char **argv) +{ + if (argc < 3 || argc % 2 == 0) { + fprintf(stderr, "Usage: ./test w0 h0 w1 h1..."); + exit(-1); + } + + int i, size = (argc - 1) / 2; + int *col_sizes = malloc(size * sizeof(int)); + int **envelopes = malloc(size * sizeof(int *)); + for (i = 0; i < size; i++) { + col_sizes[i] = 2; + envelopes[i] = malloc(col_sizes[i] * sizeof(int)); + envelopes[i][0] = atoi(argv[i * 2 + 1]); + envelopes[i][1] = atoi(argv[i * 2 + 2]); + } + + printf("%d\n", maxEnvelopes(envelopes, size, col_sizes)); + return 0; +} diff --git a/0354_russian_doll_envelopes/russian_doll.cc b/0354_russian_doll_envelopes/russian_doll.cc new file mode 100644 index 0000000..3079ee3 --- /dev/null +++ b/0354_russian_doll_envelopes/russian_doll.cc @@ -0,0 +1,39 @@ +#include + +using namespace std; + +class Solution { +public: + int maxEnvelopes(vector>& envelopes) { + vector piles; + sort(envelopes.begin(), envelopes.end(), compare); + for (const auto& e : envelopes) { + int pos = binary_search(piles, -1, piles.size(), e[1]); + if (pos == piles.size()) { + piles.push_back(e[1]); + } + piles[pos] = e[1]; + } + return piles.size(); + } +private: + static bool compare(const vector& a, const vector& b) { + int wa = a[0]; + int wb = b[0]; + int ha = a[1]; + int hb = b[1]; + return wa == wb ? ha > hb : wa < wb; + } + + int binary_search(vector& nums, int lo, int hi, int target) { + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; + if (nums[mid] < target) { + lo = mid; + } else { + hi = mid; + } + } + return hi; + } +}; From fa4cfdda5fe3059d91a9e2198ba0f96cabc5aa9a Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 6 Feb 2021 08:43:38 +0800 Subject: [PATCH 157/211] Add c++ implementation Signed-off-by: begeekmyfriend --- 0073_set_matrix_zeroes/set_zero.c | 26 ++++++++++---------- 0073_set_matrix_zeroes/set_zero.cc | 38 ++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 13 deletions(-) create mode 100644 0073_set_matrix_zeroes/set_zero.cc diff --git a/0073_set_matrix_zeroes/set_zero.c b/0073_set_matrix_zeroes/set_zero.c index 7be6a54..b56fd87 100644 --- a/0073_set_matrix_zeroes/set_zero.c +++ b/0073_set_matrix_zeroes/set_zero.c @@ -1,21 +1,23 @@ #include #include -static void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) + +void setZeroes(int** matrix, int matrixSize, int* matrixColSize) { - int row, col, bRow = 0, bCol = 0; - for (row = 0; row < matrixRowSize; row++) { - for (col = 0; col < matrixColSize; col++) { + int row, col; + bool bRow = false, bCol = false; + for (row = 0; row < matrixSize; row++) { + for (col = 0; col < matrixColSize[row]; col++) { if (matrix[row][col] == 0) { - if (row == 0) bCol = 1; - if (col == 0) bRow = 1; + if (row == 0) bRow = true; + if (col == 0) bCol = true; matrix[0][col] = matrix[row][0] = 0; } } } - for (row = 1; row < matrixRowSize; row++) { - for(col = 1; col < matrixColSize; col++){ + for (row = 1; row < matrixSize; row++) { + for(col = 1; col < matrixColSize[row]; col++){ if (matrix[0][col] == 0 || matrix[row][0] == 0) { matrix[row][col] = 0; } @@ -23,14 +25,12 @@ static void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) } if (bRow) { - for(row = 0; row < matrixRowSize; row++) { - matrix[row][0] = 0; - } + memset(matrix[0], 0, matrixColSize[0] * sizeof(int)); } if (bCol) { - for (col = 0; col + +using namespace std; + +public: + void setZeroes(vector>& matrix) { + bool bRow = false, bCol = false; + for (int row = 0; row < matrix.size(); row++) { + for (int col = 0; col < matrix[row].size(); col++) { + if (matrix[row][col] == 0) { + if (row == 0) { bRow = true; } + if (col == 0) { bCol = true; } + matrix[0][col] = matrix[row][0] = 0; + } + } + } + + for (int row = 1; row < matrix.size(); row++) { + for (int col = 1; col < matrix[row].size(); col++) { + if (matrix[0][col] == 0 || matrix[row][0] == 0) { + matrix[row][col] = 0; + } + } + } + + if (bRow) { + for (auto& m : matrix[0]) { + m = 0; + } + } + + if (bCol) { + for (int row = 0; row < matrix.size(); row++) { + matrix[row][0] = 0; + } + } + } +}; From e3b464dfd406d23c3a320506bb70228bc3bc4ffe Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 7 Feb 2021 01:15:02 +0800 Subject: [PATCH 158/211] Refine Signed-off-by: begeekmyfriend --- 0139_word_break/word_break.c | 158 +++++--------------------------- 0140_word_break_ii/word_break.c | 149 +++++++++++------------------- 2 files changed, 75 insertions(+), 232 deletions(-) diff --git a/0139_word_break/word_break.c b/0139_word_break/word_break.c index 40992fa..145d99d 100644 --- a/0139_word_break/word_break.c +++ b/0139_word_break/word_break.c @@ -3,162 +3,46 @@ #include #include -#define container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - -struct list_head { - struct list_head *next, *prev; -}; - -static inline void INIT_LIST_HEAD(struct list_head *list) -{ - list->next = list->prev = list; -} - -static inline int list_empty(const struct list_head *head) -{ - return (head->next == head); -} - -static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) -{ - next->prev = new; - new->next = next; - new->prev = prev; - prev->next = new; -} - -static inline void list_add(struct list_head *_new, struct list_head *head) -{ - __list_add(_new, head, head->next); -} - -static inline void list_add_tail(struct list_head *_new, struct list_head *head) -{ - __list_add(_new, head->prev, head); -} - -static inline void __list_del(struct list_head *entry) -{ - entry->next->prev = entry->prev; - entry->prev->next = entry->next; -} - -static inline void list_del(struct list_head *entry) -{ - __list_del(entry); - entry->next = entry->prev = NULL; -} - -struct word_node { - char *word; - struct list_head link; -}; - -struct dfs_cache { - int num; - int cap; - struct list_head **heads; -}; - -static struct dfs_cache *resize(struct dfs_cache **caches, int index) -{ - int i; - struct dfs_cache *cache = caches[index]; - if (cache->num + 1 > cache->cap) { - cache->cap *= 2; - struct list_head **heads = malloc(cache->cap * sizeof(*heads)); - for (i = 0; i < cache->cap; i++) { - if (i < cache->num) { - heads[i] = cache->heads[i]; - } else { - heads[i] = malloc(sizeof(struct list_head)); - INIT_LIST_HEAD(heads[i]); - } - } - free(cache->heads); - cache->heads = heads; - } - - return cache; -} - -static struct dfs_cache *dfs(char *s, char **words, int *sizes, int num, - struct dfs_cache **caches, int index) -{ +static int dfs(char *s, char **words, int *lens, int size, bool *ends, int index) +{ int i, j; - struct word_node *wn; - struct dfs_cache *result; - if (*s == '\0') { - return NULL; - } else if (caches[index] != NULL) { - return caches[index]; + return true; + } else if (!ends[index]) { + return false; } else { - result = malloc(sizeof(*result)); - result->num = 0; - result->cap = 1; - result->heads = malloc(sizeof(struct list_head *)); - result->heads[0] = malloc(sizeof(struct list_head)); - INIT_LIST_HEAD(result->heads[0]); - caches[index] = result; - for (i = 0; i < num; i++) { - if (!memcmp(s, words[i], sizes[i])) { - struct dfs_cache *next = dfs(s + sizes[i], words, sizes, num, caches, index + sizes[i]); - if (next != NULL) { - int k = result->num; - for (j = k; j < k + next->num; j++) { - result = resize(caches, index); - wn = malloc(sizeof(*wn)); - wn->word = words[i]; - list_add(&wn->link, result->heads[j]); - - struct list_head *p; - list_for_each(p, next->heads[j - k]) { - struct word_node *wnn = list_entry(p, struct word_node, link); - wn = malloc(sizeof(*wn)); - wn->word = wnn->word; - list_add_tail(&wn->link, result->heads[j]); - } - result->num++; - } - } else { - return NULL; + for (i = 0; i < size; i++) { + ends[index] = false; + if (!strncmp(s, words[i], lens[i])) { + /* post-order traverse */ + bool ok = dfs(s + lens[i], words, lens, size, ends, index + lens[i]); + if (ok) { + /* string s all matched */ + return true; } } } - return result; + return ends[index]; } } -static bool wordBreak(char* s, char** wordDict, int wordDictSize) +bool wordBreak(char * s, char ** wordDict, int wordDictSize) { if (wordDictSize == 0) { return false; } - int i, total = 0; - int len = strlen(s); - int *sizes = malloc(wordDictSize * sizeof(int)); - + int i, len = strlen(s); + int *lens = malloc(wordDictSize * sizeof(int)); for (i = 0; i < wordDictSize; i++) { - sizes[i] = strlen(wordDict[i]); - total += sizes[i]; + lens[i] = strlen(wordDict[i]); } - struct dfs_cache **caches = malloc(len * sizeof(*caches)); - memset(caches, 0, len * sizeof(*caches)); - return dfs(s, wordDict, sizes, wordDictSize, caches, 0) == NULL; + bool *ends = malloc(len); + memset(ends, true, len); + return dfs(s, wordDict, lens, wordDictSize, ends, 0); } int main(int argc, char **argv) diff --git a/0140_word_break_ii/word_break.c b/0140_word_break_ii/word_break.c index 2813c4f..625ff92 100644 --- a/0140_word_break_ii/word_break.c +++ b/0140_word_break_ii/word_break.c @@ -2,6 +2,7 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) @@ -11,13 +12,20 @@ #define list_for_each(p, head) \ for (p = (head)->next; p != (head); p = p->next) -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct list_head { struct list_head *next, *prev; }; +struct word_node { + char *word; + struct list_head link; +}; + +struct solution { + int count; + struct list_head heads[]; +}; + static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; @@ -46,107 +54,58 @@ static inline void list_add_tail(struct list_head *_new, struct list_head *head) __list_add(_new, head->prev, head); } -static inline void __list_del(struct list_head *entry) +static void new_word_add(struct list_head *head, char *word) { - entry->next->prev = entry->prev; - entry->prev->next = entry->next; + struct word_node *wn = malloc(sizeof(*wn)); + wn->word = word; + list_add_tail(&wn->link, head); } -static inline void list_del(struct list_head *entry) -{ - __list_del(entry); - entry->next = entry->prev = NULL; -} - -struct word_node { - char *word; - struct list_head link; -}; - -struct dfs_cache { - int num; - int cap; - struct list_head **heads; -}; - -static struct dfs_cache *resize(struct dfs_cache **caches, int index) -{ - int i; - struct dfs_cache *cache = caches[index]; - if (cache->num + 1 > cache->cap) { - cache->cap *= 2; - struct list_head **heads = malloc(cache->cap * sizeof(*heads)); - for (i = 0; i < cache->cap; i++) { - if (i < cache->num) { - heads[i] = cache->heads[i]; - } else { - heads[i] = malloc(sizeof(struct list_head)); - INIT_LIST_HEAD(heads[i]); - } - } - free(cache->heads); - cache->heads = heads; - } - - return cache; -} - -static struct dfs_cache *dfs(char *s, char **words, int *sizes, int num, - struct dfs_cache **caches, int index) +static struct solution *dfs(char *s, char **words, int *lens, int size, + struct solution **sols, int index) { int i, j; - struct word_node *wn; - struct dfs_cache *result; - if (*s == '\0') { return NULL; - } else if (caches[index] != NULL) { - return caches[index]; + } else if (sols[index] != NULL) { + return sols[index]; } else { - result = malloc(sizeof(*result)); - result->num = 0; - result->cap = 1; - result->heads = malloc(sizeof(struct list_head *)); - result->heads[0] = malloc(sizeof(struct list_head)); - INIT_LIST_HEAD(result->heads[0]); - caches[index] = result; - for (i = 0; i < num; i++) { - if (!memcmp(s, words[i], sizes[i])) { - struct dfs_cache *next = dfs(s + sizes[i], words, sizes, num, caches, index + sizes[i]); - if (next != NULL) { - int k = result->num; - for (j = k; j < k + next->num; j++) { - result = resize(caches, index); - wn = malloc(sizeof(*wn)); - wn->word = words[i]; - list_add(&wn->link, result->heads[j]); - + struct solution *sol = malloc(sizeof(*sol) + 60 * sizeof(struct list_head)); + sol->count = 0; + sols[index] = sol; + for (i = 0; i < size; i++) { + if (!strncmp(s, words[i], lens[i])) { + /* post-order traverse */ + struct solution *sub_sol = dfs(s + lens[i], words, lens, size, sols, index + lens[i]); + if (sub_sol != NULL) { + int k = sol->count; + for (j = k; j < k + sub_sol->count; j++) { + /* Append all sub-solutions */ + INIT_LIST_HEAD(&sol->heads[j]); + new_word_add(&sol->heads[j], words[i]); struct list_head *p; - list_for_each(p, next->heads[j - k]) { - struct word_node *wnn = list_entry(p, struct word_node, link); - wn = malloc(sizeof(*wn)); - wn->word = wnn->word; - list_add_tail(&wn->link, result->heads[j]); + list_for_each(p, &sub_sol->heads[j - k]) { + struct word_node *wn = list_entry(p, struct word_node, link); + new_word_add(&sol->heads[j], wn->word); } - result->num++; + sol->count++; } } else { - wn = malloc(sizeof(*wn)); - wn->word = words[i]; - list_add(&wn->link, result->heads[result->num++]); + /* leaf node */ + INIT_LIST_HEAD(&sol->heads[0]); + new_word_add(&sol->heads[sol->count++], words[i]); } } } - - return result; + return sol; } } /** - ** Return an array of size *returnSize. - ** Note: The returned array must be malloced, assume caller calls free(). - **/ -static char **wordBreak(char* s, char** wordDict, int wordDictSize, int *returnSize) + * Return an array of size *returnSize. + * Note: The returned array must be malloced, assume caller calls free(). + */ +char **wordBreak(char* s, char** wordDict, int wordDictSize, int *returnSize) { if (wordDictSize == 0) { *returnSize = 0; @@ -155,24 +114,24 @@ static char **wordBreak(char* s, char** wordDict, int wordDictSize, int *returnS int i, total = 0; int len = strlen(s); - int *sizes = malloc(wordDictSize * sizeof(int)); + int *lens = malloc(wordDictSize * sizeof(int)); /* Add into hash list */ for (i = 0; i < wordDictSize; i++) { - sizes[i] = strlen(wordDict[i]); - total += sizes[i]; + lens[i] = strlen(wordDict[i]); + total += lens[i]; } - struct dfs_cache **caches = malloc(len * sizeof(*caches)); - memset(caches, 0, len * sizeof(*caches)); - struct dfs_cache *cache = dfs(s, wordDict, sizes, wordDictSize, caches, 0); + struct solution **sols = malloc(len * sizeof(void *)); + memset(sols, 0, len * sizeof(void *)); + struct solution *sol = dfs(s, wordDict, lens, wordDictSize, sols, 0); - char **results = malloc(cache->num * sizeof(char *)); - for (i = 0; i < cache->num; i++) { + char **results = malloc(sol->count * sizeof(char *)); + for (i = 0; i < sol->count; i++) { results[i] = malloc(total + 100); char *p = results[i]; struct list_head *n; - list_for_each(n, cache->heads[i]) { + list_for_each(n, &sol->heads[i]) { struct word_node *wn = list_entry(n, struct word_node, link); char *q = wn->word; while ((*p++ = *q++) != '\0') {} @@ -181,7 +140,7 @@ static char **wordBreak(char* s, char** wordDict, int wordDictSize, int *returnS *(p - 1) = '\0'; } - *returnSize = cache->num; + *returnSize = sol->count; return results; } From b1c5b12b1ff5a4695ba8cbf64d44a0dc6c811991 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 8 Feb 2021 08:52:09 +0800 Subject: [PATCH 159/211] Refine Signed-off-by: begeekmyfriend --- 0126_word_ladder_ii/word_ladder.c | 146 +++++++++++++----------------- 1 file changed, 62 insertions(+), 84 deletions(-) diff --git a/0126_word_ladder_ii/word_ladder.c b/0126_word_ladder_ii/word_ladder.c index d0980e0..d34c196 100644 --- a/0126_word_ladder_ii/word_ladder.c +++ b/0126_word_ladder_ii/word_ladder.c @@ -2,6 +2,7 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) @@ -9,18 +10,24 @@ container_of(ptr, type, member) #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) #define list_for_each(p, head) \ for (p = (head)->next; p != (head); p = p->next) -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct list_head { struct list_head *next, *prev; }; +struct word_node { + char *word; + struct list_head node; + struct list_head sibling; + struct list_head link; + int par_num; + int step; + struct word_node *parents[]; +}; + static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; @@ -61,22 +68,6 @@ static inline void list_del(struct list_head *entry) entry->next = entry->prev = NULL; } -struct word_node { - int step; - char *word; - struct list_head node; -}; - -struct word_tree { - char *word; - struct list_head sibling; - struct list_head link; - struct word_tree **parents; - int par_num; - int par_cap; - int step; -}; - static int BKDRHash(char* str, int size) { int seed = 131; // 31 131 1313 13131 131313 etc.. @@ -87,11 +78,11 @@ static int BKDRHash(char* str, int size) return hash % size; } -static struct word_node *find(char *word, struct list_head *hheads, int size, int step) +static struct word_node *find(char *word, struct list_head *dict, int size, int step) { struct list_head *p; int hash = BKDRHash(word, size); - list_for_each(p, &hheads[hash]) { + list_for_each(p, &dict[hash]) { struct word_node *node = list_entry(p, struct word_node, node); if (!strcmp(node->word, word)) { if (node->step == 0 || node->step == step) { @@ -102,48 +93,35 @@ static struct word_node *find(char *word, struct list_head *hheads, int size, in return NULL; } -static void parent_add(struct word_tree *parent, struct word_tree *child) -{ - if (child->par_num + 1 > child->par_cap) { - child->par_cap *= 2; - struct word_tree **parents = malloc(child->par_cap * sizeof(void *)); - memcpy(parents, child->parents, child->par_num * sizeof(void *)); - free(child->parents); - child->parents = parents; - } - child->parents[child->par_num++] = parent; -} - /** ** 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(). **/ -static char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordListSize, int* returnSize, int** returnColumnSizes) +char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordListSize, int* returnSize, int** returnColumnSizes) { - int i, j, k; - int len = strlen(beginWord); + int i, word_len = strlen(beginWord); int hashsize = wordListSize * 2; - char *word = malloc(len + 1); + char *word = malloc(word_len + 1); - struct list_head *hheads = malloc(hashsize * sizeof(*hheads)); + struct list_head *dict = malloc(hashsize * sizeof(*dict)); for (i = 0; i < hashsize; i++) { - INIT_LIST_HEAD(hheads + i); + INIT_LIST_HEAD(dict + i); } - struct list_head *level_heads = malloc(wordListSize * sizeof(*level_heads)); + struct list_head *level_caches = malloc(wordListSize * sizeof(*level_caches)); for (i = 0; i < wordListSize; i++) { - INIT_LIST_HEAD(&level_heads[i]); + INIT_LIST_HEAD(&level_caches[i]); } - /* Add into hash list */ + /* Word dictionary */ struct word_node *node; for (i = 0; i < wordListSize; i++) { node = malloc(sizeof(*node)); node->word = wordList[i]; node->step = 0; int hash = BKDRHash(wordList[i], hashsize); - list_add(&node->node, &hheads[hash]); + list_add(&node->node, &dict[hash]); } /* FIFO */ @@ -151,52 +129,52 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int INIT_LIST_HEAD(&queue); /* Build tree structure for BFS */ - struct word_tree *root = malloc(sizeof(*root)); + struct word_node *root = malloc(sizeof(*root) + sizeof(void *)); root->word = beginWord; root->step = 1; - root->par_cap = 1; root->par_num = 1; - root->parents = malloc(sizeof(void *)); root->parents[0] = NULL; - list_add_tail(&root->sibling, &level_heads[0]); - node = find(beginWord, hheads, hashsize, 1); + list_add_tail(&root->sibling, &level_caches[0]); + node = find(beginWord, dict, hashsize, 1); if (node != NULL) { node->step = 1; } - /* BFS with FIFO for shortest path */ - struct word_tree *first = root; + /* BFS with FIFO queue for shortest path */ + struct word_node *first = root; while (strcmp(first->word, endWord)) { strcpy(word, first->word); - for (i = 0; i < len; i++) { + for (i = 0; i < word_len; i++) { char c; char o = word[i]; for (c = 'a'; c <= 'z'; c++) { + if (c == o) continue; word[i] = c; - node = find(word, hheads, hashsize, first->step + 1); + node = find(word, dict, hashsize, first->step + 1); if (node != NULL) { int enqueue = 1; - list_for_each(p, &level_heads[first->step]) { - struct word_tree *w = list_entry(p, struct word_tree, sibling); - if (!strcmp(w->word, node->word)) { + /* Search in level cache in case of duplication */ + list_for_each(p, &level_caches[first->step]) { + struct word_node *w = list_entry(p, struct word_node, sibling); + /* Here we could just check if they are the same reference */ + if (w->word == node->word) { enqueue = 0; /* record the parant relation */ - parent_add(first, w); + w->parents[w->par_num++] = first; break; } } if (enqueue) { + /* new level cache and enqueue */ node->step = first->step + 1; - struct word_tree *new = malloc(sizeof(*new)); + struct word_node *new = malloc(sizeof(*new) + 15 * sizeof(void *)); new->word = node->word; new->step = node->step; - new->par_cap = 10; new->par_num = 0; - new->parents = malloc(new->par_cap * sizeof(void *)); - list_add_tail(&new->sibling, &level_heads[first->step]); + list_add_tail(&new->sibling, &level_caches[first->step]); list_add_tail(&new->link, &queue); - parent_add(first, new); + new->parents[new->par_num++] = first; } } } @@ -207,53 +185,53 @@ static char*** findLadders(char* beginWord, char* endWord, char** wordList, int *returnSize = 0; return NULL; } else { - first = list_first_entry(&queue, struct word_tree, link); + /* dequeue */ + first = list_first_entry(&queue, struct word_node, link); list_del(&first->link); } } - i = 0; + *returnSize = 0; int size = first->step; char ***results = malloc(1000 * sizeof(char **)); int *indexes = malloc(size * sizeof(int)); memset(indexes, 0, size * sizeof(int)); - struct word_tree **nodes = malloc(size * sizeof(*nodes)); - list_for_each(p, &level_heads[size - 1]) { - struct word_tree *end = list_entry(p, struct word_tree, sibling); + struct word_node **nodes = malloc(size * sizeof(*nodes)); + list_for_each(p, &level_caches[size - 1]) { + struct word_node *end = list_entry(p, struct word_node, sibling); if (!strcmp(end->word, endWord)) { int move_on = 1; while (move_on) { move_on = 0; - struct word_tree *w = end; - char **list = results[i] = malloc(size * sizeof(char *)); - for (j = size - 1; j >= 0; j--) { - list[j] = malloc(len + 1); - strcpy(list[j], w->word); - nodes[j] = w; - w = w->parents[indexes[j]]; + struct word_node *w = end; + char **list = results[*returnSize] = malloc(size * sizeof(char *)); + for (i = size - 1; i >= 0; i--) { + list[i] = malloc(word_len + 1); + strcpy(list[i], w->word); + nodes[i] = w; + w = w->parents[indexes[i]]; } /* Switch to another branch */ - for (j = 0; j < size; j++) { - if (indexes[j] < nodes[j]->par_num - 1) { - indexes[j]++; - /* Reset indexes of parents */ - memset(indexes, 0, j * sizeof(int)); + for (i = 0; i < size; i++) { + if (indexes[i] < nodes[i]->par_num - 1) { + indexes[i]++; + /* common prefix */ + memset(indexes, 0, i * sizeof(int)); move_on = 1; break; } } - i++; + (*returnSize)++; } } } - *returnColumnSizes = malloc(i * sizeof(int)); - for (j = 0; j < i; j++) { - (*returnColumnSizes)[j] = size; + *returnColumnSizes = malloc(*returnSize * sizeof(int)); + for (i = 0; i < *returnSize; i++) { + (*returnColumnSizes)[i] = size; } - *returnSize = i; return results; } From b6d20d96da82e918ae90170b09c13a31f4a3d3bf Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 9 Feb 2021 15:24:36 +0800 Subject: [PATCH 160/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0991_broken_calculator/Makefile | 2 ++ 0991_broken_calculator/calculator.c | 27 +++++++++++++++++++++++++++ 0991_broken_calculator/calculator.cc | 12 ++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 0991_broken_calculator/Makefile create mode 100644 0991_broken_calculator/calculator.c create mode 100644 0991_broken_calculator/calculator.cc diff --git a/0991_broken_calculator/Makefile b/0991_broken_calculator/Makefile new file mode 100644 index 0000000..b12a1c8 --- /dev/null +++ b/0991_broken_calculator/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test calculator.c diff --git a/0991_broken_calculator/calculator.c b/0991_broken_calculator/calculator.c new file mode 100644 index 0000000..810e7ac --- /dev/null +++ b/0991_broken_calculator/calculator.c @@ -0,0 +1,27 @@ +#include +#include + + +int brokenCalc(int X, int Y) +{ + int step = 0; + while (X < Y) { + Y = Y & 1 ? Y + 1 : Y / 2; + step++; + } + step += X - Y; + return step; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test x y"); + exit(-1); + } + + int x = atoi(argv[1]); + int y = atoi(argv[2]); + printf("%d\n", brokenCalc(x, y)); + return 0; +} diff --git a/0991_broken_calculator/calculator.cc b/0991_broken_calculator/calculator.cc new file mode 100644 index 0000000..64d459a --- /dev/null +++ b/0991_broken_calculator/calculator.cc @@ -0,0 +1,12 @@ +class Solution { +public: + int brokenCalc(int X, int Y) { + int step = 0; + while (X < Y) { + Y = Y & 1 ? Y + 1 : Y / 2; + step++; + } + step += X - Y; + return step; + } +}; From 425b077e58bd2af29a49defbb2108422aeaf5c97 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 10 Feb 2021 09:57:12 +0800 Subject: [PATCH 161/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0127_word_ladder/word_ladder.c | 26 +++++++++------- 0127_word_ladder/word_ladder.cc | 53 +++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 10 deletions(-) create mode 100644 0127_word_ladder/word_ladder.cc diff --git a/0127_word_ladder/word_ladder.c b/0127_word_ladder/word_ladder.c index 013d081..03b893f 100644 --- a/0127_word_ladder/word_ladder.c +++ b/0127_word_ladder/word_ladder.c @@ -1,5 +1,6 @@ #include #include +#include #include #define container_of(ptr, type, member) \ @@ -9,14 +10,10 @@ container_of(ptr, type, member) #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) #define list_for_each(p, head) \ for (p = (head)->next; p != (head); p = p->next) -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) - struct list_head { struct list_head *next, *prev; }; @@ -78,11 +75,11 @@ static int BKDRHash(char* str, int size) return hash % size; } -static struct word_node *find(char *word, struct list_head *hheads, int size) +static struct word_node *find(char *word, struct list_head *dict, int size) { struct list_head *p; int hash = BKDRHash(word, size); - list_for_each(p, &hheads[hash]) { + list_for_each(p, &dict[hash]) { struct word_node *node = list_entry(p, struct word_node, node); if (node->step == 0 && !strcmp(node->word, word)) { return node; @@ -98,18 +95,25 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor struct list_head queue; struct word_node *node; - struct list_head *hheads = malloc(wordListSize * sizeof(*hheads)); + struct list_head *dict = malloc(wordListSize * sizeof(*dict)); for (i = 0; i < wordListSize; i++) { - INIT_LIST_HEAD(hheads + i); + INIT_LIST_HEAD(dict + i); } /* Add into hash list */ + bool found = false; for (i = 0; i < wordListSize; i++) { node = malloc(sizeof(*node)); node->word = wordList[i]; node->step = 0; int hash = BKDRHash(wordList[i], wordListSize); - list_add(&node->node, &hheads[hash]); + list_add(&node->node, &dict[hash]); + if (!strcmp(endWord, wordList[i])) { + found = true; + } + } + if (!found) { + return 0; } /* FIFO */ @@ -127,8 +131,9 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor for (c = 'a'; c <= 'z'; c++) { if (c == o) continue; word[i] = c; - node = find(word, hheads, wordListSize); + node = find(word, dict, wordListSize); if (node != NULL) { + /* enqueue */ list_add_tail(&node->link, &queue); node->step = first->step + 1; } @@ -139,6 +144,7 @@ static int ladderLength(char* beginWord, char* endWord, char** wordList, int wor if (list_empty(&queue)) { return 0; } else { + /* dequeue */ first = list_first_entry(&queue, struct word_node, link); list_del(&first->link); } diff --git a/0127_word_ladder/word_ladder.cc b/0127_word_ladder/word_ladder.cc new file mode 100644 index 0000000..f88eaa6 --- /dev/null +++ b/0127_word_ladder/word_ladder.cc @@ -0,0 +1,53 @@ +#include + +using namespace std; + +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set dict(wordList.begin(), wordList.end()); + if (!dict.count(endWord)) { + return 0; + } + + // double BFS + int step = 1; + unordered_set s1, s2, tmp, visited; + s1.insert(beginWord); + s2.insert(endWord); + while (!s1.empty() && !s2.empty()) { + if (s1.size() > s2.size()) { + tmp = s1; + s1 = s2; + s2 = tmp; + } + tmp.clear(); + + for (auto str : s1) { + if (s2.count(str)) { + return step; + } + if (!visited.count(str)) { + visited.insert(str); + } + + for (int i = 0; i < str.length(); i++) { + char o = str[i]; + for (char c = 'a'; c <= 'z'; c++) { + if (c == o) continue; + str[i] = c; + if (dict.count(str) && !visited.count(str)) { + tmp.insert(str); + } + } + str[i] = o; + } + } + + // update + s1 = tmp; + step++; + } + return 0; + } +}; From ec1138ec6f1ab76301ad0ff2246a9f212026baf5 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 11 Feb 2021 16:40:20 +0800 Subject: [PATCH 162/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0050_pow/pow.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/0050_pow/pow.c b/0050_pow/pow.c index ce98a46..065e92f 100644 --- a/0050_pow/pow.c +++ b/0050_pow/pow.c @@ -2,7 +2,8 @@ #include #include -static double fast_pow(double x, int n) + +double fast_pow(double x, int n) { if (n == 0) { return 1.0; } if (n == 1) { return x; } @@ -10,7 +11,7 @@ static double fast_pow(double x, int n) return n & 1 ? t * t * x : t * t; } -static double my_pow(double x, int n) +double my_pow(double x, int n) { if (n == INT_MIN) { double t = 1 / fast_pow(x, -(n / 2)); From 8229f9423f0956488049ef58d92f5375e8239729 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 12 Feb 2021 19:59:33 +0800 Subject: [PATCH 163/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../concatenation.c | 88 ++++++++++-------- .../binary_tree_build.c | 88 +++++++++--------- .../binary_tree_build.c | 88 +++++++++--------- 0126_word_ladder_ii/word_ladder.c | 45 +++++---- 0127_word_ladder/word_ladder.c | 11 ++- .../consec_seq.c | 91 +++++++++--------- 0130_surrounded_regions/surrounded_regions.c | 18 ++-- 0133_clone_graph/clone_graph.c | 88 ++++++++---------- 0140_word_break_ii/word_break.c | 16 ++-- 0146_lru_cache/lru_cache.c | 92 ++++++++----------- 0149_max_points_on_a_line/points_on_line.c | 86 ++++++++--------- 0166_fraction_to_recurring_decimal/fraction.c | 75 +++++++-------- 0460_lfu_cache/lfu_cache.c | 28 +++--- 13 files changed, 395 insertions(+), 419 deletions(-) diff --git a/0030_substring_with_concatenation_of_all_words/concatenation.c b/0030_substring_with_concatenation_of_all_words/concatenation.c index aefda09..4018389 100644 --- a/0030_substring_with_concatenation_of_all_words/concatenation.c +++ b/0030_substring_with_concatenation_of_all_words/concatenation.c @@ -3,48 +3,67 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -struct hlist_node; +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -struct hlist_head { - struct hlist_node *first; +struct list_head { + struct list_head *next, *prev; }; -struct hlist_node { - struct hlist_node *next, **pprev; +struct word_node { + char *word; + int index; + struct list_head link; }; -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list->prev = list; } -static inline int hlist_empty(struct hlist_head *h) { - return !h->first; +static inline int list_empty(const struct list_head *head) +{ + return (head->next == head); } -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; } -struct word_node { - struct hlist_node node; - char *word; - int index; -}; +static inline void list_add(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head, head->next); +} + +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} + +static inline void __list_del(struct list_head *entry) +{ + entry->next->prev = entry->prev; + entry->prev->next = entry->next; +} + +static inline void list_del(struct list_head *entry) +{ + __list_del(entry); + entry->next = entry->prev = NULL; +} static inline int BKDRHash(char *s, size_t size) { @@ -56,12 +75,11 @@ static inline int BKDRHash(char *s, size_t size) return hash % size; } -static int find(char *word, struct hlist_head *heads, int size) +static int find(char *word, struct list_head *heads, int size) { + struct word_node *wn; int hash = BKDRHash(word, size); - struct hlist_node *pos; - hlist_for_each(pos, &heads[hash]) { - struct word_node *wn = list_entry(pos, struct word_node, node); + list_for_each_entry(wn, &heads[hash], link) { if (!strcmp(wn->word, word)) { return wn->index; } @@ -69,13 +87,11 @@ static int find(char *word, struct hlist_head *heads, int size) return -1; } -static void add(char **words, int index, struct hlist_head *heads, int size, int *freqs) +static void add(char **words, int index, struct list_head *heads, int size, int *freqs) { - int hash = BKDRHash(words[index], size); - struct hlist_node *pos; struct word_node *wn; - hlist_for_each(pos, &heads[hash]) { - wn = list_entry(pos, struct word_node, node); + int hash = BKDRHash(words[index], size); + list_for_each_entry(wn, &heads[hash], link) { if (!strcmp(wn->word, words[index])) { freqs[wn->index]++; return; @@ -84,7 +100,7 @@ static void add(char **words, int index, struct hlist_head *heads, int size, int wn = malloc(sizeof(*wn)); wn->word = words[index]; wn->index = index; - hlist_add_head(&wn->node, &heads[hash]); + list_add(&wn->link, &heads[hash]); freqs[wn->index]++; } @@ -101,9 +117,9 @@ static int *findSubstring(char *s, char **words, int wordsSize, int *returnSize) int i, j, cap = 10000, count = 0; int hash_size = wordsSize; - struct hlist_head *heads = malloc(hash_size * sizeof(*heads)); + struct list_head *heads = malloc(hash_size * sizeof(*heads)); for (i = 0; i < hash_size; i++) { - INIT_HLIST_HEAD(&heads[i]); + INIT_LIST_HEAD(&heads[i]); } int *freqs = malloc(wordsSize * sizeof(int)); 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 6162f06..f0be239 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 @@ -1,71 +1,67 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -struct hlist_node; +struct list_head { + struct list_head *next, *prev; +}; -struct hlist_head { - struct hlist_node *first; +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; }; -struct hlist_node { - struct hlist_node *next, **pprev; +struct order_node { + struct list_head link; + int val; + int index; }; -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list->prev = list; } -static inline int hlist_empty(struct hlist_head *h) { - return !h->first; +static inline int list_empty(const struct list_head *head) +{ + return (head->next == head); } -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; } -static inline void hlist_del(struct hlist_node *n) +static inline void list_add(struct list_head *_new, struct list_head *head) { - struct hlist_node *next = n->next; - struct hlist_node **pprev = n->pprev; - *pprev = next; - if (next != NULL) { - next->pprev = pprev; - } + __list_add(_new, head, head->next); } -struct TreeNode { - int val; - struct TreeNode *left; - struct TreeNode *right; -}; - -struct order_node { - struct hlist_node node; - int val; - int index; -}; +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} -static int find(int num, int size, struct hlist_head *heads) +static int find(int num, int size, struct list_head *heads) { - struct hlist_node *p; + struct order_node *on; int hash = (num < 0 ? -num : num) % size; - hlist_for_each(p, &heads[hash]) { - struct order_node *on = list_entry(p, struct order_node, node); + list_for_each_entry(on, &heads[hash], link) { if (num == on->val) { return on->index; } @@ -74,7 +70,7 @@ static int find(int num, int size, struct hlist_head *heads) } static struct TreeNode *dfs(int *preorder, int pre_low, int pre_high, int *inorder, - int in_low, int in_high, struct hlist_head *in_heads, int size) + int in_low, int in_high, struct list_head *in_heads, int size) { if (in_low > in_high || pre_low > pre_high) { return NULL; @@ -87,21 +83,21 @@ static struct TreeNode *dfs(int *preorder, int pre_low, int pre_high, int *inord return tn; } -static void node_add(int val, int index, int size, struct hlist_head *heads) +static void node_add(int val, int index, int size, struct list_head *heads) { struct order_node *on = malloc(sizeof(*on)); on->val = val; on->index = index; int hash = (val < 0 ? -val : val) % size; - hlist_add_head(&on->node, &heads[hash]); + list_add(&on->link, &heads[hash]); } -static struct TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize) +struct TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize) { int i; - struct hlist_head *in_heads = malloc(inorderSize * sizeof(*in_heads)); + struct list_head *in_heads = malloc(inorderSize * sizeof(*in_heads)); for (i = 0; i < inorderSize; i++) { - INIT_HLIST_HEAD(&in_heads[i]); + INIT_LIST_HEAD(&in_heads[i]); } for (i = 0; i < inorderSize; i++) { node_add(inorder[i], i, inorderSize, in_heads); 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 2edb121..b37dd41 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 @@ -1,71 +1,67 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -struct hlist_node; +struct list_head { + struct list_head *next, *prev; +}; -struct hlist_head { - struct hlist_node *first; +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; }; -struct hlist_node { - struct hlist_node *next, **prev; +struct order_node { + struct list_head link; + int val; + int index; }; -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list->prev = list; } -static inline int hlist_empty(struct hlist_head *h) { - return !h->first; +static inline int list_empty(const struct list_head *head) +{ + return (head->next == head); } -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { - if (h->first != NULL) { - h->first->prev = &n->next; - } - n->next = h->first; - n->prev = &h->first; - h->first = n; + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; } -static inline void hlist_del(struct hlist_node *n) +static inline void list_add(struct list_head *_new, struct list_head *head) { - struct hlist_node *next = n->next; - struct hlist_node **prev = n->prev; - *prev = next; - if (next != NULL) { - next->prev = prev; - } + __list_add(_new, head, head->next); } -struct TreeNode { - int val; - struct TreeNode *left; - struct TreeNode *right; -}; - -struct order_node { - struct hlist_node node; - int val; - int index; -}; +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} -static int find(int num, int size, struct hlist_head *heads) +static int find(int num, int size, struct list_head *heads) { - struct hlist_node *p; + struct order_node *on; int hash = (num < 0 ? -num : num) % size; - hlist_for_each(p, &heads[hash]) { - struct order_node *on = list_entry(p, struct order_node, node); + list_for_each_entry(on, &heads[hash], link) { if (num == on->val) { return on->index; } @@ -73,17 +69,17 @@ static int find(int num, int size, struct hlist_head *heads) return -1; } -static void node_add(int val, int index, int size, struct hlist_head *heads) +static void node_add(int val, int index, int size, struct list_head *heads) { struct order_node *on = malloc(sizeof(*on)); on->val = val; on->index = index; int hash = (val < 0 ? -val : val) % size; - hlist_add_head(&on->node, &heads[hash]); + list_add(&on->link, &heads[hash]); } static struct TreeNode *dfs(int *inorder, int in_lo, int in_hi, int *postorder, - int post_lo, int post_hi, struct hlist_head *in_heads, int size) + int post_lo, int post_hi, struct list_head *in_heads, int size) { if (in_lo > in_hi || post_lo > post_hi) { return NULL; @@ -96,12 +92,12 @@ static struct TreeNode *dfs(int *inorder, int in_lo, int in_hi, int *postorder, return tn; } -static struct TreeNode *buildTree(int *inorder, int inorderSize, int *postorder, int postorderSize) +struct TreeNode *buildTree(int *inorder, int inorderSize, int *postorder, int postorderSize) { int i; - struct hlist_head *in_heads = malloc(inorderSize * sizeof(*in_heads)); + struct list_head *in_heads = malloc(inorderSize * sizeof(*in_heads)); for (i = 0; i < inorderSize; i++) { - INIT_HLIST_HEAD(&in_heads[i]); + INIT_LIST_HEAD(&in_heads[i]); } for (i = 0; i < inorderSize; i++) { node_add(inorder[i], i, inorderSize, in_heads); diff --git a/0126_word_ladder_ii/word_ladder.c b/0126_word_ladder_ii/word_ladder.c index d34c196..963b6b4 100644 --- a/0126_word_ladder_ii/word_ladder.c +++ b/0126_word_ladder_ii/word_ladder.c @@ -1,3 +1,4 @@ +#include #include #include #include @@ -11,8 +12,10 @@ #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) struct list_head { struct list_head *next, *prev; @@ -80,10 +83,9 @@ static int BKDRHash(char* str, int size) static struct word_node *find(char *word, struct list_head *dict, int size, int step) { - struct list_head *p; + struct word_node *node; int hash = BKDRHash(word, size); - list_for_each(p, &dict[hash]) { - struct word_node *node = list_entry(p, struct word_node, node); + list_for_each_entry(node, &dict[hash], node) { if (!strcmp(node->word, word)) { if (node->step == 0 || node->step == step) { return node; @@ -115,17 +117,25 @@ char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordLis } /* Word dictionary */ - struct word_node *node; + *returnSize = 0; + bool found = false; + struct word_node *node, *wn; for (i = 0; i < wordListSize; i++) { node = malloc(sizeof(*node)); node->word = wordList[i]; node->step = 0; int hash = BKDRHash(wordList[i], hashsize); list_add(&node->node, &dict[hash]); + if (!strcmp(endWord, wordList[i])) { + found = true; + } + } + if (!found) { + return NULL; } /* FIFO */ - struct list_head *p, queue; + struct list_head queue; INIT_LIST_HEAD(&queue); /* Build tree structure for BFS */ @@ -154,13 +164,12 @@ char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordLis if (node != NULL) { int enqueue = 1; /* Search in level cache in case of duplication */ - list_for_each(p, &level_caches[first->step]) { - struct word_node *w = list_entry(p, struct word_node, sibling); + list_for_each_entry(wn, &level_caches[first->step], sibling) { /* Here we could just check if they are the same reference */ - if (w->word == node->word) { + if (wn->word == node->word) { enqueue = 0; /* record the parant relation */ - w->parents[w->par_num++] = first; + wn->parents[wn->par_num++] = first; break; } } @@ -182,7 +191,6 @@ char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordLis } if (list_empty(&queue)) { - *returnSize = 0; return NULL; } else { /* dequeue */ @@ -191,25 +199,24 @@ char*** findLadders(char* beginWord, char* endWord, char** wordList, int wordLis } } - *returnSize = 0; int size = first->step; char ***results = malloc(1000 * sizeof(char **)); int *indexes = malloc(size * sizeof(int)); memset(indexes, 0, size * sizeof(int)); struct word_node **nodes = malloc(size * sizeof(*nodes)); - list_for_each(p, &level_caches[size - 1]) { - struct word_node *end = list_entry(p, struct word_node, sibling); + struct word_node *end; + list_for_each_entry(end, &level_caches[size - 1], sibling) { if (!strcmp(end->word, endWord)) { int move_on = 1; while (move_on) { move_on = 0; - struct word_node *w = end; + wn = end; char **list = results[*returnSize] = malloc(size * sizeof(char *)); for (i = size - 1; i >= 0; i--) { list[i] = malloc(word_len + 1); - strcpy(list[i], w->word); - nodes[i] = w; - w = w->parents[indexes[i]]; + strcpy(list[i], wn->word); + nodes[i] = wn; + wn = wn->parents[indexes[i]]; } /* Switch to another branch */ diff --git a/0127_word_ladder/word_ladder.c b/0127_word_ladder/word_ladder.c index 03b893f..dc12247 100644 --- a/0127_word_ladder/word_ladder.c +++ b/0127_word_ladder/word_ladder.c @@ -11,8 +11,10 @@ #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) struct list_head { struct list_head *next, *prev; @@ -77,10 +79,9 @@ static int BKDRHash(char* str, int size) static struct word_node *find(char *word, struct list_head *dict, int size) { - struct list_head *p; + struct word_node *node; int hash = BKDRHash(word, size); - list_for_each(p, &dict[hash]) { - struct word_node *node = list_entry(p, struct word_node, node); + list_for_each_entry(node, &dict[hash], node) { if (node->step == 0 && !strcmp(node->word, word)) { return node; } diff --git a/0128_longest_consecutive_sequence/consec_seq.c b/0128_longest_consecutive_sequence/consec_seq.c index 075844e..3d52eda 100644 --- a/0128_longest_consecutive_sequence/consec_seq.c +++ b/0128_longest_consecutive_sequence/consec_seq.c @@ -1,69 +1,72 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - -struct hlist_node; +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -struct hlist_head { - struct hlist_node *first; +struct list_head { + struct list_head *next, *prev; }; -struct hlist_node { - struct hlist_node *next, **pprev; +struct seq_node { + int num; + struct list_head link; }; -static inline void INIT_HLIST_HEAD(struct hlist_head *h) +static inline void INIT_LIST_HEAD(struct list_head *list) { - h->first = NULL; + list->next = list->prev = list; } -static inline int hlist_empty(struct hlist_head *h) +static inline int list_empty(const struct list_head *head) { - return !h->first; + return (head->next == head); } -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; } -static inline void hlist_del(struct hlist_node *n) +static inline void list_add(struct list_head *_new, struct list_head *head) { - struct hlist_node *next = n->next; - struct hlist_node **pprev = n->pprev; - *pprev = next; - if (next != NULL) { - next->pprev = pprev; - } + __list_add(_new, head, head->next); } -struct seq_node { - int num; - struct hlist_node node; -}; +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} + +static inline void __list_del(struct list_head *entry) +{ + entry->next->prev = entry->prev; + entry->prev->next = entry->next; +} -static struct seq_node *find(int num, int size, struct hlist_head *heads) +static inline void list_del(struct list_head *entry) { + __list_del(entry); + entry->next = entry->prev = NULL; +} + +static struct seq_node *find(int num, int size, struct list_head *heads) +{ + struct seq_node *node; int hash = num < 0 ? -num % size : num % size; - struct hlist_node *pos; - hlist_for_each(pos, &heads[hash]) { - struct seq_node *node = list_entry(pos, struct seq_node, node); + list_for_each_entry(node, &heads[hash], link) { if (node->num == num) { return node; } @@ -71,14 +74,14 @@ static struct seq_node *find(int num, int size, struct hlist_head *heads) return NULL; } -static int longestConsecutive(int* nums, int numsSize) +int longestConsecutive(int* nums, int numsSize) { int i, hash, length = 0; struct seq_node *node; - struct hlist_head *heads = malloc(numsSize * sizeof(*heads)); + struct list_head *heads = malloc(numsSize * sizeof(*heads)); for (i = 0; i < numsSize; i++) { - INIT_HLIST_HEAD(&heads[i]); + INIT_LIST_HEAD(&heads[i]); } for (i = 0; i < numsSize; i++) { @@ -86,7 +89,7 @@ static int longestConsecutive(int* nums, int numsSize) hash = nums[i] < 0 ? -nums[i] % numsSize : nums[i] % numsSize; node = malloc(sizeof(*node)); node->num = nums[i]; - hlist_add_head(&node->node, &heads[hash]); + list_add(&node->link, &heads[hash]); } } @@ -97,18 +100,18 @@ static int longestConsecutive(int* nums, int numsSize) while (node != NULL) { len++; num = node->num; - hlist_del(&node->node); + list_del(&node->link); int left = num; while ((node = find(--left, numsSize, heads)) != NULL) { len++; - hlist_del(&node->node); + list_del(&node->link); } int right = num; while ((node = find(++right, numsSize, heads)) != NULL) { len++; - hlist_del(&node->node); + list_del(&node->link); } length = len > length ? len : length; diff --git a/0130_surrounded_regions/surrounded_regions.c b/0130_surrounded_regions/surrounded_regions.c index 304b4c7..ab2cf6d 100644 --- a/0130_surrounded_regions/surrounded_regions.c +++ b/0130_surrounded_regions/surrounded_regions.c @@ -2,6 +2,7 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) @@ -9,18 +10,16 @@ container_of(ptr, type, member) #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) -#define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) - -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) - -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) struct list_head { struct list_head *next, *prev; }; +struct node { + int x, y; + struct list_head link; +}; + static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; @@ -61,11 +60,6 @@ static inline void list_del(struct list_head *entry) entry->next = entry->prev = NULL; } -struct node { - struct list_head link; - int x, y; -}; - static struct node *node_new(struct list_head *free_list) { struct node *new; diff --git a/0133_clone_graph/clone_graph.c b/0133_clone_graph/clone_graph.c index e6ef47c..748c342 100644 --- a/0133_clone_graph/clone_graph.c +++ b/0133_clone_graph/clone_graph.c @@ -1,7 +1,6 @@ #include #include -#define NEIGHBORS_MAX_SIZE 100 #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) @@ -9,67 +8,59 @@ #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) - -struct hlist_node; +struct list_head { + struct list_head *next, *prev; +}; -struct hlist_head { - struct hlist_node *first; +struct UndirectedGraphNode { + int label; + struct UndirectedGraphNode *neighbors[100]; + int neighborsCount; }; -struct hlist_node { - struct hlist_node *next, **pprev; +struct label_node { + struct list_head link; + struct UndirectedGraphNode *gn; }; -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list->prev = list; } -static inline int hlist_empty(struct hlist_head *h) { - return !h->first; +static inline int list_empty(const struct list_head *head) +{ + return (head->next == head); } -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; } -static inline void hlist_del(struct hlist_node *n) +static inline void list_add(struct list_head *_new, struct list_head *head) { - struct hlist_node *next = n->next; - struct hlist_node **pprev = n->pprev; - *pprev = next; - if (next != NULL) { - next->pprev = pprev; - } + __list_add(_new, head, head->next); } -struct UndirectedGraphNode { - int label; - struct UndirectedGraphNode *neighbors[NEIGHBORS_MAX_SIZE]; - int neighborsCount; -}; - -struct label_node { - struct UndirectedGraphNode *gn; - struct hlist_node node; -}; +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} -static struct UndirectedGraphNode *find(int label, int size, struct hlist_head *heads) +static struct UndirectedGraphNode *find(int label, int size, struct list_head *heads) { + struct label_node *ln; int hash = (label < 0 ? -label : label) % size; - struct hlist_node *p; - hlist_for_each(p, &heads[hash]) { - struct label_node *ln = list_entry(p, struct label_node, node); + list_for_each_entry(ln, &heads[hash], link) { if (ln->gn->label == label) { return ln->gn; } @@ -77,7 +68,7 @@ static struct UndirectedGraphNode *find(int label, int size, struct hlist_head * return NULL; } -static struct UndirectedGraphNode *dfs(struct UndirectedGraphNode *graph, struct hlist_head *heads, int size) +static struct UndirectedGraphNode *dfs(struct UndirectedGraphNode *graph, struct list_head *heads, int size) { if (graph == NULL) { return NULL; @@ -94,7 +85,7 @@ static struct UndirectedGraphNode *dfs(struct UndirectedGraphNode *graph, struct struct label_node *ln = malloc(sizeof(*ln)); ln->gn = node; int hash = (node->label < 0 ? -node->label : node->label) % size; - hlist_add_head(&ln->node, &heads[hash]); + list_add(&ln->link, &heads[hash]); int i; for (i = 0; i < node->neighborsCount; i++) { @@ -104,14 +95,13 @@ static struct UndirectedGraphNode *dfs(struct UndirectedGraphNode *graph, struct return node; } -static struct UndirectedGraphNode *cloneGraph(struct UndirectedGraphNode *graph) +struct UndirectedGraphNode *cloneGraph(struct UndirectedGraphNode *graph) { int i, cap = 1000; - struct hlist_head *heads = malloc(cap * sizeof(*heads)); + struct list_head *heads = malloc(cap * sizeof(*heads)); for (i = 0; i < cap; i++) { - INIT_HLIST_HEAD(&heads[i]); + INIT_LIST_HEAD(&heads[i]); } - return dfs(graph, heads, cap); } diff --git a/0140_word_break_ii/word_break.c b/0140_word_break_ii/word_break.c index 625ff92..e987eae 100644 --- a/0140_word_break_ii/word_break.c +++ b/0140_word_break_ii/word_break.c @@ -9,8 +9,10 @@ #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) struct list_head { struct list_head *next, *prev; @@ -83,9 +85,8 @@ static struct solution *dfs(char *s, char **words, int *lens, int size, /* Append all sub-solutions */ INIT_LIST_HEAD(&sol->heads[j]); new_word_add(&sol->heads[j], words[i]); - struct list_head *p; - list_for_each(p, &sub_sol->heads[j - k]) { - struct word_node *wn = list_entry(p, struct word_node, link); + struct word_node *wn; + list_for_each_entry(wn, &sub_sol->heads[j - k], link) { new_word_add(&sol->heads[j], wn->word); } sol->count++; @@ -130,9 +131,8 @@ char **wordBreak(char* s, char** wordDict, int wordDictSize, int *returnSize) for (i = 0; i < sol->count; i++) { results[i] = malloc(total + 100); char *p = results[i]; - struct list_head *n; - list_for_each(n, &sol->heads[i]) { - struct word_node *wn = list_entry(n, struct word_node, link); + struct word_node *wn; + list_for_each_entry(wn, &sol->heads[i], link) { char *q = wn->word; while ((*p++ = *q++) != '\0') {} *(p - 1) = ' '; diff --git a/0146_lru_cache/lru_cache.c b/0146_lru_cache/lru_cache.c index e268453..79c8cf5 100644 --- a/0146_lru_cache/lru_cache.c +++ b/0146_lru_cache/lru_cache.c @@ -10,30 +10,46 @@ #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) #define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) +#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); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) struct list_head { struct list_head *next, *prev; }; -static inline void -INIT_LIST_HEAD(struct list_head *list) +typedef struct { + int capacity; + int count; + struct list_head dhead; + struct list_head hheads[]; +} LRUCache; + +typedef struct { + int key; + int value; + struct list_head hlink; + struct list_head dlink; +} LRUNode; + +static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list->prev = list; } -static inline int -list_empty(const struct list_head *head) +static inline int list_empty(const struct list_head *head) { return (head->next == head); } -static inline void -__list_add(struct list_head *new, struct list_head *prev, struct list_head *next) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { next->prev = new; new->next = next; @@ -41,61 +57,40 @@ __list_add(struct list_head *new, struct list_head *prev, struct list_head *next prev->next = new; } -static inline void -list_add(struct list_head *_new, struct list_head *head) +static inline void list_add(struct list_head *_new, struct list_head *head) { __list_add(_new, head, head->next); } -static inline void -list_add_tail(struct list_head *_new, struct list_head *head) +static inline void list_add_tail(struct list_head *_new, struct list_head *head) { __list_add(_new, head->prev, head); } -static inline void -__list_del(struct list_head *entry) +static inline void __list_del(struct list_head *entry) { entry->next->prev = entry->prev; entry->prev->next = entry->next; } -static inline void -list_del(struct list_head *entry) +static inline void list_del(struct list_head *entry) { __list_del(entry); entry->next = entry->prev = NULL; } -static inline void -list_move(struct list_head *list, struct list_head *head) +static inline void list_move(struct list_head *list, struct list_head *head) { __list_del(list); list_add(list, head); } -static inline void -list_move_tail(struct list_head *entry, struct list_head *head) +static inline void list_move_tail(struct list_head *entry, struct list_head *head) { __list_del(entry); list_add_tail(entry, head); } -typedef struct { - int capacity; - int count; - struct list_head dhead; - struct list_head hheads[]; -} LRUCache; - -typedef struct { - int key; - int value; - struct list_head hlink; - struct list_head dlink; -} LRUNode; - - LRUCache *lRUCacheCreate(int capacity) { int i; @@ -111,9 +106,8 @@ LRUCache *lRUCacheCreate(int capacity) void lRUCacheFree(LRUCache *obj) { - struct list_head *pos, *n; - list_for_each_safe(pos, n, &obj->dhead) { - LRUNode *lru = list_entry(pos, LRUNode, dlink); + LRUNode *lru, *n; + list_for_each_entry_safe(lru, n, &obj->dhead, dlink) { list_del(&lru->dlink); free(lru); } @@ -122,10 +116,9 @@ void lRUCacheFree(LRUCache *obj) int lRUCacheGet(LRUCache *obj, int key) { + LRUNode *lru; int hash = key % obj->capacity; - struct list_head *pos; - list_for_each(pos, &obj->hheads[hash]) { - LRUNode *lru = list_entry(pos, LRUNode, hlink); + list_for_each_entry(lru, &obj->hheads[hash], hlink) { if (lru->key == key) { /* Move it to header */ list_move(&lru->dlink, &obj->dhead); @@ -139,9 +132,7 @@ void lRUCachePut(LRUCache *obj, int key, int value) { LRUNode *lru; int hash = key % obj->capacity; - struct list_head *pos; - list_for_each(pos, &obj->hheads[hash]) { - lru = list_entry(pos, LRUNode, hlink); + list_for_each_entry(lru, &obj->hheads[hash], hlink) { if (lru->key == key) { list_move(&lru->dlink, &obj->dhead); lru->value = value; @@ -172,9 +163,8 @@ void lRUCacheDump(LRUCache *obj) printf(">>> Total %d nodes: \n", obj->count); for (i = 0; i < obj->count; i++) { printf("hash:%d:", i); - struct list_head *pos; - list_for_each(pos, &obj->hheads[i]) { - lru = list_entry(pos, LRUNode, hlink); + list_for_each_entry(lru, &obj->hheads[i], hlink) { + lru = list_entry(lru, LRUNode, hlink); if (lru != NULL) { printf(" (%d %d)", lru->key, lru->value); } @@ -183,9 +173,7 @@ void lRUCacheDump(LRUCache *obj) } printf(">>> Double list dump\n"); - struct list_head *p; - list_for_each(p, &obj->dhead) { - lru = list_entry(p, LRUNode, dlink); + list_for_each_entry(lru, &obj->dhead, dlink) { printf("(%d %d)\n", lru->key, lru->value); } } 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 96c0122..3291c69 100644 --- a/0149_max_points_on_a_line/points_on_line.c +++ b/0149_max_points_on_a_line/points_on_line.c @@ -3,71 +3,64 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -struct hlist_node; +struct list_head { + struct list_head *next, *prev; +}; -struct hlist_head { - struct hlist_node *first; +struct Point { + int x, y; }; -struct hlist_node { - struct hlist_node *next, **pprev; +struct point_node { + int p1; + int p2; + struct list_head link; }; -static inline void INIT_HLIST_HEAD(struct hlist_head *h) { - h->first = NULL; +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list->prev = list; } -static inline int hlist_empty(struct hlist_head *h) { - return !h->first; +static inline int list_empty(const struct list_head *head) +{ + return (head->next == head); } -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; } -static inline void hlist_del(struct hlist_node *n) +static inline void list_add(struct list_head *_new, struct list_head *head) { - struct hlist_node *next = n->next; - struct hlist_node **pprev = n->pprev; - *pprev = next; - if (next != NULL) { - next->pprev = pprev; - } + __list_add(_new, head, head->next); } -struct Point { - int x, y; -}; - -struct point_node { - int p1; - int p2; - struct hlist_node node; -}; +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} -static bool can_insert(struct hlist_head *head, int p1, int p2) +static bool can_insert(struct list_head *head, int p1, int p2) { - struct hlist_node *pos; - hlist_for_each(pos, head) { - struct point_node *pn = list_entry(pos, struct point_node, node); + struct point_node *pn; + list_for_each_entry(pn, head, link) { return p1 == pn->p1; } return true; @@ -102,9 +95,9 @@ static int maxPoints(struct Point *points, int pointsSize) dup_cnts[i] = 1; } - struct hlist_head *heads = malloc(slope_size * sizeof(*heads)); + struct list_head *heads = malloc(slope_size * sizeof(*heads)); for (i = 0; i < slope_size; i++) { - INIT_HLIST_HEAD(&heads[i]); + INIT_LIST_HEAD(&heads[i]); } for (i = 0; i < pointsSize; i++) { @@ -139,17 +132,16 @@ static int maxPoints(struct Point *points, int pointsSize) struct point_node *pn = malloc(sizeof(*pn)); pn->p1 = i; pn->p2 = j; - hlist_add_head(&pn->node, &heads[hash]); + list_add(&pn->link, &heads[hash]); } } } } for (i = 0; i < slope_size; i++) { - struct hlist_node *pos; int index = -1; - hlist_for_each(pos, &heads[i]) { - struct point_node *pn = list_entry(pos, struct point_node, node); + struct point_node *pn; + list_for_each_entry(pn, &heads[i], link) { index = pn->p1; slope_cnts[i]++; } diff --git a/0166_fraction_to_recurring_decimal/fraction.c b/0166_fraction_to_recurring_decimal/fraction.c index fbb1db5..b2c7a8b 100644 --- a/0166_fraction_to_recurring_decimal/fraction.c +++ b/0166_fraction_to_recurring_decimal/fraction.c @@ -3,70 +3,61 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) #define list_entry(ptr, type, member) \ container_of(ptr, type, member) -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos; pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; true; }); pos = n) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -struct hlist_node; - -struct hlist_head { - struct hlist_node *first; +struct list_head { + struct list_head *next, *prev; }; -struct hlist_node { - struct hlist_node *next, **pprev; +struct rem_node { + int key; + int index; + struct list_head link; }; -static inline void INIT_HLIST_HEAD(struct hlist_head *h) +static inline void INIT_LIST_HEAD(struct list_head *list) { - h->first = NULL; + list->next = list->prev = list; } -static inline int hlist_empty(struct hlist_head *h) +static inline int list_empty(const struct list_head *head) { - return !h->first; + return (head->next == head); } -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next) { - if (h->first != NULL) { - h->first->pprev = &n->next; - } - n->next = h->first; - n->pprev = &h->first; - h->first = n; + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; } -static inline void hlist_del(struct hlist_node *n) +static inline void list_add(struct list_head *_new, struct list_head *head) { - struct hlist_node *next = n->next; - struct hlist_node **pprev = n->pprev; - *pprev = next; - if (next != NULL) { - next->pprev = pprev; - } + __list_add(_new, head, head->next); } -struct rem_node { - struct hlist_node node; - int key; - int index; -}; +static inline void list_add_tail(struct list_head *_new, struct list_head *head) +{ + __list_add(_new, head->prev, head); +} -static int find(struct hlist_head *heads, int size, int key) +static int find(struct list_head *heads, int size, int key) { + struct rem_node *node; int hash = key % size; - struct hlist_node *pos; - hlist_for_each(pos, &heads[hash]) { - struct rem_node *node = list_entry(pos, struct rem_node, node); + list_for_each_entry(node, &heads[hash], link) { if (key == node->key) { return node->index; } @@ -74,7 +65,7 @@ static int find(struct hlist_head *heads, int size, int key) return -1; } -static char* fractionToDecimal(int numerator, int denominator) +char* fractionToDecimal(int numerator, int denominator) { int size = 1024; char *result = malloc(size); @@ -129,9 +120,9 @@ static char* fractionToDecimal(int numerator, int denominator) char *q = decimal; size = 1333; - struct hlist_head *heads = malloc(size * sizeof(*heads)); + struct list_head *heads = malloc(size * sizeof(*heads)); for (i = 0; i < size; i++) { - INIT_HLIST_HEAD(&heads[i]); + INIT_LIST_HEAD(&heads[i]); } i = 0; @@ -154,7 +145,7 @@ static char* fractionToDecimal(int numerator, int denominator) node->index = i; int hash = remainder % size; - hlist_add_head(&node->node, &heads[hash]); + list_add(&node->link, &heads[hash]); *q++ = (remainder * 10) / d + '0'; remainder = (remainder * 10) % d; diff --git a/0460_lfu_cache/lfu_cache.c b/0460_lfu_cache/lfu_cache.c index c77ba2c..a902948 100644 --- a/0460_lfu_cache/lfu_cache.c +++ b/0460_lfu_cache/lfu_cache.c @@ -2,6 +2,7 @@ #include #include + #define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (size_t)&(((type *)0)->member))) @@ -11,11 +12,16 @@ #define list_first_entry(ptr, type, field) list_entry((ptr)->next, type, field) #define list_last_entry(ptr, type, field) list_entry((ptr)->prev, type, field) -#define list_for_each(p, head) \ - for (p = (head)->next; p != (head); p = p->next) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &(pos)->member != (head); \ + pos = list_entry((pos)->member.next, typeof(*pos), member)) -#define list_for_each_safe(p, n, head) \ - for (p = (head)->next, n = p->next; p != (head); p = n, n = p->next) +#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); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) struct list_head { struct list_head *next, *prev; @@ -348,10 +354,9 @@ int lFUCacheGet(LFUCache* obj, int key) return; } - struct list_head *pos; + LFUNode *lfu; int hash = key % obj->capacity; - list_for_each(pos, &obj->hheads[hash]) { - LFUNode *lfu = list_entry(pos, LFUNode, key_link); + list_for_each_entry(lfu, &obj->hheads[hash], key_link) { if (lfu->key == key) { freq_incr(obj->tree, lfu, key); return lfu->val; @@ -368,9 +373,7 @@ void lFUCachePut(LFUCache* obj, int key, int value) LFUNode *lfu; int hash = key % obj->capacity; - struct list_head *pos; - list_for_each(pos, &obj->hheads[hash]) { - lfu = list_entry(pos, LFUNode, key_link); + list_for_each(lfu, &obj->hheads[hash], key_link) { if (lfu->key == key) { freq_incr(obj->tree, lfu, key); lfu->val = value; @@ -404,9 +407,8 @@ void lFUCacheFree(LFUCache* obj) { int i; for (i = 0; i < obj->capacity; i++) { - struct list_head *pos, *n; - list_for_each_safe(pos, n, &obj->hheads[i]) { - LFUNode *lfu = list_entry(pos, LFUNode, key_link); + LFUNode *lfu, *n; + list_for_each_entry_safe(lfu, n, &obj->hheads[i], key_link) { list_del(&lfu->dlink); list_del(&lfu->key_link); free(lfu); From 9fa2dd432e1487085e8542d79eafa0c97501336b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 13 Feb 2021 21:22:08 +0800 Subject: [PATCH 164/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0027_remove_element/rm_elem.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/0027_remove_element/rm_elem.c b/0027_remove_element/rm_elem.c index 21109fb..6e56505 100644 --- a/0027_remove_element/rm_elem.c +++ b/0027_remove_element/rm_elem.c @@ -1,7 +1,8 @@ #include #include -static int removeElement(int *nums, int numsSize, int val) + +int removeElement(int *nums, int numsSize, int val) { int i, count = 0; for (i = 0; i < numsSize; i++) { From 04c30efa3f78150f3a2c5efdbfced7ad03bddfdc Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 14 Feb 2021 21:18:20 +0800 Subject: [PATCH 165/211] Add C++ implementation Signed-off-by: begeekmyfriend --- .../longest_substring_without_repeat.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 701efa4..7af62c6 100644 --- a/0003_longest_substring_without_repeat/longest_substring_without_repeat.c +++ b/0003_longest_substring_without_repeat/longest_substring_without_repeat.c @@ -2,7 +2,8 @@ #include #include -static int lengthOfLongestSubstring(char *s) + +int lengthOfLongestSubstring(char *s) { int offset[128]; int max_len = 0; From da4cae3069dac1940272f9b06e7934b58e25b66b Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 15 Feb 2021 23:02:09 +0800 Subject: [PATCH 166/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0129_sum_root_to_leaf_numbers/sum_tree.c | 8 +++-- 0129_sum_root_to_leaf_numbers/sum_tree.cc | 42 +++++++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 0129_sum_root_to_leaf_numbers/sum_tree.cc diff --git a/0129_sum_root_to_leaf_numbers/sum_tree.c b/0129_sum_root_to_leaf_numbers/sum_tree.c index 686b3d8..8580e8b 100644 --- a/0129_sum_root_to_leaf_numbers/sum_tree.c +++ b/0129_sum_root_to_leaf_numbers/sum_tree.c @@ -1,6 +1,7 @@ #include #include + struct TreeNode { int val; struct TreeNode *left; @@ -9,12 +10,13 @@ struct TreeNode { static int dfs(struct TreeNode* node, int sum) { - int total = 0; + /* Here we have to use pre-order */ + /* sum must be in argument stack of recusion.*/ sum = sum * 10 + node->val; - if (node->left == NULL && node->right == NULL) { return sum; } else { + int total = 0; if (node->left != NULL) { total += dfs(node->left, sum); } @@ -25,7 +27,7 @@ static int dfs(struct TreeNode* node, int sum) } } -static int sumNumbers(struct TreeNode* root) +int sumNumbers(struct TreeNode* root) { if (root == NULL) { return 0; diff --git a/0129_sum_root_to_leaf_numbers/sum_tree.cc b/0129_sum_root_to_leaf_numbers/sum_tree.cc new file mode 100644 index 0000000..5269090 --- /dev/null +++ b/0129_sum_root_to_leaf_numbers/sum_tree.cc @@ -0,0 +1,42 @@ +#include + +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int sumNumbers(TreeNode* root) { + if (root == nullptr) { + return 0; + } + return dfs(root, 0); + } +private: + int dfs(TreeNode *root, int sum) { + // Here we have to use pre-order. + // sum must be in argument stack of recusion. + sum = sum * 10 + root->val; + if (root->left == nullptr && root->right == nullptr) { + return sum; + } else { + int total = 0; + if (root->left != nullptr) { + total += dfs(root->left, sum); + } + if (root->right != nullptr) { + total += dfs(root->right, sum); + } + return total; + } + } +}; From 887c77f33a0ec05c3a02f16c662bb33af0574670 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 16 Feb 2021 22:51:31 +0800 Subject: [PATCH 167/211] Add C++ implemention Signed-off-by: begeekmyfriend --- 1143_longest_common_subsequence/Makefile | 2 ++ 1143_longest_common_subsequence/lcs.c | 46 ++++++++++++++++++++++++ 1143_longest_common_subsequence/lcs.cc | 26 ++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 1143_longest_common_subsequence/Makefile create mode 100644 1143_longest_common_subsequence/lcs.c create mode 100644 1143_longest_common_subsequence/lcs.cc diff --git a/1143_longest_common_subsequence/Makefile b/1143_longest_common_subsequence/Makefile new file mode 100644 index 0000000..5b6f54f --- /dev/null +++ b/1143_longest_common_subsequence/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test lcs.c diff --git a/1143_longest_common_subsequence/lcs.c b/1143_longest_common_subsequence/lcs.c new file mode 100644 index 0000000..8171754 --- /dev/null +++ b/1143_longest_common_subsequence/lcs.c @@ -0,0 +1,46 @@ +#include +#include +#include + + +static int max(int a, int b) +{ + return a > b ? a : b; +} + +int longestCommonSubsequence(char * text1, char * text2) +{ + int i, j; + int l1 = strlen(text1); + int l2 = strlen(text2); + int **dp = malloc((l1 + 1) * sizeof(int *)); + for (i = 0; i < l1 + 1; i++) { + dp[i] = malloc((l2 + 1) * sizeof(int)); + } + memset(dp[0], 0, (l2 + 1) * sizeof(int)); + for (i = 1; i <= l1; i++) { + dp[i][0] = 0; + } + + for (i = 1; i <= l1; i++) { + for (j = 1; j <= l2; j++) { + if (text1[i - 1] == text2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[l1][l2]; +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "Usage: ./test s1 s2\n"); + exit(-1); + } + + printf("%d\n", longestCommonSubsequence(argv[1], argv[2])); + return 0; +} diff --git a/1143_longest_common_subsequence/lcs.cc b/1143_longest_common_subsequence/lcs.cc new file mode 100644 index 0000000..78c7cac --- /dev/null +++ b/1143_longest_common_subsequence/lcs.cc @@ -0,0 +1,26 @@ +#include + +using namespace std; + +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + int l1 = text1.length(); + int l2 = text2.length(); + vector dp(l2 + 1); + int up = 0; + for (int i = 1; i <= l1; i++) { + int left_up = 0; + for (int j = 1; j <= l2; j++) { + up = dp[j]; + if (text1[i - 1] == text2[j - 1]) { + dp[j] = left_up + 1; + } else { + dp[j] = max(up, dp[j - 1]); + } + left_up = up; + } + } + return dp[l2]; + } +}; From 769617debe81cfcc66cbc8085fcfdd0a44877e46 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 17 Feb 2021 21:24:18 +0800 Subject: [PATCH 168/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0072_edit_distance/edit_distance.cc | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/0072_edit_distance/edit_distance.cc b/0072_edit_distance/edit_distance.cc index deb09f8..deec40e 100644 --- a/0072_edit_distance/edit_distance.cc +++ b/0072_edit_distance/edit_distance.cc @@ -5,25 +5,27 @@ using namespace std; class Solution { public: int minDistance(string word1, string word2) { - vector> dp; - for (int i = 0; i <= word1.length(); i++) { - dp.push_back(vector(word2.length() + 1)); - dp[i][0] = i; - } - for (int i = 0; i <= word2.length(); i++) { - dp[0][i] = i; + int l1 = word1.length(); + int l2 = word2.length(); + vector dp(l2 + 1); + for (int i = 0; i <= l2; i++) { + dp[i] = i; } - for (int i = 1; i <= word1.length(); i++) { - for (int j = 1; j <= word2.length(); j++) { + int up = 0; + for (int i = 1; i <= l1; i++) { + int left_up = dp[0]; + dp[0] = i; + for (int j = 1; j <= l2; j++) { + up = dp[j]; if (word1[i - 1] == word2[j - 1]) { - dp[i][j] = dp[i - 1][j - 1]; + dp[j] = left_up; } else { - dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])); + dp[j] = 1 + min(left_up, min(up, dp[j - 1])); } + left_up = up; } } - - return dp[word1.length()][word2.length()]; + return dp[l2]; } }; From 84dd3f80f2126581d910ba0db6852c8c0a7598a3 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Wed, 17 Feb 2021 23:18:51 +0800 Subject: [PATCH 169/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0516_longest_palindromic_subsequence/Makefile | 2 + 0516_longest_palindromic_subsequence/lps.c | 43 +++++++++++++++++++ 0516_longest_palindromic_subsequence/lps.cc | 25 +++++++++++ 3 files changed, 70 insertions(+) create mode 100644 0516_longest_palindromic_subsequence/Makefile create mode 100644 0516_longest_palindromic_subsequence/lps.c create mode 100644 0516_longest_palindromic_subsequence/lps.cc diff --git a/0516_longest_palindromic_subsequence/Makefile b/0516_longest_palindromic_subsequence/Makefile new file mode 100644 index 0000000..f5e6e53 --- /dev/null +++ b/0516_longest_palindromic_subsequence/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test lps.c diff --git a/0516_longest_palindromic_subsequence/lps.c b/0516_longest_palindromic_subsequence/lps.c new file mode 100644 index 0000000..1ffb767 --- /dev/null +++ b/0516_longest_palindromic_subsequence/lps.c @@ -0,0 +1,43 @@ +#include +#include + + +static inline int max(int a, int b) +{ + return a > b ? a : b; +} + +int longestPalindromeSubseq(char * s) +{ + int i, j, k; + int len = strlen(s); + int **dp = malloc(len * sizeof(int *)); + for (i = 0; i < len; i++) { + dp[i] = malloc(len * sizeof(int)); + memset(dp[i], 0, len * sizeof(int)); + dp[i][i] = 1; + } + + for (k = 1; k < len; k++) { + for (i = 0; i < len - k; i++) { + j = i + k; + if (s[i] == s[j]) { + dp[i][j] = dp[i + 1][j - 1] + 2; + } else { + dp[i][j] = max(dp[i][j - 1], dp[i + 1][j]); + } + } + } + return dp[0][len - 1]; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test s\n"); + exit(-1); + } + + printf("%d\n", longestPalindromeSubseq(argv[1])); + return 0; +} diff --git a/0516_longest_palindromic_subsequence/lps.cc b/0516_longest_palindromic_subsequence/lps.cc new file mode 100644 index 0000000..240fec0 --- /dev/null +++ b/0516_longest_palindromic_subsequence/lps.cc @@ -0,0 +1,25 @@ +#include + +using namespace std; + +class Solution { +public: + int longestPalindromeSubseq(string s) { + int len = s.length(); + vector dp(len, 1); + // We have to use level traverse to reduce the dp table size + for (int i = len - 2; i >= 0; i--) { + int left_down = 0; + for (int j = i + 1; j < len; j++) { + int down = dp[j]; + if (s[i] == s[j]) { + dp[j] = left_down + 2; + } else { + dp[j] = max(down, dp[j - 1]); + } + left_down = down; + } + } + return dp[len - 1]; + } +}; From ecaf278cbd4a1e74d6a23aa133c97d7a3337c298 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 18 Feb 2021 08:36:13 +0800 Subject: [PATCH 170/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0516_longest_palindromic_subsequence/lps.c | 1 + .../Makefile | 2 + .../insertion.c | 39 +++++++++++++++++++ .../insertion.cc | 24 ++++++++++++ 4 files changed, 66 insertions(+) create mode 100644 1312_minimum_insertion_steps_to_make_a_string_palindrome/Makefile create mode 100644 1312_minimum_insertion_steps_to_make_a_string_palindrome/insertion.c create mode 100644 1312_minimum_insertion_steps_to_make_a_string_palindrome/insertion.cc diff --git a/0516_longest_palindromic_subsequence/lps.c b/0516_longest_palindromic_subsequence/lps.c index 1ffb767..b8518b9 100644 --- a/0516_longest_palindromic_subsequence/lps.c +++ b/0516_longest_palindromic_subsequence/lps.c @@ -1,5 +1,6 @@ #include #include +#include static inline int max(int a, int b) diff --git a/1312_minimum_insertion_steps_to_make_a_string_palindrome/Makefile b/1312_minimum_insertion_steps_to_make_a_string_palindrome/Makefile new file mode 100644 index 0000000..2800b4e --- /dev/null +++ b/1312_minimum_insertion_steps_to_make_a_string_palindrome/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O1 -o test insertion.c diff --git a/1312_minimum_insertion_steps_to_make_a_string_palindrome/insertion.c b/1312_minimum_insertion_steps_to_make_a_string_palindrome/insertion.c new file mode 100644 index 0000000..f1d1ef3 --- /dev/null +++ b/1312_minimum_insertion_steps_to_make_a_string_palindrome/insertion.c @@ -0,0 +1,39 @@ +#include +#include +#include + + +static inline int min(int a, int b) +{ + return a < b ? a : b; +} + +int minInsertions(char * s){ + int i, j, len = strlen(s); + int *dp = malloc(len * sizeof(int)); + memset(dp, 0, len * sizeof(int)); + for (i = len - 2; i >= 0; i--) { + int left_down = 0; + for (j = i + 1; j < len; j++) { + int down = dp[j]; + if (s[i] == s[j]) { + dp[j] = left_down; + } else { + dp[j] = min(down, dp[j - 1]) + 1; + } + left_down = down; + } + } + return dp[len - 1]; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "Usage: ./test s\n"); + exit(-1); + } + + printf("%d\n", minInsertions(argv[1])); + return 0; +} diff --git a/1312_minimum_insertion_steps_to_make_a_string_palindrome/insertion.cc b/1312_minimum_insertion_steps_to_make_a_string_palindrome/insertion.cc new file mode 100644 index 0000000..bcd41ae --- /dev/null +++ b/1312_minimum_insertion_steps_to_make_a_string_palindrome/insertion.cc @@ -0,0 +1,24 @@ +#include + +using namespace std; + +class Solution { +public: + int minInsertions(string s) { + int len = s.length(); + vector dp(len); + for (int i = len - 2; i >= 0; i--) { + int left_down = 0; + for (int j = i + 1; j < len; j++) { + int down = dp[j]; + if (s[i] == s[j]) { + dp[j] = left_down; + } else { + dp[j] = min(down, dp[j - 1]) + 1; + } + left_down = down; + } + } + return dp[len - 1]; + } +}; From 45df20c4248cbadeb3f682d1ef48c1c8fdcbb64d Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Fri, 19 Feb 2021 23:50:03 +0800 Subject: [PATCH 171/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0001_two_sum/two_sum.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/0001_two_sum/two_sum.c b/0001_two_sum/two_sum.c index e91c9ff..6a701ea 100644 --- a/0001_two_sum/two_sum.c +++ b/0001_two_sum/two_sum.c @@ -1,6 +1,7 @@ #include #include + struct object { int val; int index; @@ -11,7 +12,7 @@ static int compare(const void *a, const void *b) return ((struct object *) a)->val - ((struct object *) b)->val; } -static int * twosum(int *nums, int numsSize, int target, int *returnSize) +int * twosum(int *nums, int numsSize, int target, int *returnSize) { int i, j; struct object *objs = malloc(numsSize * sizeof(*objs)); From 6054382eac8fa944dbc8221299b6824e442a5e3c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sat, 20 Feb 2021 19:34:53 +0800 Subject: [PATCH 172/211] Add C++ implementation Signed-off-by: begeekmyfriend --- 0002_add_two_numbers/add_two_numbers.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/0002_add_two_numbers/add_two_numbers.c b/0002_add_two_numbers/add_two_numbers.c index acc3ebb..2dd91d5 100644 --- a/0002_add_two_numbers/add_two_numbers.c +++ b/0002_add_two_numbers/add_two_numbers.c @@ -2,13 +2,14 @@ #include #include + /* Definition for singly-linked list. */ struct ListNode { int val; struct ListNode *next; }; -static struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) +struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { int carry = 0; struct ListNode dummy; From b03b9695f8c5325e1ace9a255077ee6f645dcc90 Mon Sep 17 00:00:00 2001 From: Razak Date: Wed, 18 Aug 2021 13:41:53 +0530 Subject: [PATCH 173/211] Adding C++ Implementation --- 0207_course_schedule/course_schedule.cc | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 0207_course_schedule/course_schedule.cc diff --git a/0207_course_schedule/course_schedule.cc b/0207_course_schedule/course_schedule.cc new file mode 100644 index 0000000..1b1ef6f --- /dev/null +++ b/0207_course_schedule/course_schedule.cc @@ -0,0 +1,37 @@ +#include + +using namespace std; + +class Solution { +public: + bool isCycle(int course, vector>& adj, vector& visited) { + if(visited[course] == 2) return true ; + if(visited[course] == 1) return false ; + visited[course] = 2 ; + for(auto connectedCourse : adj[course]) { + if(isCycle(connectedCourse, adj, visited)) { + return true ; + } + } + visited[course] = 1 ; + return false ; + } + + bool canFinish(int numCourses, vector>& prerequisites) { + vector> adj(numCourses) ; + for(auto courses : prerequisites) { + auto course1 = courses[0] ; + auto course2 = courses[1] ; + adj[course2].push_back(course1) ; + } + vector visited(numCourses, 0) ; + for(int course = 0 ; course < numCourses ; course++) { + if(!visited[course]) { + if(isCycle(course, adj, visited)) { + return false; + } + } + } + return true ; + } +}; \ No newline at end of file From a774c5f106d0caddeacd82a6f3d788889001a4bb Mon Sep 17 00:00:00 2001 From: Mohammed Abdul Razak Wahab <60781022+mdrazak2001@users.noreply.github.com> Date: Wed, 18 Aug 2021 19:38:56 +0530 Subject: [PATCH 174/211] update readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bc89fa0..fca7707 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -# leetcode -Let's fuck it up +# LEETCODE SOLUTIONS +Easy and Understandable C/C++ Solutions of Some Leetcode Questions. From 8754b3f3f0540e2313e1027422997c3b2389634a Mon Sep 17 00:00:00 2001 From: Mohammed Abdul Razak Wahab <60781022+mdrazak2001@users.noreply.github.com> Date: Wed, 18 Aug 2021 19:40:13 +0530 Subject: [PATCH 175/211] update readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bc89fa0..fca7707 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -# leetcode -Let's fuck it up +# LEETCODE SOLUTIONS +Easy and Understandable C/C++ Solutions of Some Leetcode Questions. From ad82b978a0a884470e15c05fb7e17e8b14e75c29 Mon Sep 17 00:00:00 2001 From: Razak Date: Mon, 23 Aug 2021 12:09:20 +0530 Subject: [PATCH 176/211] Adding cpp implementation for 17 --- .../letter_combinations.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 0017_letter_combinations_of_a_phone_number/letter_combinations.cpp diff --git a/0017_letter_combinations_of_a_phone_number/letter_combinations.cpp b/0017_letter_combinations_of_a_phone_number/letter_combinations.cpp new file mode 100644 index 0000000..2d375c4 --- /dev/null +++ b/0017_letter_combinations_of_a_phone_number/letter_combinations.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +class Solution +{ +public: + vector m = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + vector ans; + vector letterCombinations(string digits) + { + solve(0, "", digits); + return ans; + } + void solve(int i, string path, string digits) + { + if (i >= digits.size()) + { + if (path.size() > 0) + ans.push_back(path); + return; + } + for (auto c : m[digits[i] - '0']) + { + path += c; + solve(i + 1, path, digits); + path.pop_back(); + } + } +}; + +int main() +{ + cout << "Enter A string : "; + string s; + cin >> s; + Solution sol; + // vector ans = sol.letterCombinations(s) ; + for (auto str : sol.letterCombinations(s)) + { + cout << str << " "; + } + return 0; +} \ No newline at end of file From 536455b2aa26521bec01e8c8a3169e59cf9a6978 Mon Sep 17 00:00:00 2001 From: Pratik Goyal Date: Wed, 25 Aug 2021 09:54:07 +0530 Subject: [PATCH 177/211] Implemented the O(logN) algorithm for LIS --- 0300_longest_increasing_subsequence/lis.cc | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/0300_longest_increasing_subsequence/lis.cc b/0300_longest_increasing_subsequence/lis.cc index 6dd9198..98e81ac 100644 --- a/0300_longest_increasing_subsequence/lis.cc +++ b/0300_longest_increasing_subsequence/lis.cc @@ -5,22 +5,14 @@ using namespace std; class Solution { public: int lengthOfLIS(vector& nums) { - vector dp(nums.size(), 1); - for (int i = 0; i < nums.size(); i++) { - for (int j = 0; j < i; j++) { - // nums[i] should be contained as the last element in subsequence. - if (nums[j] < nums[i] && dp[j] + 1 > dp[i]) { - dp[i] = dp[j] + 1; - } + vector ans; + for (int x : nums) { + auto it = lower_bound(ans.begin(), ans.end(), x); + if (it == ans.end()) { + ans.push_back(x); } + else *it = x; } - - int res = 0; - for (int i : dp) { - if (i > res) { - res = i; - } - } - return res; + return ans.size(); } }; From 397ed3c0b630fec3b3acf89d1fc72750e7d3e20b Mon Sep 17 00:00:00 2001 From: Razak Date: Thu, 26 Aug 2021 15:10:19 +0530 Subject: [PATCH 178/211] 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 179/211] 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 16934aa0253ccb3a9469ebaf0235ce748951a599 Mon Sep 17 00:00:00 2001 From: Zuchen Liu Date: Fri, 27 Aug 2021 18:29:37 +0800 Subject: [PATCH 180/211] case fix for 0028 and 0066 --- 0028_implement_strstr/strstr.c | 4 ++++ 0066_plus_one/plus_one.c | 12 +++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/0028_implement_strstr/strstr.c b/0028_implement_strstr/strstr.c index 24a8c32..f8204ba 100644 --- a/0028_implement_strstr/strstr.c +++ b/0028_implement_strstr/strstr.c @@ -78,6 +78,10 @@ static int strStr(char *haystack, char *needle) unsigned int hlen = strlen(haystack); unsigned int nlen = strlen(needle); + // when haystack is shorter than needle, should return -1 + if(hlen < nlen) + return -1; + /* Brute force */ /* Corner condition: imagine nlen = 1 and it equals i < hlen */ for (i = 0; i < hlen - nlen + 1; i++) { diff --git a/0066_plus_one/plus_one.c b/0066_plus_one/plus_one.c index 4f6005c..a613f37 100644 --- a/0066_plus_one/plus_one.c +++ b/0066_plus_one/plus_one.c @@ -11,9 +11,15 @@ static int* plusOne(int* digits, int digitsSize, int* returnSize) int i, j, len = 0, carry = 1; int *result = malloc((digitsSize + 1) * sizeof(int)); for (i = digitsSize - 1; i >= 0 || carry; i--) { - int n = digits[i] + carry; - result[len++] = n % 10; - carry = n / 10; + if(i >= 0){ + int n = digits[i] + carry; + result[len++] = n % 10; + carry = n / 10; + } else { + // add case like [9] + result[len++] = 1; + carry = 0; + } } for (i = 0, j = len - 1; i < j; i++, j--) { From 6d87a27915502d0f85fffadc2fa55f69440d31a9 Mon Sep 17 00:00:00 2001 From: Zuchen Liu Date: Wed, 1 Sep 2021 17:46:28 +0800 Subject: [PATCH 181/211] 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 182/211] 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 183/211] 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 184/211] 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 185/211] 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 186/211] 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 187/211] 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 188/211] 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 189/211] 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 190/211] 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 191/211] 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 192/211] 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 193/211] 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 194/211] 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 195/211] 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 196/211] 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 197/211] 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 198/211] 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 199/211] 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 200/211] 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 201/211] 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 202/211] 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 203/211] 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 204/211] 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 205/211] 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 206/211] 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 207/211] 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 208/211] 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 209/211] 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 210/211] 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 211/211] 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);