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 <= 1000items1[i].length == items2[i].length == 21 <= valuei, weighti <= 1000items1中每个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)

浙公网安备 33010602011771号