Leetcode

2019-02-09

2019-02-09  本文已影响0人  ruicore
LeetCode 300. Longest Increasing Subsequence.jpg

LeetCode 300. Longest Increasing Subsequence

Description

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:

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.

描述

给定一个无序的整数数组,找到其中最长上升子序列的长度。

示例:

输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
说明:

可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
你算法的时间复杂度应该为 O(n2) 。

思路

# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-02-08 18:23:33
# @Last Modified by:   何睿
# @Last Modified time: 2019-02-08 18:23:33


class Solution:
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 数组的个数
        length = len(nums)
        # 如果数组中没有元素或者只有一个元素,直接返回数组长度
        if length <= 1: return length
        # 动态规划,数组没个位置初始化为1
        # 表示连续递增的序列长度最下为1
        count = [1] * length
        res = 0
        for i in range(1, length):
            # 初始化为1
            _max = 1
            # 从当前位置遍历到i
            for j in range(0, i):
                # 第i个数的最大值为0到i-1中所有小于当前元素能够称的连续序列加一的最大值
                if nums[j] < nums[i]: _max = max(count[j] + 1, _max)
            # 更新当前位置的最大值
            count[i] = _max
            # 记录所有值的最大值
            res = max(res, _max)
        return res

源代码文件在这里.
©本文首发于何睿的博客,欢迎转载,转载需保留文章来源,作者信息和本声明.

上一篇下一篇

猜你喜欢

热点阅读