Link: https://leetcode.com/problems/count-complete-subarrays-in-an-array/description/ ## 思路 sliding window 计算window里有多少个distinct number 如果数目等于```nums```里面的distinct number数 说明现在window里就是一个complete subarray 那么以左指针为起点 右指针和右指针后面的每一个index为终点的subarray都是complete subarray 因此```ans += len(nums)-r``` 接着移动左指针 也可以用brute force 最坏情况下的时间复杂度是一样的 ## Code ```python= class Solution: def countCompleteSubarrays(self, nums: List[int]) -> int: distinctInWhole = len(set(nums)) currDistinct = 0 count = collections.defaultdict(int) l, r = 0, 0 ans = 0 while r<len(nums): if count[nums[r]] == 0: currDistinct += 1 count[nums[r]] += 1 while l<=r and currDistinct==distinctInWhole: ans += len(nums)-r count[nums[l]] -= 1 if count[nums[l]] == 0: currDistinct -= 1 l += 1 r += 1 return ans ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up