func minSwaps(nums []int) int {
zero, one := 0, 0
for _, x := range nums {
if x == 0 {
zero ++
} else {
one ++
}
}
if zero == 0 || zero == len(nums) {
return 0
}
sum := 0
ans := 0x3f3f3f3f
for i, x := range nums {
sum += x
if i < zero - 1 {
continue
}
ans = min(ans, sum)
sum -= nums[i - zero + 1]
}
sum = 0
for i, x := range nums {
sum += x
if i < one - 1 {
continue
}
ans = min(ans, one - sum)
sum -= nums[i - one + 1]
}
return ans
}
另一种方法,取模运算
func minSwaps(nums []int) int {
zero, one := 0, 0
n := len(nums)
for _, x := range nums {
if x == 0 {
zero ++
} else {
one ++
}
}
if zero == 0 || zero == len(nums) {
return 0
}
sum := 0
ans := 0x3f3f3f3f
for i := 0; i < n + zero; i ++ {
sum += nums[i % n]
if i < zero - 1 {
continue
}
ans = min(ans, sum)
sum -= nums[(i - zero + 1) % n]
}
return ans
}