藍洞新作《雷霆一號》今日在steam正式發售 支援中文
阿新 • • 發佈:2021-12-08
給定一個未排序的整數陣列,找到最長遞增子序列的個數。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航import java.util.ArrayList; import java.util.List; class Solution { /** * 查詢第一個i,使得 data.get(i).get(data.get(i).size() - 1) >= target * * @param data * @param n * @param target * @return */ private static int search1(List<List<Integer>> data, int n, int target) { int l = 0, r = n - 1; while (l <= r) { int mid = (l + r) >> 1; if (data.get(mid).get(data.get(mid).size() - 1) < target) { l = mid + 1; } else { r = mid - 1; } } return l; } /** * 查詢第一個i,使得data.get(i) < target * * @param data * @param n * @param target * @return */ private static int search2(List<Integer> data, int n, int target) { int l = 0, r = n - 1; while (l <= r) { int mid = (l + r) >> 1; if (data.get(mid) >= target) { l = mid + 1; } else { r = mid - 1; } } return l; } public static int findNumberOfLIS(int[] nums) { List<List<Integer>> dp = new ArrayList<>(); List<List<Integer>> count = new ArrayList<>(); for (int num : nums) { int index = search1(dp, dp.size(), num); int cnt = 1; if (index > 0) { int k = search2(dp.get(index - 1), dp.get(index - 1).size(), num); cnt = count.get(index - 1).get(count.get(index - 1).size() - 1) - (k == 0 ? 0 : count.get(index - 1).get(k - 1)); } if (index == dp.size()) { List<Integer> dpItem = new ArrayList<>(); dpItem.add(num); dp.add(dpItem); List<Integer> countItem = new ArrayList<>(); countItem.add(cnt); count.add(countItem); } else { dp.get(index).add(num); cnt += count.get(index).get(count.get(index).size() - 1); count.get(index).add(cnt); } } return count.get(count.size() - 1).get(count.get(count.size() - 1).size() - 1); } }