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

Merge Sorted Array

时间:2015-07-01 17:35:57      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

题目

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

 

思路

题意要把两个有序的数组合并到他们中的一个数组中。

唯一的技巧就是从结尾开始归并,不会覆盖元素又能满足题意。

 

code

public class Solution {
    public void merge(int A[], int m, int B[], int n) 
    {
        while(m > 0 && n > 0)
        {
            if(A[m-1] > B[n-1])
            {
                A[m+n-1] = A[m-1];
                m--;
            }
            else
            {
                A[m+n-1] = B[n-1];
                n--;
            }
        }
 
        while(n > 0)
        {
            A[m+n-1] = B[n-1];
            n--;
        }
        
        while(m > 0)
        {
            A[m+n-1] = A[m-1];
            m--;
        }
        
    }
}

 

Merge Sorted Array

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4613429.html

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