问题描述

1144. 递减元素使数组呈锯齿状 (Medium)

给你一个整数数组 nums,每次 操作 会从中选择一个元素并 将该元素的值减少 1

如果符合下列情况之一,则数组 A 就是 锯齿数组

  • 每个偶数索引对应的元素都大于相邻的元素,即 A[0] > A[1] < A[2] > A[3] < A[4] > ...
  • 或者,每个奇数索引对应的元素都大于相邻的元素,即 A[0] < A[1] > A[2] < A[3] > A[4] < ...

返回将数组 nums 转换为锯齿数组所需的最小操作次数。

示例 1:

输入:nums = [1,2,3]
输出:2
解释:我们可以把 2 递减到 0,或把 3 递减到 1。

示例 2:

输入:nums = [9,6,1,6,2]
输出:4

提示:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000

解题思路

首先要注意本题只允许递减数字,只需要考虑分别考虑偶数索引满足情况和奇数索引满足情况的情况,模拟即可。

代码

class Solution {
public:
int movesToMakeZigzag(vector<int> &nums) {
if (nums.size() == 1)
return 0;
// 考虑偶数索引大的情况
int cnt2 = 0;
for (int i = 1; i < nums.size(); i += 2) {
if (i + 1 < nums.size() && i - 1 >= 0) {
int tmp = std::min(nums[i + 1], nums[i - 1]);
if (tmp <= nums[i]) {
cnt2 += nums[i] - tmp + 1;
}
} else if (i + 1 >= nums.size()) {
if (nums[i - 1] <= nums[i]) {
cnt2 += nums[i] - nums[i - 1] + 1;
}
} else {
if (nums[i + 1] <= nums[i]) {
cnt2 += nums[i] - nums[i + 1] + 1;
}
}
}
// 考虑奇数索引大的情况
int cnt4 = 0;
for (int i = 0; i < nums.size(); i += 2) {
if (i + 1 < nums.size() && i - 1 >= 0) {
int tmp = std::min(nums[i + 1], nums[i - 1]);
if (tmp <= nums[i]) {
cnt4 += nums[i] - tmp + 1;
}
} else if (i + 1 >= nums.size()) {
if (nums[i - 1] <= nums[i]) {
cnt4 += nums[i] - nums[i - 1] + 1;
}
} else {
if (nums[i + 1] <= nums[i]) {
cnt4 += nums[i] - nums[i + 1] + 1;
}
}
}
return std::min(cnt2, cnt4);
}
};

最新文章

  1. dbms_output.put_line 不显示
  2. 经验分享:CSS浮动(float,clear)通俗讲解
  3. nyoj138 找球号(二)_离散化
  4. flask中&#39;bool&#39; object has no attribute &#39;__call__&#39;问题
  5. 运维工作中常用到的几个rsync同步命令
  6. 不借助jquery封装好的ajax,你能用js手写ajax框架吗
  7. CCOrbitCamera卡牌翻转效果
  8. C#变量初始化问题:字段初始值无法引用非静态字段、方法或属性
  9. Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)的解决方法
  10. 微信支付错误两个问题的解决:curl出错,错误码:60
  11. TCP/IP笔记(五)IP协议相关技术
  12. bashrc和bash_profile
  13. Java synchronized 线程同步
  14. 清理XFCE4卸载残留
  15. centos安装VirtualBox增强包VBoxGuestAdditions
  16. jquery 动画总结(主要指效果函数)
  17. OWASP TOP 10 2017中文译文
  18. shell脚本案例分享 - 业务系统日志自定义保留或删除需求
  19. Xamarin.Forms.Xaml.XamlParseException: MarkupExtension not found for trans:Translate using a PCL in Release Mode
  20. 在liferay中如何使用Ajax的请求

热门文章

  1. go on
  2. seqsever 查询多个表的条数,并以列的形式展现
  3. apk文件查看指纹证书方法
  4. Ubuntu系统添加新的普通用户
  5. HTTP头注入:XFF注入
  6. JAVA图片压缩到指定大小
  7. 2022-6,flask+vue+uwsgi+nginx,线上部署完整流程打包配置文件
  8. PostgreSQL权限管理
  9. springboot Elasticsearch 实体创建索引设置Date 类型字段失败
  10. 下载接口时出现:Try to run this command from the system terminal. Make sure that you use the correct version of &#39;pip&#39; installed for your Python interpreter located at &#39;D:\python\demo\venv\Scripts\...的错误