LeetCode 674. Longest Continuous Increasing Subsequence最长连续递增序列 (C++/Java)
2024-10-18 23:36:35
题目:
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;
}
}
最新文章
- 【转】java通用URL接口地址调用方式GET和POST方式
- #import和@class的使用
- Linux 下编译安装MySQL
- Atitit 研发体系建立 数据存储与数据知识点体系知识图谱attilax 总结
- ASP.NET、C#调用外部可执行exe文件--多种方案
- 快速排序C++
- js注入,黑客之路必备!
- Oracle中instr 函数的详解
- java 抽象类和接口的区别
- J1签证办理全过程
- $(";#province";).val();取不到select的值求解
- leetcode刷题总结一
- hdu 4649 Professor Tian 反状态压缩+概率DP
- LA 3708 Graveyard(推理 参考系 中位数)
- PHP数组foreach后使用current取值的问题
- 简单使用JSON,JavaScript读取JSON文本(三)
- github设置添加SSH
- MySQL - 扩展性 1 概述:人多未必力量大
- linux-----docker
- ArcSDE数据库连接(直连、服务连)与GT_Geometry存储配置图解