当前位置:网站首页>力扣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;
}
}边栏推荐
- [autosar-rte] - 3-runnable and its task mapping mapping
- Promise实例如何解决地狱回调
- Promise learning notes
- canvas常用原型方法及绘制图片应用
- 19c sysaux tablespace sqlobj$plan table is too large. How to clean it up
- Send a message to the background when closing the page
- 【高数】高数平面立体几何
- Get started quickly with flask (I) understand the framework flask, project structure and development environment
- LeetCode_ 406_ Rebuild the queue based on height
- Magic Bracelet-【群论】【Burnside引理】【矩阵快速幂】
猜你喜欢

MQTT. JS introductory tutorial: learning notes

2022年危险化学品经营单位安全管理人员上岗证题目及答案

Bluetooth technology | the total scale of charging piles in Beijing will reach 700000 in 2025. Talk about the indissoluble relationship between Bluetooth and charging piles
![[C language] detailed explanation sequence table (seqlist)](/img/60/c8cee6a6afe57247aba583291cc99b.png)
[C language] detailed explanation sequence table (seqlist)

How promise instance solves hell callback

2022安全员-C证特种作业证考试题库及答案

Technology sharing | quick intercom integrated dispatching system

Promise learning notes

RGB-T追踪——【多模态融合】Visible-Thermal UAV Tracking: A Large-Scale Benchmark and New Baseline

IntelliJ idea associated database
随机推荐
1.5 merge\rebase\revert\stash\branch
JDBC connection database
Introduction to shardingsphere's concept of sub database and sub table (2)
Conditions and procedures of stock index futures account opening
OpenShift 4 - 使用 VerticalPodAutoscaler 优化应用资源 Request 和 Limit
Face warp - hand tear code
IT行业数据与应用关系的变迁
Magic Bracelet-【群论】【Burnside引理】【矩阵快速幂】
Hexadecimal representation of negative numbers
What is the difference between these two sets of code?
【AUTOSAR-RTE】-3-Runnable及其Task Mapping映射
《PyTorch深度学习实践》第九课多分类问题(手写数字MNIST)
Promise learning notes
Deconstruction assignment of ES6 variables
express搭建一个简易的本地后台(一)
19c sysaux tablespace sqlobj$plan table is too large. How to clean it up
IJCAI 2022 | 图结构学习最新综述:研究进展与未来展望
JDBC连接数据库
快速上手Flask(一) 认识框架Flask、项目结构、开发环境
[vscode] vscode usage
