[Leetcode]-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.

Hide Tags: Array。 Two Pointers

题目:合并两个已排好序的数组。要求合并后相同保持排好序
思路:採用两个指针分别从两个数组开头向后移。而且比較。提前须要分配一个能存下两个数组的暂时数组。

void merge(int* nums1, int m, int* nums2, int n) {

    int lpos = 0, rpos = 0, tmpos = 0;
    int* tem = (int*)malloc(sizeof(int)*(m+n));

    while(lpos < m && rpos < n)
    {
        if(nums1[lpos] < nums2[rpos])
            tem[tmpos++] = nums1[lpos++];
        else
            tem[tmpos++] = nums2[rpos++];
    }
    while(lpos < m)
    {
         tem[tmpos++] = nums1[lpos++];
    } 
    while(rpos < n)
    {
         tem[tmpos++] = nums2[rpos++];
    }

    int i = 0;
    for(i=0;i<m+n;i++)
    {
        nums1[i] = tem[i];
    }
    free(tem);
}

posted on 2017-06-15 11:07  yjbjingcha  阅读(106)  评论(0编辑  收藏  举报

导航