Last active
August 29, 2017 19:15
-
-
Save cixuuz/3102e09bd4a5b5acce4bcbed79f578cf to your computer and use it in GitHub Desktop.
[646. Maximum Length of Pair Chain] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| // O(n^2) O(n) | |
| public int findLongestChain(int[][] pairs) { | |
| if (pairs == null || pairs.length == 0) return 0; | |
| Arrays.sort(pairs, (a, b) -> (a[0] - b[0])); | |
| int[] dp = new int[pairs.length]; | |
| Arrays.fill(dp, 1); | |
| for (int i = 0; i < dp.length; i++) { | |
| for (int j = 0; j < i; j++) { | |
| dp[i] = Math.max(dp[i], pairs[i][0] > pairs[j][1]? dp[j] + 1 : dp[j]); | |
| } | |
| } | |
| return dp[pairs.length-1]; | |
| } | |
| } | |
| class Solution1 { | |
| // O(nlogn) O(1) | |
| public int findLongestChain(int[][] pairs) { | |
| if (pairs == null || pairs.length == 0) return 0; | |
| Arrays.sort(pairs, (a, b) -> (a[1] - b[1])); | |
| int right = Integer.MIN_VALUE, n = 0; | |
| for (int[] pair : pairs) { | |
| if ( right < pair[0] ) { | |
| right = pair[1]; | |
| n += 1; | |
| } | |
| } | |
| return n; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment