Skip to content

2570. Merge Two 2D Arrays by Summing Values 👍

  • Time: $O(|\texttt{nums1}| + |\texttt{nums2}|)$
  • Space: $O(1000) = O(1)$
 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
class Solution {
 public:
  vector<vector<int>> mergeArrays(vector<vector<int>>& nums1,
                                  vector<vector<int>>& nums2) {
    constexpr int kMax = 1000;
    vector<vector<int>> ans;
    vector<int> count(kMax + 1);

    addCount(nums1, count);
    addCount(nums2, count);

    for (int i = 1; i <= kMax; ++i)
      if (count[i] > 0)
        ans.push_back({i, count[i]});

    return ans;
  }

 private:
  void addCount(const vector<vector<int>>& nums, vector<int>& count) {
    for (const vector<int>& idAndVal : nums) {
      const int id = idAndVal[0];
      const int val = idAndVal[1];
      count[id] += val;
    }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int[][] mergeArrays(int[][] nums1, int[][] nums2) {
    final int kMax = 1000;
    List<int[]> ans = new ArrayList<>();
    int[] count = new int[kMax + 1];

    addCount(nums1, count);
    addCount(nums2, count);

    for (int i = 1; i <= kMax; ++i)
      if (count[i] > 0)
        ans.add(new int[] {i, count[i]});

    return ans.stream().toArray(int[][] ::new);
  }

  private void addCount(int[][] nums, int[] count) {
    for (int[] idAndVal : nums) {
      final int id = idAndVal[0];
      final int val = idAndVal[1];
      count[id] += val;
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:
    count = [0] * (1001)
    self._addCount(nums1, count)
    self._addCount(nums2, count)
    return [[i, c] for i, c in enumerate(count) if c > 0]

  def _addCount(self, nums: List[List[int]], count: List[int]) -> None:
    for id_, val in nums:
      count[id_] += val