题目链接:https://leetcode.com/problems/merge-sorted-array/
题目:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
The number of elements initialized in nums1 and nums2 are m and n respectively.
解题思路:
这题是有序数组的归并。技巧在于,归并时从后往前归并。
若从前往后,就需要挪动 nums1 中原有的元素。也不需要额外的空间暂存排好序的元素。
代码实现:
public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if(nums1 == null || nums1.length == 0) {
if(nums2 != null && nums2.length > 0) {
Arrays.fill(nums1, 0);
for(int i = 0; i < n; i ++)
nums1[i] = nums2[i];
}
return;
}
if(nums2 == null || nums2.length == 0) {
if(nums1 != null && nums1.length > 0)
return;
}
int i = m + n - 1;
int j = m - 1;
int k = n - 1;
while(j >= 0 && k >= 0) {
if(nums1[j] > nums2[k])
nums1[i --] = nums1[j --];
else if(nums1[j] < nums2[k])
nums1[i --] = nums2[k --];
else {
nums1[i --] = nums1[j --];
nums1[i --] = nums2[k --];
}
}
while(j >= 0)
nums1[i --] = nums1[j --];
while(k >= 0)
nums1[i --] = nums2[k --];
return;
}
}
59 / 59 test cases passed.
Status: Accepted
Runtime: 0 ms