[Swift]LeetCode1151. 最少交换次数来组合所有的 1 | Minimum Swaps to Group All 1's Together
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(www.zengqiang.org)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11333857.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a binary array data
, return the minimum number of swaps required to group all 1
’s present in the array together in any place in the array.
Example 1:
Input: [1,0,1,0,1]
Output: 1
Explanation:
There are 3 ways to group all 1's together:
[1,1,1,0,0] using 1 swap.
[0,1,1,1,0] using 2 swaps.
[0,0,1,1,1] using 1 swap.
The minimum is 1.
Example 2:
Input: [0,0,0,1,0]
Output: 0
Explanation:
Since there is only one 1 in the array, no swaps needed.
Example 3:
Input: [1,0,1,0,1,0,0,1,1,0,1]
Output: 3
Explanation:
One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
Note:
1 <= data.length <= 10^5
0 <= data[i] <= 1
给出一个二进制数组 data
,你需要通过交换位置,将数组中 任何位置 上的 1 组合到一起,并返回所有可能中所需 最少的交换次数。
示例 1:
输入:[1,0,1,0,1] 输出:1 解释: 有三种可能的方法可以把所有的 1 组合在一起: [1,1,1,0,0],交换 1 次; [0,1,1,1,0],交换 2 次; [0,0,1,1,1],交换 1 次。 所以最少的交换次数为 1。
示例 2:
输入:[0,0,0,1,0] 输出:0 解释: 由于数组中只有一个 1,所以不需要交换。
示例 3:
输入:[1,0,1,0,1,0,0,1,1,0,1] 输出:3 解释: 交换 3 次,一种可行的只用 3 次交换的解决方案是 [0,0,0,0,0,1,1,1,1,1,1]。
提示:
1 <= data.length <= 10^5
0 <= data[i] <= 1
820 ms
1 class Solution { 2 func minSwaps(_ data: [Int]) -> Int { 3 let n:Int = data.count 4 var s:[Int] = [Int](repeating:0,count:n+1) 5 for i in 1...n 6 { 7 s[i] = s[i-1] + data[i-1] 8 } 9 var m:Int = s[n] 10 var ret:Int = n 11 for i in m...n 12 { 13 ret = min(ret, m-(s[i]-s[i-m])) 14 } 15 return ret 16 } 17 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了