题目:

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.

分析:

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

注意是要找到连续的递增序列,由于需要连续,这道题就变得简单了许多。我们可以创建一个和给定数组同样大小的数组res,用来记录到当前元素递增序列的长度。

nums 1 3 5 4 7
res 1 2 3 1 2

初始化res[0]为1,因为有一个数的话,大小也是1。如果当前元素大于前一个元素,则长度加1,否则,意味着当前元素无法和前面的序列继续构成递增这一条件,我们要计算后面的递增序列的大小,所以重新置为1。遍历完数组后,直接返回res中最大值即可。

当然我们也可以不适用数组来存储,可以发现比较数组元素是否递增时,如果保持递增,序列长度加1,那么我们可以创建两个变量,一个用来保存当前的递增序列长度,如果下一个元素符合条件,就加1,否则就重新置为1,另一个变量用来保存最终解,每一次更新当前递增序列长度,都和最终解比较大小,将大的值赋给最终解。

nums 1 3 5 4 7
temp 1 2 3 1 2
res 1 2 3 3 3

程序:

C++

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

Java

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

最新文章

  1. 【转】java通用URL接口地址调用方式GET和POST方式
  2. #import和@class的使用
  3. Linux 下编译安装MySQL
  4. Atitit 研发体系建立 数据存储与数据知识点体系知识图谱attilax 总结
  5. ASP.NET、C#调用外部可执行exe文件--多种方案
  6. 快速排序C++
  7. js注入,黑客之路必备!
  8. Oracle中instr 函数的详解
  9. java 抽象类和接口的区别
  10. J1签证办理全过程
  11. $(&quot;#province&quot;).val();取不到select的值求解
  12. leetcode刷题总结一
  13. hdu 4649 Professor Tian 反状态压缩+概率DP
  14. LA 3708 Graveyard(推理 参考系 中位数)
  15. PHP数组foreach后使用current取值的问题
  16. 简单使用JSON,JavaScript读取JSON文本(三)
  17. github设置添加SSH
  18. MySQL - 扩展性 1 概述:人多未必力量大
  19. linux-----docker
  20. ArcSDE数据库连接(直连、服务连)与GT_Geometry存储配置图解

热门文章

  1. Re-DD-androideasy
  2. ES6 class类中定义私有变量
  3. Fiddler修改请求数据
  4. sql server相邻表记录交换(单双两两交换)
  5. js的promise
  6. Percona Monitoring and Management (PMM) - 快速入门
  7. 转Ubuntu 16.04 创建无线热点
  8. SAP模块常用增强总结(转)
  9. C#上手练习3(while、do while语句)(添加机器人聊天)
  10. webpack资源处理