-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
118 lines (114 loc) · 2.61 KB
/
index.ts
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
* # 1. Two Sum
*
* 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
*
* ```bash
* Given nums = [2, 7, 11, 15], target = 9,
*
* Because nums[0] + nums[1] = 2 + 7 = 9,
* return [0, 1].
* ```
*/
export type Solution = (nums: number[], target: number) => number[];
/**
* 嵌套循环遍历
* 这事最偷懒的办法,快速实现后,再考虑优化方案
* 使用Array.forEach在性能上会有点损耗(测试用例:61ms到59ms)
* @date 2018.9.13
* @time
* @space
* @runtime
* @memory
* @runtime_cn 120 ms, faster then 40.065%
* @memory_cn N/A
*/
export const twoSum = (nums: number[], target: number): number[] => {
let result: number[] = [];
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
result = [i, j];
break;
}
}
}
return result;
};
/**
* 哈希存储
* @date 2018.9.13
* @time
* @space
* @runtime
* @memory
* @runtime_cn 80 ms, faster then 59.00%
* @memory_cn N/A
*/
export const twoSum1 = (nums: number[], target: number): number[] => {
const map: { [k: number]: number } = {};
nums.forEach((i, k) => (map[i] = k));
let result: number[] = [];
for (let i = 0; i < nums.length; i++) {
const x = target - nums[i];
if (x in map && map[x] != i) {
result = [i, map[x]];
break;
}
}
return result;
};
/**
* 哈希存储
* @date 2018.9.13
* @time
* @space
* @runtime
* @memory
* @runtime_cn 56 ms, faster then 100.00%
* @memory_cn N/A
*/
export const twoSum2 = (nums: number[], target: number): number[] => {
const map: { [k: number]: number } = {};
const length: number = nums.length;
let result: number[] = [];
for (let i = 0; i < length; i++) {
map[nums[i]] = i;
}
for (let i = 0; i < length; i++) {
const x = target - nums[i];
if (x in map && map[x] != i) {
result = [i, map[x]];
break;
}
}
return result;
};
/**
* 哈希遍历
* @date 2018.9.13
* @time
* @space
* @runtime
* @memory
* @runtime_cn 52 ms, faster then 100%
* @memory_cn N/A
*/
export const twoSum3 = (nums: number[], target: number): number[] => {
const map: { [k: number]: number } = {};
const length = nums.length;
let result: number[] = [];
for (let i = 0; i < length; i++) {
const x: number = target - nums[i];
if (x in map && map[x] != i) {
result = [map[x], i];
break;
}
map[nums[i]] = i;
}
return result;
};