@@ -60,148 +60,15 @@ tags:
6060
6161<!-- solution:start -->
6262
63- ### 方法一:动态规划
63+ ### 方法一:排序 + 贪心
6464
65- 先将 pairs 按照第一个数字升序排列,然后转换为最长上升子序列问题 。
65+ 我们将所有数对按照第二个数的升序排序,用一个变量 $\textit{pre}$ 维护已经选择的数对的第二个数的最大值 。
6666
67- 朴素做法,时间复杂度 $O(n^2)$ 。
67+ 遍历排序后的数对,如果当前数对的第一个数大于 $\textit{pre}$,那么我们可以贪心地选择当前数对,答案加一,并将 $\textit{pre}$ 更新为当前数对的第二个数 。
6868
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+ 遍历结束后,返回答案即可。
20370
204- 时间复杂度 $O(n\ log n)$。
71+ 时间复杂度 $O(n \times \ log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数对的数量 。
20572
20673<!-- tabs:start -->
20774
@@ -210,11 +77,12 @@ impl Solution {
21077``` python
21178class Solution :
21279 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:
21784 ans += 1
85+ pre = b
21886 return ans
21987```
22088
@@ -223,13 +91,12 @@ class Solution:
22391``` java
22492class Solution {
22593 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 ]) {
23298 ++ ans;
99+ pre = p[1 ];
233100 }
234101 }
235102 return ans;
@@ -243,13 +110,11 @@ class Solution {
243110class Solution {
244111public:
245112 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] ;
253118 ++ans;
254119 }
255120 }
@@ -261,18 +126,16 @@ public:
261126#### Go
262127
263128```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
269132 for _, p := range pairs {
270- if cur < p[0] {
271- cur = p[1]
133+ if pre < p[0] {
272134 ans++
135+ pre = p[1]
273136 }
274137 }
275- return ans
138+ return
276139}
277140```
278141
@@ -281,15 +144,14 @@ func findLongestChain(pairs [][]int) int {
281144``` ts
282145function findLongestChain(pairs : number [][]): number {
283146 pairs .sort ((a , b ) => a [1 ] - b [1 ]);
284- let res = 0 ;
285- let pre = - Infinity ;
147+ let [ans, pre] = [0 , - Infinity ];
286148 for (const [a, b] of pairs ) {
287149 if (pre < a ) {
150+ ++ ans ;
288151 pre = b ;
289- res ++ ;
290152 }
291153 }
292- return res ;
154+ return ans ;
293155}
294156```
295157
@@ -298,18 +160,17 @@ function findLongestChain(pairs: number[][]): number {
298160``` rust
299161impl Solution {
300162 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 ;
303165 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 ]);
307168 if pre < a {
169+ ans += 1 ;
308170 pre = b ;
309- res += 1 ;
310171 }
311172 }
312- res
173+ ans
313174 }
314175}
315176```
0 commit comments