mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-24 20:52:16 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -6,10 +6,10 @@
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Method 1: Brute force enumeration */
|
||||
/* Method 1: brute-force enumeration */
|
||||
vector<int> twoSumBruteForce(vector<int> &nums, int target) {
|
||||
int size = nums.size();
|
||||
// Two nested loops, time complexity is O(n^2)
|
||||
// Two nested loops give a time complexity of O(n^2)
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
for (int j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target)
|
||||
@@ -19,12 +19,12 @@ vector<int> twoSumBruteForce(vector<int> &nums, int target) {
|
||||
return {};
|
||||
}
|
||||
|
||||
/* Method 2: Auxiliary hash table */
|
||||
/* Method 2: auxiliary hash table */
|
||||
vector<int> twoSumHashTable(vector<int> &nums, int target) {
|
||||
int size = nums.size();
|
||||
// Auxiliary hash table, space complexity is O(n)
|
||||
// The auxiliary hash table uses O(n) space
|
||||
unordered_map<int, int> dic;
|
||||
// Single loop, time complexity is O(n)
|
||||
// A single loop gives a time complexity of O(n)
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (dic.find(target - nums[i]) != dic.end()) {
|
||||
return {dic[target - nums[i]], i};
|
||||
@@ -34,20 +34,20 @@ vector<int> twoSumHashTable(vector<int> &nums, int target) {
|
||||
return {};
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// ======= Test Case =======
|
||||
// ======= Test case =======
|
||||
vector<int> nums = {2, 7, 11, 15};
|
||||
int target = 13;
|
||||
|
||||
// ====== Driver Code ======
|
||||
// ====== Driver code ======
|
||||
// Method 1
|
||||
vector<int> res = twoSumBruteForce(nums, target);
|
||||
cout << "Method 1 res = ";
|
||||
cout << "Method 1: res = ";
|
||||
printVector(res);
|
||||
// Method 2
|
||||
res = twoSumHashTable(nums, target);
|
||||
cout << "Method 2 res = ";
|
||||
cout << "Method 2: res = ";
|
||||
printVector(res);
|
||||
|
||||
return 0;
|
||||
|
||||
Reference in New Issue
Block a user