300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,Given [10, 9, 2, 5, 3, 7, 101, 18],The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that 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?
我们使用一个数组tail,这个数组的第i个元素保存着长i+1的增序列中结尾最小的序列的结尾
比如:[10, 9, 2, 5, 3, 7, 101, 18]。这个数组就是:[2,3,7,18]。
对应的序列是:[2],[2,3],[2,3,7],[2,3,7,18]。
可以发现这个数组一定是不减的。
那么我们从头开始遍历整个数组,对于每一个元素,我们在tail里二分找一下:
如果它大于tail里的每一个元素,那就意味着有一个新的长度的增序列出现了,我们把这个元素放到tail的末尾;
如果它不大于所有元素,找到第一个大于等于它的,换掉这个元素。
最后最长子数组的长度就是tail数组的长度。

var lengthOfLIS = function(nums) {
    var tails = [];
    var size = 0;
    var num = nums.length;
    for (var i = 0;i < num;i++) {
        var left = 0, right = size;
        while (left != right) {
            var m = parseInt((left + right) / 2);
            if (tails[m] < nums[i])
                left = m + 1;
            else
                right = m;
        }
        tails[left] = nums[i];
        if (left == size) ++size;
    }
    return size;
};

你可能感兴趣的:(300. Longest Increasing Subsequence)