leetcode-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 and nums2 are m and n respectively.

解题思路

为节省空间,将nums2数组合并到nums1数组中,从nums1数组的最高位即 m+n位依次向下添加元素。


java代码:

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int len1 = m - 1,
            len2 = n - 1,
            lenTotal = m + n -1;

         while(len1 >= 0 && len2 >= 0) {
             if(nums1[len1] >= nums2[len2]) {
                 nums1[lenTotal--] = nums1[len1--];
             } else {
                 nums1[lenTotal--] = nums2[len2--];
             }
         }
        //  就是nums2还有剩余的元素
         if(len1 == -1) {
             while(len2 >= 0) {
                 nums1[lenTotal--] = nums2[len2--];
             }
         }
    }
}

原题地址

你可能感兴趣的:(leetcode)