给定一个未经排序的整数数组,找到最长且连续的的递增序列。
示例 1:
输入: [1,3,5,4,7]
输出: 3
解释: 最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。
示例 2:
输入: [2,2,2,2,2]
输出: 1
解释: 最长连续递增序列是 [2], 长度为1。
注意:数组长度不会超过10000。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1
朴素解法
class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
count=1
temp=1
for i in range(len(nums)-1):
if nums[i]<nums[i+1]:
temp+=1
else:
if temp>count:
count=temp
temp=1
if temp>count:
count=temp
return count
执行结果:
通过
显示详情
执行用时 :68 ms, 在所有 Python 提交中击败了63.72%的用户
内存消耗 :13.7 MB, 在所有 Python 提交中击败了50.00%的用户
思路2
滑动窗口法
class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res=0
tmp=0
for i in range(len(nums)):
if i and nums[i-1]>=nums[i]:
tmp=i
res=max(res,i-tmp+1)
return res
执行结果:
通过
显示详情
执行用时:64 ms, 在所有 Python 提交中击败了80.26%的用户
内存消耗:13.6 MB, 在所有 Python 提交中击败了50.00%的用户
思路3
动态规划
class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp=[1]*len(nums)
for i in range(1,len(nums)):
if nums[i-1]<nums[i]:
dp[i]=dp[i-1]+1
return max(dp)
执行结果:
通过
显示详情
执行用时:72 ms, 在所有 Python 提交中击败了44.96%的用户
内存消耗:13.6 MB, 在所有 Python 提交中击败了50.00%的用户