★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:爲敢(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 <= data.length <= 10^5
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 <= 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 }