[leedcode 88] Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 andnums2 are m and n respectively.

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        //本题突破点:
        //从后往前遍历,哪个大就添加哪个(被添加的指针向前),
        //注意最后,当nums2不为空时,说明nums2剩下的数字比nums1小,需要把nums2的保存到nums1
        /*int i=m-1;
        int j=n-1;
        while(i>=0&&j>=0){
            if(nums1[i]>nums2[j]){
                nums1[i+j+1]=nums1[i];
                i--;
            }else{
                nums1[i+j+1]=nums2[j];
                j--;
            }
            
            
        }
        while(j>=0){
            nums1[i+j+1]=nums2[j--];
        }*/
        int res=m+n-1;
        m--;
        n--;
        while(m>=0&&n>=0){
           nums1[res--]= nums1[m]>nums2[n]?nums1[m--]:nums2[n--];
        }
        while(n>=0){
            nums1[res--]=nums2[n--];
        }
        
    }
}
原文地址:https://www.cnblogs.com/qiaomu/p/4650782.html