88 Merge Sorted Array

1. Question

Given two sorted integer arraysnums1andnums2, mergenums2intonums1as one sorted array.
Note: You may assume thatnums1has enough space (size that is greater or equal tom+n) to hold additional elements fromnums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

2. Implementation

(1) Two Pointers
1
public class Solution {
2
public void merge(int[] nums1, int m, int[] nums2, int n) {
3
int index1 = m - 1, index2 = n - 1;
4
int k = m + n - 1;
5
6
while (index1 >= 0 && index2 >= 0) {
7
nums1[k--] = nums1[index1] > nums2[index2] ? nums1[index1--] : nums2[index2--];
8
}
9
10
while (index2 >= 0) {
11
nums1[k--] = nums2[index2--];
12
}
13
}
14
}
Copied!

3. Time & Space Complexity

时间复杂度O(m + n), m为nums1的长度,n为nums2的长度,空间复杂度O(1)