題意:給出一個數組,求最長遞增子序列的長度
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
public int lengthOfLIS(int[] nums) {
//用来存长度为i的数组的结尾是哪个数,这一定是个递增的数组,所以我们用二分查找来找这个数插入的位置
int[] tails = new int[nums.length];
int size = 0;
for (int x : nums) {
int i = 0, j = size;
while (i != j) {
int m = (i + j) / 2;
if (tails[m] < x)
i = m + 1;
else
j = m;
}
//可能是新插入也可能是替换的
tails[i] = x;
//如果是新插入的话,size+1
if (i == size) ++size;
}
return size;
}