https://leetcode.com/problems/russian-doll-envelopes/
LIS(最长递增子序列)变形题
要熟练使用Arrays的API主要是sort和binarySearch。二维数组也可以sort(加comparator即可)。
按照宽度递增排序,宽度相同的高度按照递减排序。然后遍历envelopes,用dp[i]记录套上i + 1个娃娃时所需要的最小高度(说是最小高度是因为宽度相同时高度递减排序,同时因为宽度递增排序,所以顺序遍历时宽度不需要考虑)
public class Solution {
public int maxEnvelopes(int[][] envelopes) {
if (envelopes == null || envelopes.length == 0) {
return 0;
}
Arrays.sort(envelopes, new Comparator<int[]>() {
public int compare(int[] arr1, int[] arr2) {
if (arr1[0] == arr2[0]) {
return arr2[1] - arr1[1];
} else {
return arr1[0] - arr2[0];
}
}
});
int[] dp = new int[envelopes.length];
int len = 0;
for (int[] envelope : envelopes) {
int index = Arrays.binarySearch(dp, 0, len, envelope[1]);
if (index < 0) {
index = -(index + 1);
}
dp[index] = envelope[1];
if (index == len) {
len++;
}
}
return len;
}
}