Longest Continuous Increasing Subsequence(最长递增连续子序列)

题目:

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

给定一个无序的整型数组,找到最长的连续递增子序列。

例1:

输入:[1,3,5,4,7]

输出:3

2

输入:[2,2,2,2,2]

输出:1

法:时间复杂度O(N)

Every (continuous) increasing subsequence is disjoint, and the boundary of each such subsequence occurs whenever nums[i-1] >= nums[i]. When it does, it marks the start of a new increasing subsequence at nums[i], and we store such i in the variable anchor.

For example, if nums = [7, 8, 9, 1, 2, 3], then anchor starts at 0 (nums[anchor] = 7) and gets set again to anchor = 3 (nums[anchor] = 1). Regardless of the value of anchor, we record a candidate answer of i - anchor + 1, the length of the subarray nums[anchor], nums[anchor+1], ..., nums[i]; and our answer gets updated appropriately.

每一个连续递增子序列都是不相交的,并且当nums[i-1]>=nums[i]时,每个子序列的边界产生。我们可以给一个新产生的递增序列的起始点记为nums[i],然后将此时的i存为一个标记变量a。

比如,数组为[7,8,9,1,2,3],那么标记变量a为0(nums[a]=7),然后下一个标记变量a为3(nums[a]=1)。不管标记变量a的值为多少,我们可以将“i-a+1”的值记为子序列nums[a],nums[a+1],...,nums[i]的长度且结果会自适应的更新。

官方代码(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;
    }
}
复杂度分析:

Time Complexity: O(N),where N is the length of nums.

Space Complexity: O(1), the space used by anchor and ans.

时间复杂度:O(N),N是数组的长度。
空间复杂度:O(1),空间使用anchor和ans两个变量。

个人代码(C++):
class Solution {
public:
    int findLengthOfLCIS(vector& nums) {
        int l = 1;
        int ans = l;
        int len = nums.size();
        int i = 0;
        if (len == 0)
            return 0;
        for(i=1;i


你可能感兴趣的:(算法,数据结构)