题解:
public class MergeSortedArray {
/**
* 逆向思维:我们从大到小选数,从小到大选数会操作会比较麻烦
* 只需要将nums2填充到nums1即可
* @param nums1
* @param m
* @param nums2
* @param n
*/
public void merge(int[] nums1, int m, int[] nums2, int n) {
int nums1Index = m-1, nums2Index = n-1, tag = m+n-1;
// 从nums1的最后一个元素开始填充最大值开始
while (nums1Index >= 0 && nums2Index >= 0) {
if (nums1[nums1Index] >= nums2[nums2Index]) {
nums1[tag] = nums1[nums1Index];
tag--;
nums1Index--;
} else {
nums1[tag] = nums2[nums2Index];
tag--;
nums2Index--;
}
}
while (nums2Index >= 0) {
nums1[tag] = nums2[nums2Index];
tag--;
nums2Index--;
}
}
}