大佬教程收集整理的这篇文章主要介绍了[Swift]LeetCode1144. 递减元素使数组呈锯齿状 | Decrease Elements To Make Array Zigzag,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公众号:山青咏芝(shanqingyongzhi)
?博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
?GitHub地址:https://github.com/strengthen/LeetCode
?原文地址:https://www.cnblogs.com/strengthen/p/11297773.html
?如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
?原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given an array nums
of @R_675_8056@rs,a @H_119_16@move consists of choosing any element and decreasing it by 1.
An array A
is a zigzag array if either:
A[0] > A[1] < A[2] > A[3] < A[4] > ...
A[0] < A[1] > A[2] < A[3] > A[4] < ...
Return the minimum number of moves to transform the given array nums
into a zigzag array.
Example 1:
Input: nums = [1,2,3] Output: 2 Explanation: We can decrease 2 to 0 or 3 to 1.
Example 2:
Input: nums = [9,6,1,2] Output: 4
ConsTraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
给你一个整数数组 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,3] 输出:2 解释:我们可以把 2 递减到 0,或把 3 递减到 1。
示例 2:
输入:nums = [9,2] 输出:4
提示:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
1 class Solution { 2 func movesToMakeZigzag(_ nums: [Int]) -> Int { 3 var n:Int = nums.count 4 var j:Int = 0 5 var s:Int = 0 6 var t:Int = 0 7 for i in Stride(from:0,to:n,by:2) 8 { 9 j = 0 10 if i != 0 11 { 12 j = max(j,nums[i]-nums[i-1]+1) 13 } 14 if i + 1 < n 15 { 16 j = max(j,nums[i]-nums[i+1]+1) 17 } 18 s += j 19 } 20 for i in Stride(from:1,by:2) 21 { 22 j = 0 23 if i != 0 24 { 25 j = max(j,nums[i]-nums[i-1]+1) 26 } 27 if i + 1 < n 28 { 29 j = max(j,nums[i]-nums[i+1]+1) 30 } 31 t += j 32 } 33 return min(s,t) 34 } 35 }
以上是大佬教程为你收集整理的[Swift]LeetCode1144. 递减元素使数组呈锯齿状 | Decrease Elements To Make Array Zigzag全部内容,希望文章能够帮你解决[Swift]LeetCode1144. 递减元素使数组呈锯齿状 | Decrease Elements To Make Array Zigzag所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。