397. Longest Continuous Increasing Subsequence
给定一个整数数组(下标从 0 到 n-1, n 表示整个数组的规模),请找出该数组中的最长上升连续子序列。(最长上升连续子序列可以定义为从右到左或从左到右的序列。)
样例
给定 [5, 4, 2, 1, 3]
, 其最长上升连续子序列(LICS)为 [5, 4, 2, 1]
, 返回 4
.
给定 [5, 1, 2, 3, 4]
, 其最长上升连续子序列(LICS)为 [1, 2, 3, 4]
, 返回 4
.
注意事项
time
解题思路:思路还是很好想的,值得注意的地方就是序列不一定从头开始,可能在中间。
代码:
public class Solution {
/**
* @param A: An array of Integer
* @return: an integer
*/
public int longestIncreasingContinuousSubsequence(int[] A) {
// write your code here
if(A.length == 0)
return 0;
int count1 = 1,count2 = 1;
int max1 = 1,max2 = 1;
int len = A.length;
for (int i=1; i<len;i++ ){
if(A[i]<A[i-1])
count1++;
else{
if(max1<count1)
max1 = count1;
count1 = 1;
//continue;
}
}
if(max1<count1)
max1 = count1;
//System.out.println(count1);
for(int i=len-1;i>0;i--){
if(A[i]>A[i-1])
count2++;
else{
if(max2<count2)
max2 = count2;
count2 = 1;
//continue;
}
}
if(max2<count2)
max2 = count2;
return max2>max1?max2:max1;
}
}
上网上百度了一下别人的代码,没有对比就没有伤害,但是思路都是差不的,哈哈哈。。。
贴几个别人的代码,好东西要分享的。。。
来源:https://www.jiuzhang.com/solution/longest-continuous-increasing-subsequence/
public class Solution {
/**
* @param A: An array of Integer
* @return: an integer
*/
public int longestIncreasingContinuousSubsequence(int[] A) {
if (A == null || A.length == 0) return 0;
int max = 1;
//from left to right
int inCount = 1;
int deCount = 1;
for (int i = 1; i < A.length; i++)
{
if (A[i] > A[i-1]) inCount++;
else inCount = 1;
if (A[i] < A[i-1]) deCount++;
else deCount = 1;
max = Math.max(max, Math.max(inCount, deCount));
}
return max;
}
}
public int longestIncreasingContinuousSubsequence(int[] A) {
// write your code here
if(A == null || A.length == 0){
return 0;
}
if(A.length == 1)
return 1;
int j = 1;
int i = 0;
int max = 0;
while(i<A.length && j<A.length){
boolean increase = A[i] <= A[j] ? true : false;
j++;
while(j<A.length){
if(increase && A[j-1] > A[j]){
break;
}
if(!increase && A[j-1] < A[j]){
break;
}
j++;
}
max = Math.max(max, j-i);
i=j-1;
}
return max;
}
public class Solution {
/**
* @param A: An array of Integer
* @return: an integer
*/
public int longestIncreasingContinuousSubsequence(int[] A) {
// write your code here
if (A == null || A.length == 0) {
return 0;
}
int longest = 1;
int count = 2;
boolean prevUp;
for (int i = 1; i < A.length - 1; i++) {
prevUp = A[i - 1] > A[i];
if (A[i] > A[i + 1] == prevUp) {
count += 1;
} else {
prevUp = A[i] > A[i + 1];
count = 2;
}
longest = Math.max(longest, count);
}
return longest;
}
}
还是很容易理解的,主要学习一下别人代码的整洁。。。