leetcode 88. Merge Sorted Array

来源:互联网 发布:周朝放弃关中 知乎 编辑:程序博客网 时间:2024/06/10 06:17

88. Merge Sorted Array

Description

Given two sorted integer arrays nums1 andnums2, 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.

思路:数组一足够包含m+n个数,为了时间的效率,不能涉及到大量的移动,从前向后的话,会超时。反过来,我们从后向前。这种方法也适用于字符数组合并

void merge(int* nums1, int m, int* nums2, int n) {    int i = m - 1, j = n - 1, k = 0;    int newIndex = m + n - 1;    while(i >= 0 && j >= 0){//找最大的,反向进行        if(nums1[i] > nums2[j])         {            nums1[newIndex--] = nums1[i];            --i;        }else{            nums1[newIndex--] = nums2[j];            --j;        }     }    while(m != 0 && i >= 0)//m!=0成功解决[0]/0、[1]/1    {        nums1[newIndex--] = nums1[i--];    }    while(j >= 0)    {        nums1[newIndex--] = nums2[j--];    }}


0 0
原创粉丝点击