码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode]-Merge Sorted Array

时间:2015-07-06 12:21:02      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:leetcode   two-point   

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);
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[Leetcode]-Merge Sorted Array

标签:leetcode   two-point   

原文地址:http://blog.csdn.net/xiabodan/article/details/46771777

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!