Merge Sorted Array(easy)

来源:互联网 发布:org.apache.cxf maven 编辑:程序博客网 时间:2024/06/06 10:56

题目

  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 tom + n) to hold additional elements   from nums2. The number of elements initialized innums1 and nums2 are m and n respectively.

题意

  两个有序数组,合并成一个有序数组,假设第一个数组空间足够容纳两个数组。

分析

   考虑到num1数组很大,可以直接在num1数组上进行合并,但是要讲究效率。
   如果单纯从前往后合并,那么效率会非常低,因为a数组后面的数字需要不停的移动。

   换一种思路,我们采用从后往前合并,首先计算出总长度,设置一个指针从num1数组最后往前移动。

题目

public class Solution {    public void merge(int A[], int m, int B[], int n) {        // Start typing your Java solution below        // DO NOT write main() function        //input check                 int i=m-1;        int j=n-1;        int k=m+n-1;                while(i>=0 && j>=0) {            A[k--] = A[i] > B[j] ? A[i--] : B[j--];         }                while(j>=0) {            A[k--] = B[j--];        }    }}


0 0
原创粉丝点击