LeetCode-in-Java

2570. Merge Two 2D Arrays by Summing Values

Easy

You are given two 2D integer arrays nums1 and nums2.

Each array contains unique ids and is sorted in ascending order by id.

Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:

Return the resulting array. The returned array must be sorted in ascending order by id.

Example 1:

Input: nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]

Output: [[1,6],[2,3],[3,2],[4,6]]

Explanation: The resulting array contains the following:

Example 2:

Input: nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]]

Output: [[1,3],[2,4],[3,6],[4,3],[5,5]]

Explanation: There are no common ids, so we just include each id with its value in the resulting list.

Constraints:

Solution

import java.util.Arrays;

public class Solution {
    public int[][] mergeArrays(int[][] nums1, int[][] nums2) {
        int n1 = nums1.length;
        int n2 = nums2.length;
        int[][] res = new int[n1 + n2][2];
        int i = 0;
        int j = 0;
        int idx = 0;
        while (i < n1 && j < n2) {
            if (nums1[i][0] == nums2[j][0]) {
                res[idx][0] = nums1[i][0];
                res[idx][1] = nums1[i][1] + nums2[j][1];
                i++;
                j++;
            } else if (nums1[i][0] < nums2[j][0]) {
                res[idx][0] = nums1[i][0];
                res[idx][1] = nums1[i][1];
                i++;
            } else {
                res[idx][0] = nums2[j][0];
                res[idx][1] = nums2[j][1];
                j++;
            }
            idx++;
        }
        while (i < n1) {
            res[idx][0] = nums1[i][0];
            res[idx][1] = nums1[i][1];
            i++;
            idx++;
        }
        while (j < n2) {
            res[idx][0] = nums2[j][0];
            res[idx][1] = nums2[j][1];
            j++;
            idx++;
        }

        return Arrays.copyOf(res, idx);
    }
}