397. Longest Continuous Increasing Subsequence
Posted phdeblog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了397. Longest Continuous Increasing Subsequence相关的知识,希望对你有一定的参考价值。
Description
Give an integer array,find the longest increasing continuous subsequence in this array.
An increasing continuous subsequence:
- Can be from right to left or from left to right.
- Indices of the integers in the subsequence should be continuous.
O(n) time and O(1) extra space.
Example
For [5, 4, 2, 1, 3]
, the LICS is [5, 4, 2, 1]
, return 4
.
For [5, 1, 2, 3, 4]
, the LICS is [1, 2, 3, 4]
, return 4
.
解题:记录连续增大或者连续减少的个数,返回最大值。代码如下:
public class Solution {
/**
* @param A: An array of Integer
* @return: an integer
*/
public int longestIncreasingContinuousSubsequence(int[] A) {
// write your code here
int i_count = 1;//上升的时候的个数
int d_count = 1;//下降时候的个数
int temp = 1;
//注意,当下标有减号时,要注意返回,下标不为负
if(A.length == 0){
return 0;
}
for(int i = 1; i < A.length; i++){
if(A[i] > A[i-1]){
//说明增大
temp++;
}else{
//否则
if(temp > i_count){
i_count = temp;//更新
}
temp = 1;
}
}
if(temp > i_count){
//如果一直到最后,可能缺少一次跟新
i_count = temp;
}
temp = 1;
for(int i = 1; i < A.length; i++){
if(A[i] < A[i-1]){
//说明减小
temp++;
}else{
//否则
if(temp > d_count){
d_count = temp;//更新
}
temp = 1;
}
}
if(temp > d_count){
//如果一直到最后,可能缺少一次跟新
d_count = temp;
}
if(i_count >= d_count)
return i_count;
else return d_count;
}
}
以上是关于397. Longest Continuous Increasing Subsequence的主要内容,如果未能解决你的问题,请参考以下文章
Longest Continuous Increasing Subsequence
674. Longest Continuous Increasing Subsequence
674. Longest Continuous Increasing Subsequence
674. Longest Continuous Increasing Subsequence@python