LeetCode 674. Longest Continuous Increasing Subsequence--python,Java,C++解法

LeetCode 674. Longest Continuous Increasing Subsequence


LeetCode题解专栏:LeetCode题解
我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java,Python和C++的解法都有。


此题链接:Longest Continuous Increasing Subsequence - LeetCode


Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).

Example 1:

Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 

Example 2:

Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1. 
Note: Length of the array will not exceed 10,000.

这道题目很简单,滑动窗口就可以了,时间复杂度是O(N),空间复杂度是O(1)。
Python代码如下:

class Solution:
    def findLengthOfLCIS(self, nums: List[int]) -> int:
        ans = anchor = 0
        length=len(nums)
        if length==0:
            return 0
        ans=1
        for i in range(1,length):
            if nums[i-1] >= nums[i]: 
                anchor = i
            ans = max(ans, i - anchor + 1)
        return ans

Java代码如下:

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

c++代码如下:

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

猜你喜欢

转载自blog.csdn.net/zhangpeterx/article/details/89414383