zoukankan      html  css  js  c++  java
  • leetcode 之 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? 

    即 给定一个无序的数组,找到最长的递增子序列。 返回其长度

    解法1: 动态规划的解法。 设maxIns[i]  为以第i个数结尾的最长递增子序列的长度。

    则maxIns[i+1]:

    遍历0~i, 若nums[i+1] > nums[j] (j ~(0, i))  maxIns[i+1] = max(maxIns[i+1] , maxIns[i]+1)

    算法的时间复杂度为o(n2), 空间复杂度为o(n), 代码如下:

     1 class Solution(object):
     2     def lengthOfLIS(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: int
     6         """
     7         ln = len(nums)
     8         if ln == 1 or ln == 0:
     9             return ln
    10         lgst = [1]*(ln+1)
    11         for i in range(1, ln):
    12             for j in range(0, i):
    13                 if nums[i] > nums[j]:
    14                     lgst[i] = max(lgst[j]+1, lgst[i])
    15         return max(lgst)
    ~~~~~
  • 相关阅读:
    报错:maven 程序包org.junit不存在
    Sublime Text 3
    Win10使用技巧
    CookieHelper
    log4net
    文件导出 Aspose
    C# 数字证书加载 X509Certificate2
    前后端文件上传
    WebApi 后端文件传输至远程服务器
    aspnet_regiis.exe用法(备忘非自创)
  • 原文地址:https://www.cnblogs.com/missmzt/p/5587393.html
Copyright © 2011-2022 走看看