LeetCode----------------------合併兩個有序數組

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

說明:

初始化 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]

public void merge(int[] nums1, int m, int[] nums2, int n) {

        int i = nums1.length - 1;
        int a = m - 1 > -1 ? m - 1 : -1;
        int b = n - 1;
        while (b > -1 && i > -1) {
            if (a > -1 && nums1[a] > nums2[b]) {
                nums1[i] = nums1[a];
                nums1[a] = 0;
                a--;
                i--;
            } else {
                nums1[i] = nums2[b];
                b--;
                i--;
            }
        }
    }

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-sorted-array
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章