Input: nums =[1,-1,-3,-2,3], k =3, x =2Output: [-1,-2,-2]Explanation: There are 3 subarrays with size k =3.The first subarray is[1,-1,-3] and the 2nd smallest negative integer is-1.The second subarray is[-1,-3,-2] and the 2nd smallest negative integer is-2.The third subarray is[-3,-2,3] and the 2nd smallest negative integer is-2.
Input: nums =[-1,-2,-3,-4,-5], k =2, x =2Output: [-1,-2,-3,-4]Explanation: There are 4 subarrays with size k =2.For [-1,-2], the 2nd smallest negative integer is-1.For [-2,-3], the 2nd smallest negative integer is-2.For [-3,-4], the 2nd smallest negative integer is-3.For [-4,-5], the 2nd smallest negative integer is-4.
Input: nums =[-3,1,2,-3,0,-3], k =2, x =1Output: [-3,0,-3,-3,-3]Explanation: There are 5 subarrays with size k =2**.**For [-3,1], the 1st smallest negative integer is-3.For [1,2], there is no negative integer so the beauty is0.For [2,-3], the 1st smallest negative integer is-3.For [-3,0], the 1st smallest negative integer is-3.For [0,-3], the 1st smallest negative integer is-3.
Since all numbers are in [-50, 50], we can use a fixed-size frequency array to count negatives in the window. For each window, find the x-th smallest negative by scanning the count array.
#include<vector>usingnamespace std;
classSolution {
public: vector<int> getSubarrayBeauty(vector<int>& nums, int k, int x) {
vector<int> res, cnt(101);
int n = nums.size();
for (int i =0; i < k-1; ++i) cnt[nums[i]+50]++;
for (int i = k-1; i < n; ++i) {
cnt[nums[i]+50]++;
int c =0, val =0;
for (int v =0; v <50; ++v) {
c += cnt[v];
if (c >= x) { val = v-50; break; }
}
if (c < x) val =0;
res.push_back(val);
cnt[nums[i-k+1]+50]--;
}
return res;
}
};
import java.util.*;
classSolution {
publicint[]getSubarrayBeauty(int[] nums, int k, int x) {
int n = nums.length;
int[] cnt =newint[101], res =newint[n-k+1];
for (int i = 0; i < k-1; ++i) cnt[nums[i]+50]++;
for (int i = k-1; i < n; ++i) {
cnt[nums[i]+50]++;
int c = 0, val = 0;
for (int v = 0; v < 50; ++v) {
c += cnt[v];
if (c >= x) { val = v-50; break; }
}
if (c < x) val = 0;
res[i-k+1]= val;
cnt[nums[i-k+1]+50]--;
}
return res;
}
}
classSolution:
defgetSubarrayBeauty(self, nums, k, x):
n = len(nums)
cnt = [0]*101 res = []
for i in range(k-1):
cnt[nums[i]+50] +=1for i in range(k-1, n):
cnt[nums[i]+50] +=1 c =0 val =0for v in range(0, 50):
c += cnt[v]
if c >= x:
val = v-50breakif c < x:
val =0 res.append(val)
cnt[nums[i-k+1]+50] -=1return res