forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchoidabom.ts
More file actions
36 lines (29 loc) · 689 Bytes
/
choidabom.ts
File metadata and controls
36 lines (29 loc) · 689 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// https://leetcode.com/problems/two-sum/
// TC: O(n^2)
// SC: O(1)
function twoSum(nums: number[], target: number): number[] {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return [];
}
// TC: O(n)
// SC: O(n)
function twoSum(nums: number[], target: number): number[] {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
const diff = target - num;
if (map.has(diff)) {
return [i, map.get(diff)];
} else {
map.set(num, i);
}
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9));