在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a binary 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: 输入:[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]。 提示:
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 }
|
请发表评论