class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
d, n = Counter(barcodes), len(barcodes)
ans = [0] * n
q = sorted(d.items(), key=lambda x:x[1])
i = 0
for k, v in reversed(q):
for _ in range(v):
ans[i] = k
i += 2
if i >= n: i = 1
return ans
class Solution {
public int[] rearrangeBarcodes(int[] barcodes) {
Map<Integer, Integer> map = new HashMap<>();
for (int b : barcodes) {
map.put(b, map.getOrDefault(b, 0) + 1);
}
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (b[1] - a[1]));
for (int k : map.keySet()) {
pq.add(new int[]{k, map.get(k)});
}
int[] res = new int[barcodes.length];
int i = 0;
while (!pq.isEmpty()) {
int[] temp = pq.poll();
while (temp[1] -- > 0) {
res[i] = temp[0];
i += 2;
if (i >= barcodes.length) i = 1;
}
}
return res;
}
}
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
res, acc, d = 0, 0, {}
for x in nums:
d[acc] = d.get(acc, 0) + 1
acc += x
res += d.get(acc - k, 0)
return res
class Solution {
public int subarraySum(int[] nums, int k) {
int res = 0, acc = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++){
map.put(acc, map.getOrDefault(acc, 0) + 1);
acc += nums[i];
res += map.getOrDefault(acc - k, 0);
}
return res;
}
}
|