问题
2653. Sliding Subarray Beauty个
给定一个包含
n
个整数的整数数组nums
,就会发现 每个子数组的大小为k
.子数组的优点是子数组中的
xth
个最小整数 如果为负数,则为0;如果小于x
个负整数,则为0.返回一个包含
n - k + 1
个整数的整数数组,表示 中第一个索引的顺序排列的子数组的美感 array.
代码
class Solution(object):
def getSubarrayBeauty(self, nums, k, x):
"""
:type nums: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
eleToFreq = {m: 0 for m in range(-50, 0)}
i = j = 0
toReturn = list()
while j < len(nums):
if j >= k - 1:
if nums[j] < 0:
eleToFreq[nums[j]] += 1
a = 0
for key, value in eleToFreq.items():
if value > 0 and a == x - 1:
toReturn.append(key)
a += 1
elif value > 0:
a += value
if a < x :
toReturn.append(0)
if nums[i] < 0:
eleToFreq[nums[i]] -= 1
i += 1
j += 1
else:
if nums[j] < 0:
eleToFreq[nums[j]] += 1
j += 1
return toReturn
solution = Solution()
v = solution.getSubarrayBeauty([1, -1, -3, -2, 3], 3, 2) # expected output [-1,-2,-2]
print(v)
v = solution.getSubarrayBeauty([-1, -2, -3, -4, -5], 2, 2) # expected output [-1,-2,-3,-4]
print(v)
v = solution.getSubarrayBeauty([-3, 1, 2, -3, 0, -3], 2, 1) # expected output [-3,0,-3,-3,-3]
print(v)
v = solution.getSubarrayBeauty([1,-1,-3,-2,3], 3, 2) # expected output [-1,-2,-2]
print(v)
v = solution.getSubarrayBeauty([-43], 1, 1) # expected output [-43]
print(v)
发行
这些情况在IDE中有效,但在Leetcode中无效.我在Intellij中得到了所有预期的答案,但在以下情况下,相同的代码在leetcode中给了我错误的答案
nums=[1,-1,-3,-2,3] k=3 x=2 expected output: [-1,-2,-2] actual output [-3,-3,-2]
nums=[-1,-2,-3,-4,-5] k=2 x=2 expected output: [-1,-2,-3,-4] actual output [-2,-2,-3,-4]