300-最长上升子序列

题目描述

给定一个无序的整数数组,找到其中最长上升子序列的长度。

示例:

输入: [10,9,2,5,3,7,101,18]
输出: 4 
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。

说明:

  • 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
  • 你算法的时间复杂度应该为 O(n2) 。

进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?


解题思路

利用动态规划和二分查找解题。

遍历一遍数组,dp[]表示目前为止的上升子序列(不一定是最长),通过二分查找,找到当前元素在dp[]中的位置,如果为负值,则说明该元素比dp[]中所有元素都小,索引值要相应处理一下,然后原地替换;如果为正值,说明该元素比dp[]中所有元素都大,则加入尾部,顺便len++

Java 实现

public int lengthOfLIS (int[] nums) {
    int[] dp = new int[nums.length];
    int len = 0;
    for (int num : nums) {
        int i = Arrays.binarySearch(dp,0,len,num);
        if (i < 0) i = -(i+1);
        dp[i] = num;
        if (i == len) len++;
    }
    return len;
}

心得体会

JDK 中数组二分查找的用法:

public static int binarySearch(int[] a,
            int fromIndex,
            int toIndex,
            int key)

Searches a range of the specified array of ints for the specified value using the binary search algorithm. The range must be sorted (as by the sort(int[\], int, int)) method) prior to making this call. If it is not sorted, the results are undefined. If the range contains multiple elements with the specified value, there is no guarantee which one will be found.

  • Parameters:

a - the array to be searched

fromIndex - the index of the first element (inclusive) to be searched

toIndex - the index of the last element (exclusive) to be searched

key - the value to be searched for

  • Returns:

index of the search key, if it is contained in the array within the specified range; otherwise, (-(*insertion point*) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element in the range greater than the key, or toIndex if all elements in the range are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

  • Throws:

IllegalArgumentException - if fromIndex > toIndex

ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > a.length

  • Since:

1.6


  转载请注明: yuzhenzero 300-最长上升子序列

 上一篇
524-通过删除字母匹配到字典里最长单词 524-通过删除字母匹配到字典里最长单词
题目描述给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。 示例 1: 输入: s = "
2019-04-11
下一篇 
322-零钱兑换 322-零钱兑换
题目描述给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 示例 1: 输入: coins = [1, 2, 5], amou
2019-04-03
  目录