LeetCode (88) merge two ordered arrays

(88) merge two ordered arrays

Description:

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

Description:

  • Initialization nums1 and nums2 number of elements respectively m and n- .
  • You can assume nums1 sufficient space (space greater than or equal to m + n- ) to hold nums2 elements.

Example:

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

输出: [1,2,2,3,5,6]

Ideas:

What ideas do not need, that is, merge easiest merge sort. The only consideration is how to complete the operation without increasing the complexity of the case space.

After reference to someone else's code and found that the operation can be completed without the application of the new array. As long as the last place elements from the start nums1 array.

Code:

  1. c language version: open int array 1000.
//8ms
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
    int temp[1000];
    int i=0, j=0, k=0;
    while(i<m&&j<n)
    {
        if(nums1[i]<nums2[j])temp[k++]=nums1[i++];
        else temp[k++]=nums2[j++];
    }
    while(i<m)temp[k++]=nums1[i++];
    while(j<n)temp[k++]=nums2[j++];
    for(int i=0;i<m+n;i++)
    {
        nums1[i]=temp[i];
    }
}
  1. C (modified version): the element is placed at the end nums1
//4ms
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
    int i=m-1, j=n-1, k=m+n-1;
    while(i>=0&&j>=0)
    {
        if(nums1[i]>nums2[j])nums1[k--]=nums1[i--];
        else nums1[k--]=nums2[j--];
    }
    while(j>=0)nums1[k--]=nums2[j--];
}
Released six original articles · won praise 1 · views 38

Guess you like

Origin blog.csdn.net/LordTech/article/details/104283470