@@ -60,148 +60,15 @@ tags:
60
60
61
61
<!-- solution:start -->
62
62
63
- ### 方法一:动态规划
63
+ ### 方法一:排序 + 贪心
64
64
65
- 先将 pairs 按照第一个数字升序排列,然后转换为最长上升子序列问题 。
65
+ 我们将所有数对按照第二个数的升序排序,用一个变量 $\textit{pre}$ 维护已经选择的数对的第二个数的最大值 。
66
66
67
- 朴素做法,时间复杂度 $O(n^2)$ 。
67
+ 遍历排序后的数对,如果当前数对的第一个数大于 $\textit{pre}$,那么我们可以贪心地选择当前数对,答案加一,并将 $\textit{pre}$ 更新为当前数对的第二个数 。
68
68
69
- <!-- tabs:start -->
70
-
71
- #### Python3
72
-
73
- ``` python
74
- class Solution :
75
- def findLongestChain (self , pairs : List[List[int ]]) -> int :
76
- pairs.sort()
77
- dp = [1 ] * len (pairs)
78
- for i, (c, _) in enumerate (pairs):
79
- for j, (_, b) in enumerate (pairs[:i]):
80
- if b < c:
81
- dp[i] = max (dp[i], dp[j] + 1 )
82
- return max (dp)
83
- ```
84
-
85
- #### Java
86
-
87
- ``` java
88
- class Solution {
89
- public int findLongestChain (int [][] pairs ) {
90
- Arrays . sort(pairs, Comparator . comparingInt(a - > a[0 ]));
91
- int n = pairs. length;
92
- int [] dp = new int [n];
93
- int ans = 0 ;
94
- for (int i = 0 ; i < n; ++ i) {
95
- dp[i] = 1 ;
96
- int c = pairs[i][0 ];
97
- for (int j = 0 ; j < i; ++ j) {
98
- int b = pairs[j][1 ];
99
- if (b < c) {
100
- dp[i] = Math . max(dp[i], dp[j] + 1 );
101
- }
102
- }
103
- ans = Math . max(ans, dp[i]);
104
- }
105
- return ans;
106
- }
107
- }
108
- ```
109
-
110
- #### C++
111
-
112
- ``` cpp
113
- class Solution {
114
- public:
115
- int findLongestChain(vector<vector<int >>& pairs) {
116
- sort(pairs.begin(), pairs.end());
117
- int n = pairs.size();
118
- vector<int > dp(n, 1);
119
- for (int i = 0; i < n; ++i) {
120
- int c = pairs[ i] [ 0 ] ;
121
- for (int j = 0; j < i; ++j) {
122
- int b = pairs[ j] [ 1 ] ;
123
- if (b < c) dp[ i] = max(dp[ i] , dp[ j] + 1);
124
- }
125
- }
126
- return * max_element(dp.begin(), dp.end());
127
- }
128
- };
129
- ```
130
-
131
- #### Go
132
-
133
- ```go
134
- func findLongestChain(pairs [][]int) int {
135
- sort.Slice(pairs, func(i, j int) bool {
136
- return pairs[i][0] < pairs[j][0]
137
- })
138
- n := len(pairs)
139
- dp := make([]int, n)
140
- ans := 0
141
- for i := range pairs {
142
- dp[i] = 1
143
- c := pairs[i][0]
144
- for j := range pairs[:i] {
145
- b := pairs[j][1]
146
- if b < c {
147
- dp[i] = max(dp[i], dp[j]+1)
148
- }
149
- }
150
- ans = max(ans, dp[i])
151
- }
152
- return ans
153
- }
154
- ```
155
-
156
- #### TypeScript
157
-
158
- ``` ts
159
- function findLongestChain(pairs : number [][]): number {
160
- pairs .sort ((a , b ) => a [0 ] - b [0 ]);
161
- const n = pairs .length ;
162
- const dp = new Array (n ).fill (1 );
163
- for (let i = 0 ; i < n ; i ++ ) {
164
- for (let j = 0 ; j < i ; j ++ ) {
165
- if (pairs [i ][0 ] > pairs [j ][1 ]) {
166
- dp [i ] = Math .max (dp [i ], dp [j ] + 1 );
167
- }
168
- }
169
- }
170
- return dp [n - 1 ];
171
- }
172
- ```
173
-
174
- #### Rust
175
-
176
- ``` rust
177
- impl Solution {
178
- pub fn find_longest_chain (mut pairs : Vec <Vec <i32 >>) -> i32 {
179
- pairs . sort_by (| a , b | a [0 ]. cmp (& b [0 ]));
180
- let n = pairs . len ();
181
- let mut dp = vec! [1 ; n ];
182
- for i in 0 .. n {
183
- for j in 0 .. i {
184
- if pairs [i ][0 ] > pairs [j ][1 ] {
185
- dp [i ] = dp [i ]. max (dp [j ] + 1 );
186
- }
187
- }
188
- }
189
- dp [n - 1 ]
190
- }
191
- }
192
- ```
193
-
194
- <!-- tabs: end -->
195
-
196
- <!-- solution: end -->
197
-
198
- <!-- solution: start -->
199
-
200
- ### 方法二:贪心
201
-
202
- 在所有可作为下一个数对的集合中,选择第二个数最小的数对添加到数对链。因此可以按照第二个数升序排列的顺序遍历所有数对,如果当前数能加入链,则加入。
69
+ 遍历结束后,返回答案即可。
203
70
204
- 时间复杂度 $O(n\ log n)$。
71
+ 时间复杂度 $O(n \times \ log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数对的数量 。
205
72
206
73
<!-- tabs:start -->
207
74
@@ -210,11 +77,12 @@ impl Solution {
210
77
``` python
211
78
class Solution :
212
79
def findLongestChain (self , pairs : List[List[int ]]) -> int :
213
- ans, cur = 0 , - inf
214
- for a, b in sorted (pairs, key = lambda x : x[ 1 ]):
215
- if cur < a :
216
- cur = b
80
+ pairs.sort( key = lambda x : x[ 1 ])
81
+ ans, pre = 0 , - inf
82
+ for a, b in pairs :
83
+ if pre < a:
217
84
ans += 1
85
+ pre = b
218
86
return ans
219
87
```
220
88
@@ -223,13 +91,12 @@ class Solution:
223
91
``` java
224
92
class Solution {
225
93
public int findLongestChain (int [][] pairs ) {
226
- Arrays . sort(pairs, Comparator . comparingInt(a - > a[1 ]));
227
- int ans = 0 ;
228
- int cur = Integer . MIN_VALUE ;
229
- for (int [] p : pairs) {
230
- if (cur < p[0 ]) {
231
- cur = p[1 ];
94
+ Arrays . sort(pairs, (a, b) - > Integer . compare(a[1 ], b[1 ]));
95
+ int ans = 0 , pre = Integer . MIN_VALUE ;
96
+ for (var p : pairs) {
97
+ if (pre < p[0 ]) {
232
98
++ ans;
99
+ pre = p[1 ];
233
100
}
234
101
}
235
102
return ans;
@@ -243,13 +110,11 @@ class Solution {
243
110
class Solution {
244
111
public:
245
112
int findLongestChain(vector<vector<int >>& pairs) {
246
- sort(pairs.begin(), pairs.end(), [ ] (vector<int >& a, vector<int > b) {
247
- return a[ 1] < b[ 1] ;
248
- });
249
- int ans = 0, cur = INT_MIN;
250
- for (auto& p : pairs) {
251
- if (cur < p[ 0] ) {
252
- cur = p[ 1] ;
113
+ ranges::sort(pairs, {}, [ ] (const auto& p) { return p[ 1] ; });
114
+ int ans = 0, pre = INT_MIN;
115
+ for (const auto& p : pairs) {
116
+ if (pre < p[ 0] ) {
117
+ pre = p[ 1] ;
253
118
++ans;
254
119
}
255
120
}
@@ -261,18 +126,16 @@ public:
261
126
#### Go
262
127
263
128
```go
264
- func findLongestChain(pairs [][]int) int {
265
- sort.Slice(pairs, func(i, j int) bool {
266
- return pairs[i][1] < pairs[j][1]
267
- })
268
- ans, cur := 0, math.MinInt32
129
+ func findLongestChain(pairs [][]int) (ans int) {
130
+ sort.Slice(pairs, func(i, j int) bool { return pairs[i][1] < pairs[j][1] })
131
+ pre := math.MinInt
269
132
for _, p := range pairs {
270
- if cur < p[0] {
271
- cur = p[1]
133
+ if pre < p[0] {
272
134
ans++
135
+ pre = p[1]
273
136
}
274
137
}
275
- return ans
138
+ return
276
139
}
277
140
```
278
141
@@ -281,15 +144,14 @@ func findLongestChain(pairs [][]int) int {
281
144
``` ts
282
145
function findLongestChain(pairs : number [][]): number {
283
146
pairs .sort ((a , b ) => a [1 ] - b [1 ]);
284
- let res = 0 ;
285
- let pre = - Infinity ;
147
+ let [ans, pre] = [0 , - Infinity ];
286
148
for (const [a, b] of pairs ) {
287
149
if (pre < a ) {
150
+ ++ ans ;
288
151
pre = b ;
289
- res ++ ;
290
152
}
291
153
}
292
- return res ;
154
+ return ans ;
293
155
}
294
156
```
295
157
@@ -298,18 +160,17 @@ function findLongestChain(pairs: number[][]): number {
298
160
``` rust
299
161
impl Solution {
300
162
pub fn find_longest_chain (mut pairs : Vec <Vec <i32 >>) -> i32 {
301
- pairs . sort_by ( | a , b | a [1 ]. cmp ( & b [ 1 ]) );
302
- let mut res = 0 ;
163
+ pairs . sort_by_key ( | pair | pair [1 ]);
164
+ let mut ans = 0 ;
303
165
let mut pre = i32 :: MIN ;
304
- for pair in pairs . iter () {
305
- let a = pair [0 ];
306
- let b = pair [1 ];
166
+ for pair in pairs {
167
+ let (a , b ) = (pair [0 ], pair [1 ]);
307
168
if pre < a {
169
+ ans += 1 ;
308
170
pre = b ;
309
- res += 1 ;
310
171
}
311
172
}
312
- res
173
+ ans
313
174
}
314
175
}
315
176
```
0 commit comments