# 最长递增子序列LIS的两种解法问题

0
[已关闭问题] 关闭于 2017-08-27 21:03

```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("出错了！");
}
}

}
}```

0

0
```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("出错了！");
}
}

}
}```
fcyh | 园豆：568 (小虾三级) | 2017-08-28 09:16

您需要登录以后才能回答，未注册用户请先注册