題目
給你兩個有序整數(shù)數(shù)組 nums1 和 nums2,請你將 nums2 合并到 nums1 中,使 nums1 成為一個有序數(shù)組。
說明:
初始化 nums1 和 nums2 的元素數(shù)量分別為 m 和 n 。
你可以假設(shè) nums1 有足夠的空間(空間大小大于或等于 m + n)來保存 nums2 中的元素
示例:
輸入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
輸出: [1,2,2,3,5,6]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-sorted-array
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
實現(xiàn)1
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] resultArray = new int[m + n];
int mIndex = 0;
int nIndex = 0;
int rIndex = 0;
while(mIndex < m && nIndex < n){
resultArray[rIndex++] = nums1[mIndex] < nums2[nIndex] ? nums1[mIndex++] : nums2[nIndex++];
}
while(mIndex < m){
resultArray[rIndex++] = nums1[mIndex++];
}
while(nIndex < n){
resultArray[rIndex++] = nums2[nIndex++];
}
for(int i = 0; i < resultArray.length; i++){
nums1[i] = resultArray[i];
}
}
實現(xiàn)2
public void merge(int[] nums1, int m, int[] nums2, int n) {
int mums1Index = m - 1;
int nums2Index = n - 1;
int meageCurIndex = m + n - 1;
while (mums1Index >= 0 && nums2Index >= 0) {
int tempM = nums1[mums1Index];
int tempN = nums2[nums2Index];
if (tempN >= tempM) {
nums1[meageCurIndex] = tempN;
nums2Index--;
meageCurIndex--;
} else {
nums1[meageCurIndex] = tempM;
mums1Index--;
meageCurIndex--;
}
}
if (nums2Index >= 0) {
System.arraycopy(nums2, 0, nums1, 0, nums2Index + 1);
}
}