Skip to content

Latest commit

 

History

History
 
 

0674.Longest Continuous Increasing Subsequence

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

English Version

题目描述

给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。

连续递增的子序列 可以由两个下标 lrl < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。

 

示例 1:

输入:nums = [1,3,5,4,7]
输出:3
解释:最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。 

示例 2:

输入:nums = [2,2,2,2,2]
输出:1
解释:最长连续递增序列是 [2], 长度为1。

 

提示:

  • 1 <= nums.length <= 104
  • -109 <= nums[i] <= 109

解法

设 f(i) 表示将数组第 i 项作为最长连续递增子序列的最后一项时,子序列的长度。

那么,当 nums[i - 1] < nums[i],即 f(i) = f(i - 1) + 1,否则 f(i) = 1。问题转换为求 f(i) (i ∈ [0 ,n - 1]) 的最大值。

由于 f(i) 只与前一项 f(i - 1) 有关联,故不需要用一个数组存储。

Python3

class Solution:
    def findLengthOfLCIS(self, nums: List[int]) -> int:
        res, n = 1, len(nums)
        i = 0
        while i < n:
            j = i + 1
            while j < n and nums[j] > nums[j - 1]:
                j += 1
            res = max(res, j - i)
            i = j
        return res
class Solution:
    def findLengthOfLCIS(self, nums: List[int]) -> int:
        n = len(nums)
        res = f = 1
        for i in range(1, n):
            f = 1 + (f if nums[i - 1] < nums[i] else 0)
            res = max(res, f)
        return res

Java

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        int res = 1;
        for (int i = 1, f = 1; i < nums.length; ++i) {
            f = 1 + (nums[i - 1] < nums[i] ? f : 0);
            res = Math.max(res, f);
        }
        return res;
    }
}

双指针:

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        int res = 1;
        for (int i = 0, n = nums.length; i < n;) {
            int j = i + 1;
            while (j < n && nums[j] > nums[j - 1]) {
                ++j;
            }
            res = Math.max(res, j - i);
            i = j;
        }
        return res;
    }
}

C++

class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        int res = 1;
        for (int i = 1, f = 1; i < nums.size(); ++i)
        {
            f = 1 + (nums[i - 1] < nums[i] ? f : 0);
            res = max(res, f);
        }
        return res;
    }
};

Go

func findLengthOfLCIS(nums []int) int {
	res, f := 1, 1
	for i := 1; i < len(nums); i++ {
		if nums[i-1] < nums[i] {
			f += 1
			res = max(res, f)
		} else {
			f = 1
		}
	}
	return res
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

TypeScript

function findLengthOfLCIS(nums: number[]): number {
    const n = nums.length;
    let res = 1;
    let i = 0;
    for (let j = 1; j < n; j++) {
        if (nums[j - 1] >= nums[j]) {
            res = Math.max(res, j - i);
            i = j;
        }
    }
    return Math.max(res, n - i);
}

...