Leetcode (Java) -88. Merge two ordered arrays

Given two ordered arrays of integers and nums2 nums1, incorporated into the nums2 nums1 in an ordered array such as a num1.

Description:

And initializing the number of elements nums1 nums2 of m and n.
You can assume nums1 sufficient space (space equal to or greater than m + n) to save the elements of nums2.
Example:

Input:
nums1 = [1,2,3,0,0,0], m =. 3
nums2 = [2,5,6], n-=. 3

Output: [1,2,2,3,5,6]

 

1 idea: first merge reordering (obviously not out of the question's meaning)

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
            for(int i=0;i<n;i++)
            {
                nums1[m+i]=nums2[i];
            }
            Arrays.sort(nums1);
    }
}

2 ideas:

Here modify the requirements in place, in fact, as long as we can compare from back to front and from the back to insert.

We need three pointers:

  1. current record for that position to fill the current

  2. m nums1 for recording element array to which the process

  3. n nums2 for recording element array to which the process

as the picture shows:

  • Gray on behalf of num2 array element has been treated
  • Red for ongoing comparison element
  • Green represents the elements already in place

 

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int current=m+n-1;
        while(current>=0){
            if(n==0) return ;
            if(m==0){
                nums1[current--]=nums2[--n];
                continue;
            }
            if(nums1[m-1]>nums2[n-1]){
                nums1[current--]=nums1[--m];
            }
            else{
                 nums1[current--]=nums2[--n];
            }
        }
    }
}

 

Published 142 original articles · won praise 31 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_38905818/article/details/104069370