题解 | #信封嵌套#
信封嵌套
http://www.nowcoder.com/practice/25fe1fc89c4c4e82bbc63df04bc6ca30
根据题意,将第一维的数据进行排序,第二维的数据防止重复计算进行逆序排序,转化为求最长的上升子序列的长度(O(nlogn))的时间复杂度。
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int[][] letters = new int[n][2];
int[] tmp = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
letters[i][j] = reader.nextInt();
}
}
// 贪心 按照第一个进行排序,按照第二列进行最长上升序列
Arrays.sort(letters, (n1, n2) -> {
if (n1[0] != n2[0]) {
return n1[0] - n2[0];
} else {
return n2[1] - n1[1];
}
});
for (int i = 0; i < n; i++) {
tmp[i] = letters[i][1];
}
System.out.println(helper(tmp));
}
public static int helper(int[] nums) {
int n = nums.length;
int[] tails = new int[n + 1];
int res = 0;
for (int i = 0; i < n; i++) {
int l = 0, r = res;
while (l < r) {
int m = (l + r) / 2;
if (tails[m] < nums[i]) {
l = m + 1;
} else {
r = m;
}
}
tails[l] = nums[i];
if (r == res) res += 1;
}
return res;
}
}