法1:DP,LIS问题
O(N*N)基本方法,必须掌握!!!
class Solution {
public int maxEnvelopes(int[][] envelopes) {
int n = envelopes.length;
if (n < 2) {
return n;
}
Arrays.sort(envelopes, (a1, a2) -> {
return a1[0] == a2[0] ? a2[1] - a1[1] : a1[0] - a2[0];
});
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; ++i) {
list.add(envelopes[i][1]);
}
int[] dp = new int[n];
int max = 1;
Arrays.fill(dp, 1);
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (list.get(i) > list.get(j) && (dp[j] + 1 > dp[i])) {
dp[i] = dp[j] + 1;
}
}
max = Math.max(max, dp[i]);
}
return max;
}
}
法2:二分法
O(nlgn),注意,此处二分的左右索引与习惯不太一致!
class Solution {
public int maxEnvelopes(int[][] envelopes) {
int n = envelopes.length;
if (n < 2) {
return n;
}
Arrays.sort(envelopes, (a1, a2) -> {
return a1[0] == a2[0] ? a2[1] - a1[1] : a1[0] - a2[0];
});
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; ++i) {
list.add(envelopes[i][1]);
}
int max = lis(list);
return max;
}
int lis(List<Integer> list) {
int n = list.size();
if (n < 2) {
return n;
}
int count = 0;
int[] top = new int[n];
for (int i = 0; i < n; ++i) {
int left = 0, right = count, curVal = list.get(i); // 注意: 这里right取得n
while (left < right) { // 注意: 这里没有"="
int mid = left + (right - left) / 2;
if (top[mid] >= curVal) {
right = mid;
} else {
left = mid + 1;
}
}
if (left == count) {
++count;
}
top[left] = curVal;
}
return count;
}
}