一、题目
二、代码
class Solution
{
//子序列是可以删除的
//只需要保留峰值就可以了
public int wiggleMaxLength(int[] nums)
{
if(nums.length==1 ) return 1;
int length = nums.length;
int i;
//第一次作差不为0 加一
int last_symbol = -(nums[1]-nums[0]);
int symbol=0;
int temp_length = 1;
int last_num = nums[0];
for(i=1;i<length;i++)
{
symbol = nums[i]-nums[i-1];
System.out.println(" last_symbol " + last_symbol);
System.out.println(" symbol " + symbol);
//symbol大于0小于0都要计数
if((last_symbol<=0&&symbol>0)||(last_symbol>=0&&symbol<0))
{
temp_length++;
//摆动时更新
last_symbol = symbol;
}
System.out.println(" temp_length " + temp_length);
}
return temp_length;
}
}
三、运行结果
四、附录
二刷
class Solution
{
//寻找局部峰值
public int wiggleMaxLength(int[] nums)
{
if(nums.length < 2 ) return nums.length;
int res = 2;
int i;
int length=nums.length;
int direction = 2;
int another = 1;
while(another<length&&nums[another] == nums[0]) another++;
if(another==length) return 1;
int min = Math.min(nums[0],nums[another]);
int max = Math.max(nums[0],nums[another]);
if(nums[0]<nums[another]) direction = 1;
for(i=another+1;i<=length-1;i++)
{
//1是凸起
if(direction==1)
{
if(nums[i]>max) max = nums[i];
else if(nums[i]<max)
{
//System.out.println("1 "+nums[i]);
res++;
min = nums[i];
direction=2;
}
}
//2是凹陷
else if(direction==2)
{
if(nums[i]<min) min = nums[i];
else if(nums[i]>min)
{
//System.out.println("2 "+nums[i]);
res++;
max = nums[i];
direction=1;
}
}
}
return res;
}
}