1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public int maxEnvelopes(int[][] envelopes) { int n = envelopes.length; if (n == 0) return 0; Arrays.sort(envelopes, (a, b) -> { if (a[0] != b[0]) return a[0] - b[0]; else return b[1] - a[1]; }); List<Integer> list = new ArrayList<>(); list.add(envelopes[0][1]); for (int i = 1; i < n; ++i) { int h = envelopes[i][1]; if (h > list.get(list.size() - 1)) { list.add(h); } else { int index = binarySearch(list, h); list.set(index, h); } } return list.size(); }
private int binarySearch(List<Integer> list, int target) { int left = 0, right = list.size() - 1; while (left < right) { int mid = left + right >> 1; if (list.get(mid) >= target) right = mid; else left = mid + 1; } return left; } }
|