题目来源:https://leetcode.com/problems/merge-sorted-array/
题目难度:Easy
题目
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
1 2 3 4 5
| Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
|
解答1[Java]
思路
新建一个数组,然后把待合并的数组的元素依次填充到新数组中。
实现
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 28 29 30 31
| class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int[] result = new int[m + n]; int index = 0; int i = 0; int j = 0; while (i < m && j < n) { if (nums1[i] < nums2[j]) { result[index++] = nums1[i++]; } else { result[index++] = nums2[j++]; } }
if (i == m) { while (j < n) { result[index++] = nums2[j++]; } } if (j == n) { while (i < m) { result[index++] = nums1[i++]; } }
for (int k = 0; k < result.length; k++) { nums1[k] = result[k]; }
} }
|
复杂度分析
空间复杂度为 $O(m+n)$。
时间复杂度为 $O(m+n)$。
解答2[Java]
思路
既然数组1后边有多余的位置,就从后面开始填充,从后向前,原地合并。
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int i = m - 1; int j = n - 1; int k = m + n - 1; while (i >= 0 && j >= 0) { if (nums1[i] > nums2[j]) { nums1[k--] = nums1[i--]; } else { nums1[k--] = nums2[j--]; } } while (j >= 0) { nums1[k--] = nums2[j--]; } } }
|
复杂度分析