在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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. For example, 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. Example 1: Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.
Example 2: 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: Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up: 如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。 例如, 给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。 示例 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 进阶: 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 }
|
请发表评论