A subarray A[i], A[i+1], …, A[j] of A is said to be turbulent if and only if:
Return the length of a maximum size turbulent subarray of A.
Example 1:
Input: [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])
Example 2:
Input: [4,8,12,16]
Output: 2
Example 3:
Input: [100]
Output: 1
Note:
题目的意思是:这道题要求我们找出最长的震荡子序列,我想过要暴力破解啥的,当我写完了之后我就感觉完了,要分两种情况来做,还是双循环,肯定会超时。看了一下参考答案,可以用滑动窗口来做,把数组A标成1,0,-1的情况,然后用乘法就可以判断相邻两个数是否是一个大一个小,这样的话就不用分两种情况判断了,大概思路就是这样例如:
A = [9,4,2,10,7,8,8,1,9]
把它标注成:[1,1,-1,1,-1,0,-1,1]
满足条件的子数组:[1], [1,-1,1,-1], [0], [-1,1]
这样就只需要遍历一遍就行了
class Solution:
def compare(self,a,b):
if(a>b):
return 1
elif(a int:
N=len(A)
res=1
anchor=0
for i in range(1,N):
c=self.compare(A[i-1],A[i])
if(c==0):
anchor=i
elif(i==N-1 or c*self.compare(A[i],A[i+1])!=-1):
res=max(res,i-anchor+1)
anchor=i
return res
[LeetCode] Approach 1: Sliding Window