为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode978. 最长湍流子数组 | Longest Turbulent Subarray

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10294636.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:

  • For i <= k < jA[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
  • OR, for i <= k < jA[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.

That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.

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:

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

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

  • 若 i <= k < j,当 k 为奇数时, A[k] > A[k+1],且当 k 为偶数时,A[k] < A[k+1]
  • 或 若 i <= k < j,当 k 为偶数时,A[k] > A[k+1] ,且当 k 为奇数时, A[k] < A[k+1]

也就是说,如果比较符号在子数组中的每个相邻元素对之间翻转,则该子数组是湍流子数组。

返回 A 的最大湍流子数组的长度。 

示例 1:

输入:[9,4,2,10,7,8,8,1,9]
输出:5
解释:(A[1] > A[2] < A[3] > A[4] < A[5])

示例 2:

输入:[4,8,12,16]
输出:2

示例 3:

输入:[100]
输出:1 

提示:

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

676ms

 1 class Solution {
 2     func maxTurbulenceSize(_ A: [Int]) -> Int {
 3         var n:Int = A.count
 4         var dp:Int = 0
 5         var ret:Int = 1
 6         for i in 0..<(n - 1)
 7         {
 8             if A[i] < A[i+1]
 9             {
10                 if i > 0 && A[i-1] > A[i]
11                 {
12                     dp += 1
13                 }
14                 else
15                 {
16                     dp = 2
17                 }
18             }
19             else if A[i] > A[i+1]
20             {
21                 if i > 0 && A[i-1] < A[i]
22                 {
23                     dp += 1
24                 }
25                 else
26                 {
27                     dp = 2
28                 }
29             }
30             else
31             {
32                 dp = 1
33             }
34             ret = max(ret, dp)
35         }
36         return ret        
37     }
38 }

 

posted @ 2019-01-20 13:16  为敢技术  阅读(360)  评论(0编辑  收藏  举报