From 3a01f21dcaf53529b3e7592309c75c72d7934782 Mon Sep 17 00:00:00 2001 From: gyt95 Date: Thu, 15 Dec 2022 11:06:51 +0800 Subject: [PATCH] Add JS for chapter of computational complexity --- .../leetcode_two_sum.js | 36 +++++++++++++++++++ .../space_time_tradeoff.md | 25 +++++++++++-- 2 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 codes/javascript/chapter_computational_complexity/leetcode_two_sum.js diff --git a/codes/javascript/chapter_computational_complexity/leetcode_two_sum.js b/codes/javascript/chapter_computational_complexity/leetcode_two_sum.js new file mode 100644 index 000000000..432e2b2ee --- /dev/null +++ b/codes/javascript/chapter_computational_complexity/leetcode_two_sum.js @@ -0,0 +1,36 @@ +/* + * @Author: gyt95 (gytkwan@gmail.com) + * @Date: 2022-12-15 10:51:54 + * @Last Modified by: gyt95 (gytkwan@gmail.com) + * @Last Modified time: 2022-12-15 10:56:26 + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +function twoSumBruteForce(nums, target) { + let n = nums.length; + // 两层循环,时间复杂度 O(n^2) + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + if (nums[i] + nums[j] === target) { + return [i, j] + } + } + } +} + +function twoSumHashTable(nums, target) { + // 辅助哈希表,空间复杂度 O(n) + let m = {} + // 单层循环,时间复杂度 O(n) + for (let i = 0; i < nums.length; i++) { + if (m[nums[i]] !== undefined) { + return [m[nums[i]], i] + } else { + m[target - nums[i]] = i; + } + } +} \ No newline at end of file diff --git a/docs/chapter_computational_complexity/space_time_tradeoff.md b/docs/chapter_computational_complexity/space_time_tradeoff.md index ca54e907f..8cbb3b5b2 100644 --- a/docs/chapter_computational_complexity/space_time_tradeoff.md +++ b/docs/chapter_computational_complexity/space_time_tradeoff.md @@ -90,7 +90,17 @@ comments: true === "JavaScript" ```js title="leetcode_two_sum.js" - + function twoSumBruteForce(nums, target) { + let n = nums.length; + // 两层循环,时间复杂度 O(n^2) + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + if (nums[i] + nums[j] === target) { + return [i, j] + } + } + } + } ``` === "TypeScript" @@ -193,7 +203,18 @@ comments: true === "JavaScript" ```js title="leetcode_two_sum.js" - + function twoSumHashTable(nums, target) { + // 辅助哈希表,空间复杂度 O(n) + let m = {} + // 单层循环,时间复杂度 O(n) + for (let i = 0; i < nums.length; i++) { + if (m[nums[i]] !== undefined) { + return [m[nums[i]], i] + } else { + m[target - nums[i]] = i; + } + } + } ``` === "TypeScript"