2363. 合并相似的物品 【模拟】

题目

给你两个二维整数数组 items1 和 items2 ,表示两个物品集合。每个数组 items 有以下特质:

  • items[i] = [valuei, weighti] 其中 valuei 表示第 i 件物品的 价值 ,weighti 表示第 i 件物品的 重量 。
  • items 中每件物品的价值都是 唯一的 。

请你返回一个二维数组 ret,其中 ret[i] = [valuei, weighti], weighti 是所有价值为 valuei 物品的 重量之和 。

注意:ret 应该按价值 升序 排序后返回。

难度:简单

提示:

  • 1 <= items1.length, items2.length <= 1000
  • items1[i].length == items2[i].length == 2
  • 1 <= valuei, weighti <= 1000
  • items1 中每个 valuei 都是 唯一的 。
  • items2 中每个 valuei 都是 唯一的 。

题解

因为题目数据量不大且数据范围不大,所以用数组代替Map会更快。

class Solution {
    public static final int ARRAY_LENGTH = 1001;

    public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {
        List<List<Integer>> res = new LinkedList<>();
        int[] itemsInt = new int[ARRAY_LENGTH];
        for (int[] ints : items1) {
            itemsInt[ints[0]] += ints[1];
        }
        for (int[] ints : items2) {
            itemsInt[ints[0]] += ints[1];
        }
        for (int i = 1; i < itemsInt.length; i++) {
            if (itemsInt[i] != 0) {
                List<Integer> list = new LinkedList<>();
                list.add(i);
                list.add(itemsInt[i]);
                res.add(list);
            }
        }
        return res;
    }
}

复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(1)

最后编辑时间:2023年2月28日14:00:00

posted @ 2023-02-28 13:57  tothk  阅读(66)  评论(0)    收藏  举报