76.Longest Increasing Subsequence-最长上升子序列(中等题)

最长上升子序列

  1. 题目

    给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。

  2. 说明

    最长上升子序列的定义:
    最长上升子序列问题是在一个无序的给定序列中找到一个尽可能长的由低到高排列的子序列,这种子序列不一定是连续的或者唯一的。
    https://en.wikipedia.org/wiki/Longest_increasing_subsequence

  3. 样例

    给出 [5,4,1,2,3],LIS 是 [1,2,3],返回 3
    给出 [4,2,4,5,3,7],LIS 是 [2,4,5,7],返回 4

  4. 挑战

    要求时间复杂度为O(n^2) 或者 O(nlogn)

  5. 题解

1.动态规划O(n^2)
假设在数组nums的前i个元素中,最长上升子序列长度为max[i]。如果nums[i+1]大于nums[k],k<=i。那么第i+1个元素可以构成一个更长的子序列。同时每个元素本身至少可以构成一个长度为1的子序列。

public class Solution {
    /**
     * @param nums: The integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
    public int longestIncreasingSubsequence(int[] nums) {
        if (nums.length == 0)
        {
            return 0;
        }
        int[] max = new int[nums.length];
        for (int i=0;i<nums.length;i++)
        {
            max[i] = 1;
            for (int j=0;j<i;j++)
            {
                //max[j]+1>max[i]的作用是排除前面同等长度子序列
                if (nums[i] > nums[j] && max[j]+1>max[i])
                {
                    max[i] = max[j]+1;
                }
            }
        }
        int result = max[0];
        for (int i=1;i<max.length;i++)
        {
            result = Math.max(result,max[i]);
        }

        return result;
    }
}

2.O(nLogn)

只要nums[i]大于i之前所有的数,则LIS则可以直接+1。定义等长数组lis用Integer.MAX_VALUE初始化,对nums进行遍历,将lis中第一个大于等于nums[i]的数lis[index]替换为nums[i]。则index的最大长度就是答案。查找lis[index]的过程可以用二分法替换遍历以达到O(nLogn)。

public class Solution {
    /**
     * @param nums: The integer array
     * @return: The length of LIS (longest increasing subsequence)
     */
    public int longestIncreasingSubsequence(int[] nums) {
        int[] lis = new int[nums.length];
        int max = 0;
        for (int i = 0; i < nums.length; i++) 
        {
            lis[i] = Integer.MAX_VALUE;
            int index = binarySearch(lis, nums[i],i);
            lis[index] = nums[i];
            max = Math.max(max,index);
        }

        return nums.length == 0 ? 0 : ++max;
    }

    private int binarySearch(int[] lis, int num, int end) 
    {
        int start = 0;
        while (start < end)
        {
            int mid = (end - start) / 2 + start;
            if (lis[mid] < num) 
            {
                start = mid+1;
            } 
            else 
            {
                end = mid;
            }
        }

        return end;
    }
}

Last Update 2016.10.4

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值