为有牺牲多壮志,敢教日月换新天。

[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 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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. 1 <= data.length <= 10^5
  2. 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. 1 <= data.length <= 10^5
  2. 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 }

 

posted @ 2019-08-11 08:51  为敢技术  阅读(927)  评论(0编辑  收藏  举报