当前位置:网站首页>力扣376-摆动序列——贪心
力扣376-摆动序列——贪心
2022-07-28 09:00:00 【张怼怼√】
题目描述
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为 摆动序列 。第一个差(如果存在的话)可能是正数或负数。仅有一个元素或者含两个不等元素的序列也视作摆动序列。
例如, [1, 7, 4, 9, 2, 5] 是一个 摆动序列 ,因为差值 (6, -3, 5, -7, 3) 是正负交替出现的。
相反,[1, 4, 7, 2, 5] 和 [1, 7, 4, 5, 5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。
子序列 可以通过从原始序列中删除一些(也可以不删除)元素来获得,剩下的元素保持其原始顺序。
给你一个整数数组 nums ,返回 nums 中作为 摆动序列 的 最长子序列的长度 。
解题思路

- 这道题目的目的主要是找到波峰和波谷的个数;
- 建立两个变量 firstDiff 和 lastDiff 分别记录当前元素与前一个元素的差值(因此下标从1开始)以及前一个元素与之前面的元素的差值,lastDiff 是动态更新的;
- 结果保存在变量res中,nums[0] 作为起始节点,应该是算作一个节点的,所以res初始化为1;
- 遍历nums ,每次需要判断 firstDiff 和 lastDiff 的值是否是相反的,如果相反,res更新+1。
输入输出示例
代码
class Solution {
public int wiggleMaxLength(int[] nums) {
int len = nums.length;
//if(len==1 || len==2) return 1;
int res = 1;
int firstDiff = 0;
int lastDiff = 0;
for(int i = 1; i <= len - 1; i++){
firstDiff = nums[i] - nums[i-1];
if((firstDiff < 0 && lastDiff >= 0) ||(firstDiff > 0 && lastDiff <= 0)){
res++;
lastDiff = firstDiff;
}
}
return res;
}
}边栏推荐
- Activiti启报错: Cannot create PoolableConnectionFactory (Could not create connection to database server
- 21 day learning challenge - "AUTOSAR from introduction to mastery - practical part"
- [multithreading] non atomic agreement of long and double
- 2022安全员-C证特种作业证考试题库及答案
- oracle 创建用户且只有查询权限
- 树上启发式合并
- express搭建一个简易的本地后台(一)
- [gossip] the development of programmers needs two abilities most
- C signed and unsigned byte variables
- Title and answer of work permit for safety management personnel of hazardous chemical business units in 2022
猜你喜欢

Get started quickly with flask (I) understand the framework flask, project structure and development environment

对话MySQL之父:代码一次性完成才是优秀程序员

C simply call FMU for simulation calculation

js数组去重,id相同对某值相加合并

Activiti启报错: Cannot create PoolableConnectionFactory (Could not create connection to database server

ECCV 2022 | 无需微调即可推广!基于配准的少样本异常检测框架

golang升级到1.18.4版本 遇到的问题

QT基础练手小程序-简单计算器设计(附带源码,解析)

Oracle-11gR2默认的系统JOB

IP protocol of network layer
随机推荐
负数的十六进制表示
Regular expressions are hexadecimal digits?
CakePHP 4.4.3 release, PHP rapid development framework
数据库核心体系
Personal blog applet
7 C控制语句:分支和跳转
Leetcode 452. minimum number of arrows to burst balloons (medium)
股指期货开户的条件和流程
信息学奥赛一本通 1617:转圈游戏 | 1875:【13NOIP提高组】转圈游戏 | 洛谷 P1965 [NOIP2013 提高组] 转圈游戏
[autosar-rte] - 3-runnable and its task mapping mapping
Title and answer of work permit for safety management personnel of hazardous chemical business units in 2022
Activiti启报错: Cannot create PoolableConnectionFactory (Could not create connection to database server
IntelliJ IDEA 关联数据库
《数据库系统内 幕》分布式系统
Changes in the relationship between data and application in IT industry
ShardingSphere之分库分表概念介绍(二)
7 C control statements: branches and jumps
个人博客小程序
MQTT.js 入门教程:学习笔记
Introduction to shardingsphere's concept of sub database and sub table (2)
