[LintCode] 300. Longest Increasing Subsequence

Problem

Given an unsorted array of integers, find the length of longest increasing subsequence.

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.

Note:

There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.

Follow up:

Could you improve it to O(n log n) time complexity?

Solution

using Arrays.binarySearch(int[] array, int start, int end, int target)

class Solution {
    public int lengthOfLIS(int[] nums) {
        int len = 0;
        //use Arrays.binarySearch() to find the right index of to-be-inserted number in dp[]
        int[] dp = new int[nums.length];
        for (int num: nums) {
            int index = Arrays.binarySearch(dp, 0, len, num);
            if (index < 0) {
                //calculate the right index in dp[] and insert num
                index = -index-1;
                dp[index] = num;
            }
            //if last inserted index equals len, increase len by 1
            //reason: index is 0-based, should always keep: len == index+1
            if (index == len) len++;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章