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)
    ~~~~~
  • 相关阅读:
    jni ndk 入门
    Activity 四种启动模式
    广播接收者 BroadcastReceiver
    android 焦点 ListView 点击事件获取失败
    android 动画效果
    JAVA 配置
    python 1:列表和字典
    poj1595 水题
    hdu 1181 深搜
    poj3264 划分树
  • 原文地址:https://www.cnblogs.com/missmzt/p/5587393.html
Copyright © 2011-2022 走看看