publicstaticvoidmerge(int[] nums1, int m, int[] nums2, int n) { if (nums2 == null || nums2.length <= 0) { return; }
int[] num = newint[m + n]; intidx1=0; intidx2=0; intidx=0; while (idx < m + n) { if (idx1 < m && idx2 < n && nums1[idx1] <= nums2[idx2]) { num[idx++] = nums1[idx1++]; } elseif (idx1 < m && idx2 < n && nums1[idx1] > nums2[idx2]) { num[idx++] = nums2[idx2++]; } elseif (idx1 == m && idx2 < n) { num[idx++] = nums2[idx2++]; } elseif (idx2 == n && idx1 < m) { num[idx++] = nums1[idx1++]; } }
for (inti=0; i < m + n; i++) { nums1[i] = num[i]; } }
Analysis
Time Complexity: .
Space Complexity: .
Reverse Two Pointers
Since the extra space of is in the back, it’s better to process the sorted data from the back to the front, fill in the values while traversing the array.
Let two pointers and to point to the tails of and , traversal from the tail and compare the values, and set the pointer to point to the end of . After each traversal of the size of the comparison value, it will be filled.
When , the traversal ends. If the data of is not copied completely, we can copy the rest to the front of , and finally we got the answer.
预览: