1151. Minimum Swaps to Group All 1‘s Together
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: data = [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: data = [0,0,0,1,0] Output: 0 Explanation: Since there is only one 1 in the array, no swaps are needed.
Example 3:
Input: data = [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].
Constraints:
1 <= data.length <= 105
data[i]
is either0
or1
.
class Solution:
def minSwaps(self, data: List[int]) -> int:
w=sum(data)
n=len(data)
tsum=sum(data[:w])
ans=w-tsum
for i in range(w,n):
tsum=tsum+data[i]-data[i-w]
ans=min(ans,w-tsum)
return ans
这个题的意思是,最后我们会有一个window size是1的个数,然后需要每个每个window的位置
------------------------
2134. Minimum Swaps to Group All 1's Together II
# class Solution:
# def minSwaps(self, nums: List[int]) -> int:
class Solution:
def minSwaps(self, data: List[int]) -> int:
w=sum(data)
n=len(data)
tsum=sum(data[:w])
ans=w-tsum
for i in range(w,n+w):
tsum=tsum+data[i%n]-data[(i-w)%n]
ans=min(ans,w-tsum)
return ans