herrDeng網內搜尋

自訂搜尋

Ads

2024年8月2日 星期五

Python C++ sliding windows解Leetcode 2134 Minimum Swaps to Group All 1'...


Python C++  sliding windows解Leetcode 2134  Minimum Swaps to Group All 1's Together II
使用sliding window, 由於陣列是循環的,所以右邊的游標r應該一直走到n+n0或n+n1
[Python  code請進]
-----
Use sliding window. Since the array is circular, the right point r should go to til n+n0 or n+n1
class Solution:
    def minSwaps(self, nums: List[int]) -> int:
        n=len(nums)
        n1=sum(nums)
        n0=n-n1
        mswap=cnt1=sum(nums[0:n0])
        for l in range(n):
            r=l+n0
            cnt1+=nums[r%n]-nums[l]
            mswap=min(mswap, cnt1)
        return mswap
        

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章