-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.三数之和.ts
More file actions
126 lines (112 loc) · 2.17 KB
/
15.三数之和.ts
File metadata and controls
126 lines (112 loc) · 2.17 KB
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
119
120
121
122
123
124
125
126
/*
* @lc app=leetcode.cn id=15 lang=typescript
*
* [15] 三数之和
*
* https://leetcode.cn/problems/3sum/description/
*
* algorithms
* Medium (36.06%)
* Likes: 5130
* Dislikes: 0
* Total Accepted: 1.1M
* Total Submissions: 3M
* Testcase Example: '[-1,0,1,2,-1,-4]'
*
* 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0
* 且不重复的三元组。
*
* 注意:答案中不可以包含重复的三元组。
*
*
*
* 示例 1:
*
*
* 输入:nums = [-1,0,1,2,-1,-4]
* 输出:[[-1,-1,2],[-1,0,1]]
*
*
* 示例 2:
*
*
* 输入:nums = []
* 输出:[]
*
*
* 示例 3:
*
*
* 输入:nums = [0]
* 输出:[]
*
*
*
*
* 提示:
*
*
* 0
* -10^5
*
*
*/
export
// @lc code=start
function threeSum(nums: number[]): number[][] {
quickSort(nums, (a, b) => a - b)
const result: Array<[number, number, number]> = []
for (let a = 0; a < nums.length - 2; a++) {
if (a > 0 && nums[a] === nums[a - 1]) {
continue
}
let c = nums.length - 1
for (let b = a + 1; b < nums.length - 1; b++) {
if (b > a + 1 && nums[b] === nums[b - 1]) {
continue
}
while (b < c && nums[a] + nums[b] + nums[c] > 0) {
c--
}
if (b >= c) break
if (nums[a] + nums[b] + nums[c] === 0) {
result.push([nums[a], nums[b], nums[c]])
}
}
}
return result
}
function quickSort<T>(
arr: T[],
compare: (a: T, b: T) => number,
begin = 0,
end = arr.length - 1,
) {
if (begin >= end) return
const i = partition(arr, compare, begin, end)
quickSort(arr, compare, begin, i - 1)
quickSort(arr, compare, i + 1, end)
}
function partition<T>(
arr: T[],
compare: (a: T, b: T) => number,
begin: number,
end : number,
): number {
// todo: rand
const pivotValue = arr[begin]
let j = begin
for (let i = begin + 1; i <= end; i++) {
if (compare(arr[i], pivotValue) <= 0) {
swap(arr, i, ++j)
}
}
swap(arr, begin, j)
return j
}
function swap(arr: any[], i: number, j: number) {
const temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
// @lc code=end