[Swift]LeetCode1151. 最少交换次数来组合全部的 1 | Minimum Swaps to Group All 1's Together

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:为敢(WeiGanTechnologies)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-mxdgxvpe-kq.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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. git

Example 1:github

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:ui

  1. 1 <= data.length <= 10^5
  2. 0 <= data[i] <= 1

给出一个二进制数组 data,你须要经过交换位置,将数组中 任何位置 上的 1 组合到一块儿,并返回全部可能中所需 最少的交换次数。spa

示例 1:code

输入:[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:htm

输入:[0,0,0,1,0]
输出:0
解释: 
因为数组中只有一个 1,因此不须要交换。

示例 3:blog

输入:[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 }
相关文章
相关标签/搜索