题目
求一个数组的最长严格递增子序列
比如:输入8
5 9 4 1 3 7 6 7
输出 4
解题思路
假设要寻找的最长上升子序列的是a[n],然后寻找到的递增子序列放入到数组b中。
1.当遍历到数组a的第一个元素时,将这个元素放入到b数组中,以后遍历到的元素和已经放入到b中的元素进行比较;
2.如果比b数组中的每个元素都大,则将该元素插入到b数组的最后一个元素,并且b数组的长度加1;
3.如果比b数组中最后一个元素小,就要用二分查找法进行查找,查找出第一个比该元素大的最小的元素,然后将其替换;
重复2,3步,最后b数组的长度就是最长的上升子序列的长度。
比如:序列为5 9 4 1 3 7 6 7
那么
5 //加入
5 9 //加入
4 9 //用4替换5
1 9 //用1替换4
1 3 //用3替换9
1 3 7 //加入
1 3 6 //用6替换7
1 3 6 7 //加入
源代码
import java.util.Arrays;
public class SubSeqLong {
public static void main(String[] args) {
System.out.println(subSeqLong(8, new int[]{5, 9, 4, 1, 3, 7, 6, 7}));
}
private static int subSeqLong(int num, int[] numbers) {
int len;
int[] arr = new int[num];//用于保存最长子序列
Arrays.fill(arr, 0);//初始化为0
int count = 1;
arr[count] = numbers[0];//将第一个元素加入数组
for (int i = 2; i < num; i++) {
if (arr[count] > numbers[i]) {
len = BinarySearch(arr, numbers[i], 1, count);//二分查找
arr[len] = numbers[i];//numbers[i]<arr[count]
} else if (arr[count] < numbers[i]) {//numbers[i]>arr[count]
arr[++count] = numbers[i];//直接追加到arr数组后面
}
}
return count;//返回子序列长度
}
private static int BinarySearch(int[] arr, int number, int low, int hight) {
int mid;
while (low <= hight) {
mid = (low + hight) / 2;//中间位置
if (number > arr[mid])
low = mid + 1;
else
hight = mid - 1;
}
return low;
}
}