博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] Longest Increasing Subsequence
阅读量:7056 次
发布时间:2019-06-28

本文共 1930 字,大约阅读时间需要 6 分钟。

Problem

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Clarification

What's the definition of longest increasing subsequence?

The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.

Example

For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3

For [4, 2, 4, 5, 3, 7], the LIS is [2, 4, 5, 7], return 4

Challenge

Time complexity O(n^2) or O(nlogn)

Solution

DP O(n^2)

public class Solution {    public int longestIncreasingSubsequence(int[] nums) {        int n = nums.length, max = 0;        int[] dp = new int[n];        for (int i = 0; i < n; i++) {            dp[i] = 1;            for (int j = 0; j < i; j++) {                dp[i] = nums[i] >= nums[j] ? Math.max(dp[j]+1, dp[i]) : dp[i];                max = Math.max(max, dp[i]);            }        }        return max;    }}

Binary Search O(nlogn)

public class Solution {    public int longestIncreasingSubsequence(int[] nums) {        int n = nums.length, max = 0;        if (n == 0) return 0;        int[] tails = new int[nums.length];        tails[0] = nums[0];        int index = 0;        for (int i = 1; i < nums.length; i++) {            if (nums[i] < tails[0]) tails[0] = nums[i];            else if (nums[i] >= tails[index]) tails[++index] = nums[i];            else tails[bisearch(tails, 0, index, nums[i])] = nums[i];        }        return index+1;    }    public int bisearch(int[] tails, int start, int end, int target) {        while (start <= end) {            int mid = start + (end-start)/2;            if (tails[mid] == target) return mid;            else if (tails[mid] < target) start = mid+1;            else end = mid-1;        }        return start;    }}

转载地址:http://oglol.baihongyu.com/

你可能感兴趣的文章
004-线程同步问题引出、同步问题解决、死锁、生产者与消费者
查看>>
学习正则表达式
查看>>
glibc的几个有用的处理二进制位的内置函数(转)
查看>>
vue 跨域:使用vue-cli 配置 proxyTable 实现跨域问题
查看>>
围棋十诀
查看>>
nodejs - 创建服务器(1)
查看>>
Unity读Excel 输出PC端(Windows)后不能读取的问题
查看>>
一台服务器部署多个tomcat
查看>>
shell判断文件是否存在
查看>>
XNA程序开发常用到的一些代码汇总
查看>>
Running ASP.NET Applications in Debian and Ubuntu using XSP and Mono
查看>>
Hudson+Maven+SVN 快速搭建持续集成环境
查看>>
VC++ 编译环境设置 学习之路vs2005
查看>>
Getting Back to a Pure Gnome on Ubuntu
查看>>
Linux之父话糙理不糙 - 51CTO.COM
查看>>
ACM HDU 1404 Digital Deletions(博弈)
查看>>
solution for lost fonts
查看>>
SQL语法大全(转)
查看>>
linux C++开发学习
查看>>
supports-screens
查看>>