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++;
        }
    }
}

Define a binary search method

class Solution {
    public int lengthOfLIS(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int index = 0;
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int pos = findPos(dp, nums[i], index);
            if (pos > index) index = pos;
            dp[pos] = nums[i];
        }
        return index+1;
    }
    private int findPos(int[] nums, int val, int index) {
        int start = 0, end = index;
        while (start+1 < end) {
            int mid = start+(end-start)/2;
            if (nums[mid] == val) return mid;
            else if (nums[mid] < val) start = mid;
            else end = mid;
        }
        if (nums[end] < val) return end+1;
        else if (nums[start] < val) return end;
        else return start;
    }
}

linspiration
161 声望53 粉丝