1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public int[] getSubarrayBeauty(int[] nums, int k, int x) { int n = nums.length; int[] res = new int[n - k + 1]; TreeMap<Integer, Integer> greater = new TreeMap<>(), smaller = new TreeMap<>(); for (int i = 0; i < n; ++i) { smaller.put(nums[i], smaller.getOrDefault(nums[i], 0) + 1); if (i >= x) { int curMax = smaller.lastKey(); greater.put(curMax, greater.getOrDefault(curMax, 0) + 1); if (smaller.get(curMax) == 1) smaller.remove(curMax); else smaller.put(curMax, smaller.get(curMax) - 1); } if (i >= k) { int target = nums[i - k]; if (greater.containsKey(target)) { if (greater.get(target) == 1) greater.remove(target); else greater.put(target, greater.get(target) - 1); } else { if (smaller.get(target) == 1) smaller.remove(target); else smaller.put(target, smaller.get(target) - 1); int temp = greater.firstKey(); smaller.put(temp, smaller.getOrDefault(temp, 0) + 1); if (greater.get(temp) == 1) greater.remove(temp); else greater.put(temp, greater.get(temp) - 1); } } if (i >= k - 1) res[i - k + 1] = Math.min(0, smaller.lastKey()); } return res; } }
|