Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JS for chapter of computational complexity #116

Merged
merged 10 commits into from Dec 16, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1,36 @@
/*
* @Author: gyt95 (gytkwan@gmail.com)
* @Date: 2022-12-15 10:51:54
* @Last Modified by: gyt95 (gytkwan@gmail.com)
gyt95 marked this conversation as resolved.
Show resolved Hide resolved
* @Last Modified time: 2022-12-15 10:56:26
*/

/**
* @param {number[]} nums
gyt95 marked this conversation as resolved.
Show resolved Hide resolved
* @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]
}
}
gyt95 marked this conversation as resolved.
Show resolved Hide resolved
}
}

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;
}
gyt95 marked this conversation as resolved.
Show resolved Hide resolved
}
}
25 changes: 23 additions & 2 deletions docs/chapter_computational_complexity/space_time_tradeoff.md
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down