File tree 1 file changed +14
-14
lines changed
src/main/java/com/fishercoder/solutions/firstthousand
1 file changed +14
-14
lines changed Original file line number Diff line number Diff line change 3
3
import java .util .Arrays ;
4
4
5
5
public class _646 {
6
+ /**
7
+ * Although this problem could be solved using DP, greedy is more efficient in both time and space complexity.
8
+ */
6
9
public static class Solution1 {
7
10
/**
8
- * credit: https://discuss. leetcode.com/topic/96804/java-o-nlog-n-time-o-1-space
11
+ * credit: https://leetcode.com/problems/maximum-length-of-pair-chain/editorial/
9
12
*/
10
13
public int findLongestChain (int [][] pairs ) {
11
- Arrays .sort (pairs , (o1 , o2 ) -> o1 [1 ] - o2 [1 ]);
12
- int result = 0 ;
13
- int n = pairs .length ;
14
- int i = -1 ;
15
- while (++i < n ) {
16
- result ++;
17
- int curEnd = pairs [i ][1 ];
18
- while (i + 1 < n && pairs [i + 1 ][0 ] <= curEnd ) {
19
- /**This means, we'll keep incrementing i until pairs[i+1][0] is
20
- * exactly greater than curEnd.*/
21
- i ++;
14
+ //sort by the second element
15
+ Arrays .sort (pairs , (a , b ) -> a [1 ] - b [1 ]);
16
+ int ans = 0 ;
17
+ int prev = Integer .MIN_VALUE ;
18
+ for (int [] pair : pairs ) {
19
+ if (pair [0 ] > prev ) {
20
+ ans ++;
21
+ prev = pair [1 ];
22
22
}
23
23
}
24
- return result ;
24
+ return ans ;
25
25
}
26
26
}
27
27
@@ -30,7 +30,7 @@ public static class Solution2 {
30
30
* credit: https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/105623/Java-Very-Simple-without-DP
31
31
*/
32
32
public int findLongestChain (int [][] pairs ) {
33
- //sort by pair[0]
33
+ //sort by the first element
34
34
Arrays .sort (pairs , (a , b ) -> a [0 ] - b [0 ]);
35
35
int len = 0 ;
36
36
int pre = Integer .MIN_VALUE ;
You can’t perform that action at this time.
0 commit comments