Easy
You are given two 2D integer arrays nums1
and nums2.
nums1[i] = [idi, vali]
indicate that the number with the id idi
has a value equal to vali
.nums2[i] = [idi, vali]
indicate that the number with the id idi
has a value equal to vali
.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:
0
.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:
1 <= nums1.length, nums2.length <= 200
nums1[i].length == nums2[j].length == 2
1 <= idi, vali <= 1000
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);
}
}