88. Merge Sorted Array

五个月前写的了。我记得好像当时去东京的飞机上还重新写了一遍,真是naive。。这种题要在纸上模拟一下就容易很多。

    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = m-1 , j = n-1;
        int slot = m + n - 1;
        while(i >= 0 && j >= 0 ){
            if(nums1[i]>=nums2[j]){
                nums1[slot] = nums1[i];
                i--;
                slot--;
            }
            else{
                nums1[slot] = nums2[j];
                j--;
                slot--;
            }
        }
// if nums2 has some numbers that are smaller than nums1[0]
        if(j>=0){
            for(int k = 0 ; k <= j ; k ++){
                nums1[k] = nums2[k];
            }
        }
    }

你可能感兴趣的:(88. Merge Sorted Array)