[Swift]LeetCode376. 擺動序列 | Wiggle Subsequence

原文地址:http://www.javashuo.com/article/p-vvmfzenv-dm.html html

A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.this

For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.spa

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.code

Example 1:htm

Input: [1,7,4,9,2,5]
Output: 6 Explanation: The entire sequence is a wiggle sequence.

Example 2:blog

Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7 Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].

Example 3:element

Input: [1,2,3,4,5,6,7,8,9]
Output: 2

Follow up:
Can you do it in O(n) time?rem


若是連續數字之間的差嚴格地在正數和負數之間交替,則數字序列稱爲擺動序列。第一個差(若是存在的話)多是正數或負數。少於兩個元素的序列也是擺動序列。get

例如, [1,7,4,9,2,5] 是一個擺動序列,由於差值 (6,-3,5,-7,3) 是正負交替出現的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是擺動序列,第一個序列是由於它的前兩個差值都是正數,第二個序列是由於它的最後一個差值爲零。input

給定一個整數序列,返回做爲擺動序列的最長子序列的長度。 經過從原始序列中刪除一些(也能夠不刪除)元素來得到子序列,剩下的元素保持其原始順序。

示例 1:

輸入: [1,7,4,9,2,5]
輸出: 6 
解釋: 整個序列均爲擺動序列。

示例 2:

輸入: [1,17,5,10,13,15,10,5,16,8]
輸出: 7
解釋: 這個序列包含幾個長度爲 7 擺動序列,其中一個可爲[1,17,10,13,10,16,8]。

示例 3:

輸入: [1,2,3,4,5,6,7,8,9]
輸出: 2

進階:
你可否用 O(n) 時間複雜度完成此題?


12ms 
 1 class Solution {
 2     func wiggleMaxLength(_ nums: [Int]) -> Int {
 3         if nums.isEmpty {return 0}
 4         var p:Int = 1
 5         var q:Int = 1
 6         var n:Int = nums.count
 7         for i in 1..<n
 8         {
 9             if nums[i] > nums[i - 1]
10             {
11                 p = q + 1
12             }
13             else if nums[i] < nums[i - 1]
14             {
15                 q = p + 1
16             }
17         }
18         return min(n, max(p, q))
19     }
20 }

40ms

 1 class Solution {
 2     func wiggleMaxLength(_ nums: [Int]) -> Int {
 3 
 4         guard nums.count > 0 else { return 0 }
 5         var n = nums.count
 6         var p = Array(repeating: 1, count: n)
 7         var q = Array(repeating: 1, count: n)
 8         for i in 1..<n {
 9             for j in 0..<i {
10                 if nums[i] < nums[j] { q[i] = max(q[i], p[j]+1)}
11                 else if nums[i] > nums[j] { p[i] = max(p[i], q[j]+1)}
12             }
13         }
14         return max(q.last!, p.last!)
15     }    
16 }  
相關文章
相關標籤/搜索