數組-88. 合併兩個有序數組(20200524)

題目描述

給你兩個有序整數數組 nums1 和 nums2,請你將 nums2 合併到 nums1 中,使 nums1 成爲一個有序數組。

說明:

初始化 nums1 和 nums2 的元素數量分別爲 m 和 n 。
你可以假設 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]

題目思路

本題目中指出兩個數組爲「有序整數數組」,可以利用這個特性,對兩個數組進行「歸併排序」。由於需要修改nums1數組,將num2數組合並至nums1數組中;所以可以由nums1數組複製一個新的nums數組,歸併排序複製數組nums和nums2,將結果放在nums1數組中。

參考代碼

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int[] nums = new int[m];
        System.arraycopy(nums1, 0, nums, 0, m);
        int index1 = 0;
        int index2 = 0;
        int index = 0;

        while (index1 < m && index2 < n) {
            if (nums[index1] >= nums2[index2]) {
                nums1[index] = nums2[index2];
                index2++;
            } else {
                nums1[index] = nums[index1];
                index1++;
            }
            index++;
        }
        if (index1 < m) {
            System.arraycopy(nums, index1, nums1, index1+index2, m + n - index1-index2);
        }
        if (index2 < n) {
            System.arraycopy(nums2, index2, nums1, index1+index2, m + n - index1-index2);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章