From 3377886e4111c14478d90dc4e444b36ab5881fc7 Mon Sep 17 00:00:00 2001 From: URpineapple Date: Fri, 8 May 2020 20:47:50 -0400 Subject: [PATCH 01/12] Added 1.TwoSum.en.md --- problems/1.TwoSum.en.md | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 problems/1.TwoSum.en.md diff --git a/problems/1.TwoSum.en.md b/problems/1.TwoSum.en.md new file mode 100644 index 000000000..ec7b84aac --- /dev/null +++ b/problems/1.TwoSum.en.md @@ -0,0 +1,51 @@ +## Problem +https://leetcode-cn.com/problems/two-sum + +## Problem Description +``` +Given an array of integers, return indices of the two numbers such that they add up to a specific target. + +You may assume that each input would have exactly one solution, and you may not use the same element twice. + +Example: + +Given nums = [2, 7, 11, 15], target = 9, + +Because nums[0] + nums[1] = 2 + 7 = 9, +return [0, 1]. +``` + +## Solution +The easiest solution to come up with is Brute Force. We could write two for-loops to traverse every element, and find the target numbers that meet the requirement. However, the time complexity of this method is O(N^2), while the space complexity is O(1). Clearly, we need to find a way to optimize this solution since the time complexity is too high. What we could do is to record the numbers we have traversed and the relevant index with a Map. Whenever we meet a new number during traversal, we go back to the Map and check has the difference value between this number and the target number appeared before. If it did, the problem has been solved and there's no need to continue the execution. + +## Key Points + - Find the difference instead of the sum + - Connect every number with its index through the help of Map + - More space, less time. Reduce the time complexity from O(N) to O(1) + + ## Code + - Support Language: JS + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +const twoSum = function (nums, target) { + const map = new Map(); + for (let i = 0; i < nums.length; i++) { + const diff = target - nums[i]; + if (map.has(diff)) { + return [map.get(diff), i]; + } + map.set(nums[i], i); + } +} +``` + +***Complexity Anlysis*** + +- *Time Complexity*: O(N) +- *Space Complexity*๏ผšO(N) + From ec024fa0186443f62deae818de795f56be3c88c5 Mon Sep 17 00:00:00 2001 From: URpineapple <35406893+URpineapple@users.noreply.github.com> Date: Sat, 9 May 2020 17:22:20 -0400 Subject: [PATCH 02/12] Update problems/1.TwoSum.en.md/Solution Co-authored-by: lucifer --- problems/1.TwoSum.en.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/problems/1.TwoSum.en.md b/problems/1.TwoSum.en.md index ec7b84aac..a6262047b 100644 --- a/problems/1.TwoSum.en.md +++ b/problems/1.TwoSum.en.md @@ -16,7 +16,7 @@ return [0, 1]. ``` ## Solution -The easiest solution to come up with is Brute Force. We could write two for-loops to traverse every element, and find the target numbers that meet the requirement. However, the time complexity of this method is O(N^2), while the space complexity is O(1). Clearly, we need to find a way to optimize this solution since the time complexity is too high. What we could do is to record the numbers we have traversed and the relevant index with a Map. Whenever we meet a new number during traversal, we go back to the Map and check has the difference value between this number and the target number appeared before. If it did, the problem has been solved and there's no need to continue the execution. +The easiest solution to come up with is Brute Force. We could write two for-loops to traverse every element, and find the target numbers that meet the requirement. However, the time complexity of this solution is O(N^2), while the space complexity is O(1). Apparently, we need to find a way to optimize this solution since the time complexity is too high. What we could do is to record the numbers we have traversed and the relevant index with a Map. Whenever we meet a new number during traversal, we go back to the Map and check whether the `diff` between this number and the target number appeared before. If it did, the problem has been solved and there's no need to continue. ## Key Points - Find the difference instead of the sum @@ -48,4 +48,3 @@ const twoSum = function (nums, target) { - *Time Complexity*: O(N) - *Space Complexity*๏ผšO(N) - From 9fa90fd519058ac8e0dc8eb068439367cf653f91 Mon Sep 17 00:00:00 2001 From: URpineapple <35406893+URpineapple@users.noreply.github.com> Date: Sat, 9 May 2020 17:23:11 -0400 Subject: [PATCH 03/12] Update problems/1.TwoSum.en.md/keypoint Co-authored-by: lucifer --- problems/1.TwoSum.en.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/1.TwoSum.en.md b/problems/1.TwoSum.en.md index a6262047b..4e80118b6 100644 --- a/problems/1.TwoSum.en.md +++ b/problems/1.TwoSum.en.md @@ -21,7 +21,7 @@ The easiest solution to come up with is Brute Force. We could write two for-loop ## Key Points - Find the difference instead of the sum - Connect every number with its index through the help of Map - - More space, less time. Reduce the time complexity from O(N) to O(1) + - Less time by more space. Reduce the time complexity from O(N) to O(1) ## Code - Support Language: JS From 187055d3f13b4e2be1ba061499f692e2c42bd1a0 Mon Sep 17 00:00:00 2001 From: URpineapple Date: Mon, 11 May 2020 17:21:45 -0400 Subject: [PATCH 04/12] - Added twosum.en.md link in README.en.md - Changed the text in () from 'Not Translated Yet' to 'Transaltion in Progress' - Added check emoji at the end of tranlasted problems' titles --- README.en.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/README.en.md b/README.en.md index a2c07b220..d8649f91d 100644 --- a/README.en.md +++ b/README.en.md @@ -110,13 +110,13 @@ The data structures mainly include: > Here only lists some **representative problems** but not all. -#### Easy ๏ผˆNot Translated Yet๏ผ‰ -- [0001.TwoSum](./problems/1.TwoSum.md)๐Ÿ†• +#### Easy (Translation in Progress) +- [0001.TwoSum](./problems/1.TwoSum.en.md)๐Ÿ†•โœ… - [0020.Valid Parentheses](./problems/20.validParentheses.md) - [0021.MergeTwoSortedLists](./problems/21.MergeTwoSortedLists.md) ๐Ÿ†• - [0026.remove-duplicates-from-sorted-array](./problems/26.remove-duplicates-from-sorted-array.md) -- [0053.maximum-sum-subarray](./problems/53.maximum-sum-subarray-en.md) ๐Ÿ†• +- [0053.maximum-sum-subarray](./problems/53.maximum-sum-subarray-en.md) ๐Ÿ†•โœ… - [0088.merge-sorted-array](./problems/88.merge-sorted-array.md) - [0104.maximum-depth-of-binary-tree](./problems/104.maximum-depth-of-binary-tree.md) - [0121.best-time-to-buy-and-sell-stock](./problems/121.best-time-to-buy-and-sell-stock.md) @@ -145,7 +145,7 @@ The data structures mainly include: - [0501.find-mode-in-binary-search-tree](./problems/501.Find-Mode-in-Binary-Search-Tree.md) ๐Ÿ†• - [0575.distribute-candies](./problems/575.distribute-candies.md) -#### Medium ๏ผˆNot Translated Yet๏ผ‰ +#### Medium (Translation in Progress) - [0002. Add Two Numbers](./problems/2.addTwoNumbers.md) - [0003. Longest Substring Without Repeating Characters](./problems/3.longestSubstringWithoutRepeatingCharacters.md) @@ -171,7 +171,7 @@ The data structures mainly include: - [0073.set-matrix-zeroes](./problems/73.set-matrix-zeroes.md) - [0075.sort-colors](./problems/75.sort-colors.md) - [0078.subsets](./problems/78.subsets.md) -- [0079.word-search](./problems/79.word-search-en.md) +- [0079.word-search](./problems/79.word-search-en.md) โœ… - [0086.partition-list](./problems/86.partition-list.md) - [0090.subsets-ii](./problems/90.subsets-ii.md) - [0091.decode-ways](./problems/91.decode-ways.md) @@ -211,11 +211,11 @@ The data structures mainly include: - [0416.partition-equal-subset-sum](./problems/416.partition-equal-subset-sum.md) - [0445.add-two-numbers-ii](./problems/445.add-two-numbers-ii.md) - [0454.4-sum-ii](./problems/454.4-sum-ii.md) -- [0474.ones-and-zeros](./problems/474.ones-and-zeros-en.md) +- [0474.ones-and-zeros](./problems/474.ones-and-zeros-en.md)โœ… - [0494.target-sum](./problems/494.target-sum.md) - [0516.longest-palindromic-subsequence](./problems/516.longest-palindromic-subsequence.md) - [0518.coin-change-2](./problems/518.coin-change-2.md) -- [0547.friend-circles](./problems/547.friend-circles-en.md) ๐Ÿ†• +- [0547.friend-circles](./problems/547.friend-circles-en.md) ๐Ÿ†•โœ… - [0609.find-duplicate-file-in-system](./problems/609.find-duplicate-file-in-system.md) - [0875.koko-eating-bananas](./problems/875.koko-eating-bananas.md) - [0877.stone-game](./problems/877.stone-game.md) @@ -225,11 +225,12 @@ The data structures mainly include: - [1031.maximum-sum-of-two-non-overlapping-subarrays](./problems/1031.maximum-sum-of-two-non-overlapping-subarrays.md) - [1218.longest-arithmetic-subsequence-of-given-difference.md](./problems/1218.longest-arithmetic-subsequence-of-given-difference.md) ๐Ÿ†• -#### Hard ๏ผˆNot Translated Yet๏ผ‰ + +#### Hard (Translation in Progress) - [0004.median-of-two-sorted-array](./problems/4.median-of-two-sorted-array.md) ๐Ÿ†• - [0023.merge-k-sorted-lists](./problems/23.merge-k-sorted-lists.md) -- [0025.reverse-nodes-in-k-group](./problems/25.reverse-nodes-in-k-groups-en.md) ๐Ÿ†• +- [0025.reverse-nodes-in-k-group](./problems/25.reverse-nodes-in-k-groups-en.md) ๐Ÿ†•โœ… - [0032.longest-valid-parentheses](./problems/32.longest-valid-parentheses.md) ๐Ÿ†• - [0042.trapping-rain-water](./problems/42.trapping-rain-water.md) - [0052.N-Queens-II](./problems/52.N-Queens-II.md) ๐Ÿ†• @@ -240,12 +241,12 @@ The data structures mainly include: - [0295.find-median-from-data-stream](./problems/295.find-median-from-data-stream.md) ๐Ÿ†• - [0301.remove-invalid-parentheses](./problems/301.remove-invalid-parentheses.md) - [0460.lfu-cache](./problems/460.lfu-cache.md) ๐Ÿ†• -- [1168.optimize-water-distribution-in-a-village](./problems/1168.optimize-water-distribution-in-a-village-en.md) ๐Ÿ†• +- [1168.optimize-water-distribution-in-a-village](./problems/1168.optimize-water-distribution-in-a-village-en.md) ๐Ÿ†•โœ… ### Summary of Data Structures and Algorithm - [Data Structure](./thinkings/basic-data-structure-en.md) (Drafts) -- [Basic Algorithm](./thinkings/basic-algorithm-en.md)Drafts +- [Basic Algorithm](./thinkings/basic-algorithm-en.md)(Drafts) - [Binary Tree Traversal](./thinkings/binary-tree-traversal-en.md) - [Dynamic Programming](./thinkings/dynamic-programming-en.md) - [Huffman Encode and Run Length Encode](./thinkings/run-length-encode-and-huffman-encode-en.md) From cf6b9349afeb981d422b6fd63f02e9b5c0b4e250 Mon Sep 17 00:00:00 2001 From: URpineapple Date: Mon, 11 May 2020 17:39:26 -0400 Subject: [PATCH 05/12] Updated the title of preview as well --- README.en.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.en.md b/README.en.md index d8649f91d..f29ad3a74 100644 --- a/README.en.md +++ b/README.en.md @@ -76,13 +76,13 @@ The data structures mainly include: - Tree and Graph: Lowest Common Ancestor (LCA); Disjoint-Set - String: Prefix Tree (Trie); Suffix Tree -## Previews๏ผˆNot Translated Yet๏ผ‰ +## Previews (Translation in Progress) [0042.trapping-rain-water](./problems/42.trapping-rain-water.md): ![0042.trapping-rain-water](./assets/problems/42.trapping-rain-water-1.png) -[0547.friend-circles](./problems/547.friend-circles-en.md): +[0547.friend-circles](./problems/547.friend-circles-en.md) โœ…: ![friend circle BFS](./assets/problems/547.friend-circle-bfs.png) From 46f29b5341967a00706aa78ce4003a088a00bf27 Mon Sep 17 00:00:00 2001 From: lucifer Date: Tue, 12 May 2020 11:29:08 +0800 Subject: [PATCH 06/12] Update README.en.md --- README.en.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.en.md b/README.en.md index f29ad3a74..b2d1e6a63 100644 --- a/README.en.md +++ b/README.en.md @@ -52,6 +52,7 @@ If you want to do some contributions or collaborations, just feel free to contac - For the parts that were added recently, there will be a ๐Ÿ†• behind. - For the parts that were updated recently, there will be a ๐Ÿ–Š behind. +- For the parts that have been translated, there will be a โœ… behind. - Here will be the place to update Anki Flashcards in the future as well. - Here is a mind mapping graph showing the summary of categorizations of problems that are questioned frequently in interviews. We could analyze according to the information in the graph. From a8e437ce0712073cd0ffe3c68e1f9b035d1b051f Mon Sep 17 00:00:00 2001 From: URpineapple Date: Sat, 23 May 2020 23:15:02 -0400 Subject: [PATCH 07/12] Added translation for problem 2 --- README.en.md | 2 +- problems/2.addTwoNumbers.en.md | 174 +++++++++++++++++++++++++++++++++ 2 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 problems/2.addTwoNumbers.en.md diff --git a/README.en.md b/README.en.md index f29ad3a74..c47db2816 100644 --- a/README.en.md +++ b/README.en.md @@ -147,7 +147,7 @@ The data structures mainly include: #### Medium (Translation in Progress) -- [0002. Add Two Numbers](./problems/2.addTwoNumbers.md) +- [0002. Add Two Numbers](./problems/2.addTwoNumbers.en.md) โœ… - [0003. Longest Substring Without Repeating Characters](./problems/3.longestSubstringWithoutRepeatingCharacters.md) - [0005.longest-palindromic-substring](./problems/5.longest-palindromic-substring.md) - [0011.container-with-most-water](./problems/11.container-with-most-water.md) diff --git a/problems/2.addTwoNumbers.en.md b/problems/2.addTwoNumbers.en.md new file mode 100644 index 000000000..b7bf08c5a --- /dev/null +++ b/problems/2.addTwoNumbers.en.md @@ -0,0 +1,174 @@ +## Problem +https://leetcode.com/problems/add-two-numbers/description/ + +## Problem Description +``` +You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +Example + +Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) +Output: 7 -> 0 -> 8 +Explanation: 342 + 465 = 807. + +``` +## Solution + +Define a new variable `carried` that represents the carry value during the calculation, and a new linked list +Traverse the two linked lists from the start to the end simultaneously, and calculate the sum of node value from each linked list. The sum of the result and `carried` would be appended as a new node to the end of new linked list. + +![2.addTwoNumbers](../assets/2.addTwoNumbers.gif) + +(Image Reference: https://github.com/MisterBooo/LeetCodeAnimation) + +## Key Point Analysis + +1. The characteristics and application of this data structure - linked list + +2. Define a variable named `carried` to replace the role of carry-over, calculate `carried` after each sum and apply it to the next round's calculation + +## Code +* Language Support: JS, C++ + +JavaScript: +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + if (l1 === null || l2 === null) return null + + // using dummyHead can simplify linked list's calculation, dummyHead.next points to the new linked list + let dummyHead = new ListNode(0) + let cur1 = l1 + let cur2 = l2 + let cur = dummyHead // cur is for the calculation in new linked list + let carry = 0 // carry-over symbol + + while (cur1 !== null || cur2 !== null) { + let val1 = cur1 !== null ? cur1.val : 0 + let val2 = cur2 !== null ? cur2.val : 0 + let sum = val1 + val2 + carry + let newNode = new ListNode(sum % 10) // the result of sum%10 ranges from 0 to 9, which is the value of the current digit + carry = sum >= 10 ? 1 : 0 // sum>=10, carry=1, so carry-over exists here + cur.next = newNode + cur = cur.next + + if (cur1 !== null) { + cur1 = cur1.next + } + + if (cur2 !== null) { + cur2 = cur2.next + } + } + + if (carry > 0) { + // If there's still carry-over in the end, then add a new node + cur.next = new ListNode(carry) + } + + return dummyHead.next +}; +``` +C++ +> C++ code is slightly different from the JavaScript code above: the step that checks whether carry equals to 0 is put in the while-loop. +```c++ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* ret = nullptr; + ListNode* cur = nullptr; + int carry = 0; + while (l1 != nullptr || l2 != nullptr || carry != 0) { + carry += (l1 == nullptr ? 0 : l1->val) + (l2 == nullptr ? 0 : l2->val); + auto temp = new ListNode(carry % 10); + carry /= 10; + if (ret == nullptr) { + ret = temp; + cur = ret; + } + else { + cur->next = temp; + cur = cur->next; + } + l1 = l1 == nullptr ? nullptr : l1->next; + l2 = l2 == nullptr ? nullptr : l2->next; + } + return ret; + } +}; +``` +## Extension +The singly-linked list also has a recursive structure based on its definition. Therefore, the recursive apporach works on reversing a linked list, as well. +> Because a singly-linked list is a linear data structure, the recursive approach means that the use of stack would also be linear. When the linked list's length reaches a certain level, the recursion would result in a stack overflow. Therefore, using recursion to manipulate a linked list is not recommended in reality. + +### Description + +1. Add up the first node of two linked lists, and covert the result to a number between 0 and 10, record the carry-over as well. +2. Proceed to add up the two linked lists after the first node with carry-over recursively +3. Point the next of the head node from the first step to the linked list returned from the second step + +### C++ Implementation +```C++ +// Normal recursion +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + return addTwoNumbers(l1, l2, 0); + } + +private: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2, int carry) { + if (l1 == nullptr && l2 == nullptr && carry == 0) return nullptr; + carry += (l1 == nullptr ? 0 : l1->val) + (l2 == nullptr ? 0 : l2->val); + auto ret = new ListNode(carry % 10); + ret->next = addTwoNumbers(l1 == nullptr ? l1 : l1->next, + l2 == nullptr ? l2 : l2->next, + carry / 10); + return ret; + } +}; +// (Similiar) Tail recursion +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* head = nullptr; + addTwoNumbers(head, nullptr, l1, l2, 0); + return head; + } + +private: + void addTwoNumbers(ListNode*& head, ListNode* cur, ListNode* l1, ListNode* l2, int carry) { + if (l1 == nullptr && l2 == nullptr && carry == 0) return; + carry += (l1 == nullptr ? 0 : l1->val) + (l2 == nullptr ? 0 : l2->val); + auto temp = new ListNode(carry % 10); + if (cur == nullptr) { + head = temp; + cur = head; + } else { + cur->next = temp; + cur = cur->next; + } + addTwoNumbers(head, cur, l1 == nullptr ? l1 : l1->next, l2 == nullptr ? l2 : l2->next, carry / 10); + } +}; \ No newline at end of file From d55f1b0cf40ba4e39fc55e041885d6d86045f04b Mon Sep 17 00:00:00 2001 From: URpineapple Date: Wed, 27 May 2020 23:28:27 -0400 Subject: [PATCH 08/12] Accepted incoming change --- README.en.md | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/README.en.md b/README.en.md index b41515f76..ee554f418 100644 --- a/README.en.md +++ b/README.en.md @@ -263,16 +263,6 @@ The data structures mainly include: ### Summary of Data Structures and Algorithm -<<<<<<< HEAD -- [Data Structure](./thinkings/basic-data-structure-en.md) (Drafts) -- [Basic Algorithm](./thinkings/basic-algorithm-en.md)(Drafts) -- [Binary Tree Traversal](./thinkings/binary-tree-traversal-en.md) -- [Dynamic Programming](./thinkings/dynamic-programming-en.md) -- [Huffman Encode and Run Length Encode](./thinkings/run-length-encode-and-huffman-encode-en.md) -- [Bloom Filter](./thinkings/bloom-filter-en.md) -- [String Problems](./thinkings/string-problems-en.md) -- [Sliding Window Technique](./thinkings/slide-window.en.md) -======= - [Data Structure](./thinkings/basic-data-structure-en.md)โœ… - [Basic Algorithm](./thinkings/basic-algorithm-en.md)โœ… - [Binary Tree Traversal](./thinkings/binary-tree-traversal.en.md)โœ… @@ -281,7 +271,6 @@ The data structures mainly include: - [Bloom Filter](./thinkings/bloom-filter-en.md)โœ… - [String Problems](./thinkings/string-problems-en.md)โœ… - [Sliding Window Technique](./thinkings/slide-window.en.md)โœ… ->>>>>>> upstream/master ### Anki Flashcards From 86c33c37d86970f6f0b70cc8455f32ce01cba445 Mon Sep 17 00:00:00 2001 From: URpineapple Date: Sun, 7 Jun 2020 22:25:58 -0400 Subject: [PATCH 09/12] Added translation for 454 --- README.en.md | 2 +- problems/454.4-Sum-ii.en.md | 103 ++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 problems/454.4-Sum-ii.en.md diff --git a/README.en.md b/README.en.md index ee554f418..294894e21 100644 --- a/README.en.md +++ b/README.en.md @@ -95,7 +95,7 @@ The data structures mainly include: ![198.house-robber](./assets/problems/198.house-robber.png) -[0454.4-sum-ii](./problems/454.4-sum-ii.md): +[0454.4-sum-ii](./problems/454.4-sum-ii.en.md) โœ…: ![454.4-sum-ii](./assets/problems/454.4-sum-ii.png) diff --git a/problems/454.4-Sum-ii.en.md b/problems/454.4-Sum-ii.en.md new file mode 100644 index 000000000..ac105ef5e --- /dev/null +++ b/problems/454.4-Sum-ii.en.md @@ -0,0 +1,103 @@ + + +## Problem Address +https://leetcode.com/problems/4sum-ii/description/ + +## Problem Description + +``` +Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. + +To make problem a bit easier, all A, B, C, D have same length of N where 0 โ‰ค N โ‰ค 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. + +Example: + +Input: +A = [ 1, 2] +B = [-2,-1] +C = [-1, 2] +D = [ 0, 2] + +Output: +2 + +Explanation: +The two tuples are: +1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 +2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 +``` +## Solution + +The normal solution to complete the search would require four rounds of traversal, and that would make the time complexity reaches O(n^4), which doesn't work obviously. We have to figure out a more effective algorithm. + +My idea is to separate these four lists into two groups and combine them two by two. We then calculate separately `all the sums from these two groups, and the relevant counts` + +As the picture shows: + +![454.4-sum-ii](../assets/problems/454.4-sum-ii.png) + + +Now that we got two `hashTable`, and the result would appear with some basic calculations. + +## Key Point Analysis + +- ็ฉบ้—ดๆขๆ—ถ้—ด +- ไธคไธคๅˆ†็ป„๏ผŒๆฑ‚ๅ‡บไธคไธค็ป“ๅˆ่ƒฝๅคŸๅพ—ๅ‡บ็š„ๅฏ่ƒฝๆ•ฐ๏ผŒ็„ถๅŽๅˆๅนถๅณๅฏใ€‚ +- Less time by more space. +- Divide the lists by 2, and calculate all the possible sums from two groups, then combine the result. + +## Code + +Language Support: `JavaScript`๏ผŒ`Python3` + +`JavaScript`: +```js + +/* + * @lc app=leetcode id=454 lang=javascript + * + * [454] 4Sum II + * + * https://leetcode.com/problems/4sum-ii/description/ +/** + * @param {number[]} A + * @param {number[]} B + * @param {number[]} C + * @param {number[]} D + * @return {number} + */ +var fourSumCount = function(A, B, C, D) { + const sumMapper = {}; + let res = 0; + for (let i = 0; i < A.length; i++) { + for (let j = 0; j < B.length; j++) { + sumMapper[A[i] + B[j]] = (sumMapper[A[i] + B[j]] || 0) + 1; + } + } + + for (let i = 0; i < C.length; i++) { + for (let j = 0; j < D.length; j++) { + res += sumMapper[- (C[i] + D[j])] || 0; + } + } + + return res; +}; +``` + +`Python3`: + +```python +class Solution: + def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: + mapper = {} + res = 0 + for i in A: + for j in B: + mapper[i + j] = mapper.get(i + j, 0) + 1 + + for i in C: + for j in D: + res += mapper.get(-1 * (i + j), 0) + return res + ``` \ No newline at end of file From 9904db2e967fb8a001d43014ecc96990e2079bea Mon Sep 17 00:00:00 2001 From: URpineapple Date: Mon, 8 Jun 2020 20:31:54 -0400 Subject: [PATCH 10/12] added changes --- README.en.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/README.en.md b/README.en.md index ee554f418..bfc19d5df 100644 --- a/README.en.md +++ b/README.en.md @@ -111,10 +111,6 @@ The data structures mainly include: > Here only lists some **representative problems** but not all. -<<<<<<< HEAD - -======= ->>>>>>> upstream/master #### Easy (Translation in Progress) - [0001.TwoSum](./problems/1.TwoSum.en.md)๐Ÿ†•โœ… - [0020.Valid Parentheses](./problems/20.validParentheses.md) From 72d9081e216cb96d45d0dd70ff451879c5085a68 Mon Sep 17 00:00:00 2001 From: URpineapple Date: Mon, 8 Jun 2020 20:34:19 -0400 Subject: [PATCH 11/12] Solved conflicts --- README.en.md | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/README.en.md b/README.en.md index 076e56fc0..af0c4f777 100644 --- a/README.en.md +++ b/README.en.md @@ -170,11 +170,7 @@ The data structures mainly include: - [0062.unique-paths](./problems/62.unique-paths.md) - [0073.set-matrix-zeroes](./problems/73.set-matrix-zeroes.md) - [0075.sort-colors](./problems/75.sort-colors.md) -<<<<<<< HEAD -- [0078.subsets](./problems/78.subsets.md) -======= - [0078.subsets](./problems/78.subsets-en.md)โœ… ->>>>>>> upstream/master - [0079.word-search](./problems/79.word-search-en.md) โœ… - [0086.partition-list](./problems/86.partition-list.md) - [0090.subsets-ii](./problems/90.subsets-ii-en.md)โœ… @@ -220,10 +216,7 @@ The data structures mainly include: - [0516.longest-palindromic-subsequence](./problems/516.longest-palindromic-subsequence.md) - [0518.coin-change-2](./problems/518.coin-change-2.md) - [0547.friend-circles](./problems/547.friend-circles-en.md) ๐Ÿ†•โœ… -<<<<<<< HEAD -======= - [0560.subarray-sum-equals-k](./problems/560.subarray-sum-equals-k.en.md) โœ… ->>>>>>> upstream/master - [0609.find-duplicate-file-in-system](./problems/609.find-duplicate-file-in-system.md) - [0875.koko-eating-bananas](./problems/875.koko-eating-bananas.md) - [0877.stone-game](./problems/877.stone-game.md) @@ -236,10 +229,6 @@ The data structures mainly include: - [1371.find-the-longest-substring-containing-vowels-in-even-counts](./problems/1371.find-the-longest-substring-containing-vowels-in-even-counts.en.md) ๐Ÿ†•โœ… -<<<<<<< HEAD - -======= ->>>>>>> upstream/master #### Hard (Translation in Progress) - [0004.median-of-two-sorted-array](./problems/4.median-of-two-sorted-array.md) ๐Ÿ†• From f209ef5ec7c0b2188551a09aaddf292cc21ef4a8 Mon Sep 17 00:00:00 2001 From: URpineapple Date: Mon, 8 Jun 2020 20:36:38 -0400 Subject: [PATCH 12/12] Modified 454 translation --- problems/454.4-Sum-ii.en.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/problems/454.4-Sum-ii.en.md b/problems/454.4-Sum-ii.en.md index ac105ef5e..5a5d0eb82 100644 --- a/problems/454.4-Sum-ii.en.md +++ b/problems/454.4-Sum-ii.en.md @@ -40,9 +40,6 @@ As the picture shows: Now that we got two `hashTable`, and the result would appear with some basic calculations. ## Key Point Analysis - -- ็ฉบ้—ดๆขๆ—ถ้—ด -- ไธคไธคๅˆ†็ป„๏ผŒๆฑ‚ๅ‡บไธคไธค็ป“ๅˆ่ƒฝๅคŸๅพ—ๅ‡บ็š„ๅฏ่ƒฝๆ•ฐ๏ผŒ็„ถๅŽๅˆๅนถๅณๅฏใ€‚ - Less time by more space. - Divide the lists by 2, and calculate all the possible sums from two groups, then combine the result.