栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 第 31 课 1054. 距离相等的条形码 560. 和为 K 的子数组

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 第 31 课 1054. 距离相等的条形码 560. 和为 K 的子数组

第 31 课
  • [1054. 距离相等的条形码](https://leetcode-cn.com/problems/distant-barcodes/)
  • [560. 和为 K 的子数组](https://leetcode-cn.com/submissions/detail/305506050/)

1054. 距离相等的条形码
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 map = new HashMap<>();
        for (int b : barcodes) {
            map.put(b, map.getOrDefault(b, 0) + 1);
        }
        PriorityQueue 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;
    }
}
560. 和为 K 的子数组
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 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;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/837631.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号