classSolution { publicintfindLongestChain(int[][] pairs) { Arrays.sort(pairs, (a, b) -> Integer.compare(a[0], b[0])); // index means the length of the chain and the element means the last pair's 1st // element List<Integer> list = newArrayList<>(); for (inti=0; i < pairs.length; i++) { inttargetChainIdx= binarySearch(list, pairs[i][0]); if (targetChainIdx + 1 == list.size()) { list.add(pairs[i][1]); } else { list.set(targetChainIdx + 1, Math.min(list.get(targetChainIdx + 1), pairs[i][1])); } } return list.size(); }
privateintbinarySearch(List<Integer> list, int target) { intleft=0, right = list.size() - 1, ans = -1; while (left <= right) { intmid= left + (right - left) / 2; if (list.get(mid) < target) { ans = mid; left = mid + 1; } else { right = mid - 1; } } return ans; } }