You've successfully subscribed to The Daily Awesome
Welcome back! You've successfully signed in.
Success! Your billing info is updated.
Billing info update failed.

978. 最长湍流子数组 - Longest Turbulent Subarray

当 A 的子数组 A[i], A[i+1], ..., A[j] 满足下列条件时，我们称其为湍流子数组：



Example:

输入：[9,4,2,10,7,8,8,1,9]



输入：[4,8,12,16]



输入：[100]



1. 1 <= A.length <= 40000
2. 0 <= A[i] <= 10^9

Solutions

Solution  ( 15ms)

class Solution {
public int maxTurbulenceSize(int[] A) {
int length = A.length;
if (length == 1) {
return 1;
} else if (length == 2) {
return A[0] == A[1] ? 1 : 2;
}

int lastCOmpare = Integer.compare(A[0], A[1]);
int presentCompare;
int maxLength = 0;
int curLength = lastCOmpare == 0 ? 1 : 2;
for (int i = 1, len = length - 1; i < len; i++) {
presentCompare = Integer.compare(A[i], A[i+1]);
if (lastCOmpare == 0) {
lastCOmpare = presentCompare;
curLength = lastCOmpare == 0 ? 1 : 2;
continue;
} else if (presentCompare == 0) {
lastCOmpare = presentCompare;
if (curLength > maxLength) {
maxLength = curLength;
}
curLength = 1;
} else if (Math.abs(presentCompare + lastCOmpare) == 2) {
lastCOmpare = presentCompare;
if (curLength > maxLength) {
maxLength = curLength;
}
curLength = 2;
} else {
lastCOmpare = presentCompare;
curLength++;
}
}
if (curLength > maxLength) {
maxLength = curLength;
}
return maxLength;
}
}


Solution  ( 22ms)

class Solution {
public int maxTurbulenceSize(int[] A) {
int N = A.length;
int ans = 1;
int anchor = 0;

for (int i = 1; i < N; ++i) {
int c = Integer.compare(A[i-1], A[i]);
if (i == N-1 || c * Integer.compare(A[i], A[i+1]) != -1) {
if (c != 0) ans = Math.max(ans, i - anchor + 1);
anchor = i;
}
}

return ans;
}
}


Solution (11ms)

class Solution {
public int maxTurbulenceSize(int[] A) {
if (A.length == 1)
return 1;
int[] o = new int[A.length-1];
for (int i = 0; i < A.length - 1; ++i) {
if (A[i + 1] - A[i] > 0) {
o[i]=1;
} else if (A[i + 1] - A[i] < 0) {
o[i]=-1;
} else {
o[i]=0;
}
}
int count=0;
int maxCount=0;
for(int i=0;i<o.length-1;++i)
{
if(o[i]*o[i+1]==-1)
{
count++;
if(maxCount<count)
maxCount=count;
}else{
count=0;
}
}
return maxCount+2;
}
}