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
[codes on Leetcode]https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/solutions/5571822/sliding-window45ms-beats-9961/
[sliding window/2 pointer play list]https://www.youtube.com/watch?v=pi1XpQU_Yxo&list=PLYRlUBnWnd5KrCfs7qCFb-Bvn7dvnakFy
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
沒有留言:
張貼留言
HTML 編輯器