美文网首页
2019-01-07 Day 2

2019-01-07 Day 2

作者: 骚得过火 | 来源:发表于2019-01-07 19:34 被阅读0次

Day 2 01-07-2019

1.给定一个未经排序的整数数组,找到最长且连续的的递增序列。

来源:LeetCode
示例 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。

遍历整个数组,分别求出以每个数组元素为结尾的最长递增子序列,一遍遍历即可
class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        
        if( nums.size() == 0 )
            return 0 ;
        
        int current_size = 1;
        int max_length = 1;
        
        for( int i = 0 ; i < nums.size() ; i++ )
        {
            if( i == 0 )
            {
                continue;    
            }
            else
            {
                if( nums[i] > nums[i-1] )  //数组当前索引的元素比前一个大
                {
                    current_size += 1;
                    if(max_length <current_size) //更新最长递增子序列长度
                        max_length = current_size;
                }
                else
                {
                    current_size = 1;
                }
            }
        }
        
        return max_length;
        
    }
};

相关文章

网友评论

      本文标题:2019-01-07 Day 2

      本文链接:https://www.haomeiwen.com/subject/jnjprqtx.html