Leetcode88. 合併兩個有序數組

 使用雙指針,從後往前插數據,用使用Index記錄當前數組的位置

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
    //    System.arraycopy(nums2, 0, nums1, m, n);
    //     Arrays.sort(nums1);
    // 太慢了
    //從後面開始檢索
        int m1 = m -1;
        int n1 = n -1;
        int index = 1;
        if(m == 0)
            System.arraycopy(nums2, 0, nums1, m, n);
        while(m1 >= 0 && n1 >= 0){
            if(nums1[m1] > nums2[n1]){
                nums1[m+n-index] = nums1[m1];
                m1--;
                index++;
            }else{
                nums1[m+n-index] = nums2[n1];
                n1--;
                index++;
            }
        }
        while(n1 >= 0){
            nums1[m+n - index] = nums2[n1--];
            index++;
        }

    
    }
}

 

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