我写了最长递增子序列问题的两种解法,一种是O(n²)的方法,一种是O(nlogn)的方法,但是两个方法写完以后用对数器跑了下发现有问题,但是自己检查代码好久也看不出问题,下面是代码
public class GetLis { // O(n²) public static int getLis1(int[] arr) { int maxLen = 1; int[] dp = new int[arr.length]; for (int i = 0; i < arr.length; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; } } maxLen = Math.max(maxLen, dp[i]); } return maxLen; } // O(nlogn) public static int getLis2(int[] arr) { int maxLen = 1; int[] dp = new int[arr.length]; int right = 0; int l = 0; int r = 0; int m = 0; dp[0] = 1; for (int i = 1; i < arr.length; i++) { l = 0; r = right; while (l <= r) { m = (l + r) / 2; if (arr[i] > dp[m]) { l = m + 1; } else { r = m - 1; } } right = Math.max(l, right); dp[l] = arr[i]; } maxLen = right + 1; return maxLen; } public static void main(String[] args) { // 对数器验证 for (int i = 0; i < 10000; i++) { int n = (int) (Math.random() * 98 + 2); int[] arr = new int[n]; for (int j = 0; j < n; j++) { arr[j] = (int) (Math.random() * 200); } int res1 = getLis1(arr); int res2 = getLis2(arr); if (res1 != res2) { System.out.println("出错了!"); } } } }
求大佬帮我看看问题!
解决了。实在太不认真了,dp[0]赋值应该为arr[0],我给他赋值1,所以导致了错误
public class GetLis { // O(n²) public static int getLis1(int[] arr) { int maxLen = 1; int[] dp = new int[arr.length]; for (int i = 0; i < arr.length; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; } } maxLen = Math.max(maxLen, dp[i]); } return maxLen; } // O(nlogn) public static int getLis2(int[] arr) { int maxLen = 1; int[] dp = new int[arr.length]; int right = 0; int l = 0; int r = 0; int m = 0; dp[0] = arr[0]; for (int i = 1; i < arr.length; i++) { l = 0; r = right; while (l <= r) { m = (l + r) / 2; if (arr[i] > dp[m]) { l = m + 1; } else { r = m - 1; } } right = Math.max(l, right); dp[l] = arr[i]; } maxLen = right + 1; return maxLen; } public static void main(String[] args) { // 对数器验证 for (int i = 0; i < 10000; i++) { int n = (int) (Math.random() * 98 + 2); int[] arr = new int[n]; for (int j = 0; j < n; j++) { arr[j] = (int) (Math.random() * 200); } int res1 = getLis1(arr); int res2 = getLis2(arr); if (res1 != res2) { System.out.println("出错了!"); } } } }
解决了。谢谢了。