题目: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, [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.
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
题解:
方法一:动态规划
定义两个变量,up,down分别表示当前元素以前的最长以上升结尾,以下降结尾的子序列的最长长度,对于当前元素,和前一个元素的位置关系只有三种情况:
1.当前元素比之前的元素大,表示当前是上升的,那么就应该找一个最长的以下降结尾的子序列,更新up变量
2.当前元素比之前的元素小,表示当前是下降的,那么就应该找一个最长的以上升结尾的子序列,更新down变量
3.当前元素和之前的元素相等,那么down,up应该保持不变
C++代码:
int wiggleMaxLength(vector& nums) {
if(nums.size()<2) return nums.size();
int up=1,down=1;
for(int i=1;i<nums.size();i++)
if(nums[i]<nums[i-1]) down=up+1;
else if(nums[i]>nums[i-1]) up=down+1;
return max(up,down);
}
python 代码:
def wiggleMaxLength(self, nums):
“”"
:type nums: List[int]
:rtype: int
“”"
if len(nums)<2:return len(nums)
down,up,n=1,1,len(nums)
for i in xrange(1,n):
if nums[i]>nums[i-1]:
up=down+1
elif nums[i]<nums[i-1]:
down=up+1
return max(down,up)
**方法二:贪心算法**:
其实找最长的摆动数列,其实就是找连续的极值点的数目
C++代码:
int wiggleMaxLength(vector& nums) {
if(nums.size()<2) return nums.size();
int prediff=nums[1]-nums[0];
int ans=prediff!=0?2:1;
for(int i=2;i<nums.size();i++)
{
int diff=nums[i]-nums[i-1];
if((diff>0&&prediff<=0)||(diff<0&&prediff>=0))
{
ans++;
prediff=diff;
}
}
return ans;
}
python 代码:
def wiggleMaxLength(self, nums: ‘List[int]’) -> ‘int’:
if len(nums)<2:return len(nums)
prediff=nums[1]-nums[0]
ans=2 if prediff else 1
for i in range(2,len(nums)):
diff=nums[i]-nums[i-1]
if (diff>0 and prediff<=0) or (diff<0 and prediff>=0):
ans,prediff=ans+1,diff
return ans