LeetCode 88 Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]

思路:

通常想法是从nums1数组的前面开始判断,并插入,但是这样写出来的程序太过复杂,并且会出现超时的情况。

所以我们换一种思路,我们从nums1的后面开始插入。

从nums2的尾开始给nums1的尾赋值。

只要nums2的值比nums[m-1]大就赋值到nums1中。

这里会出现一个问题,如果nums1是空的,那么nums1数组中就全是0;这样在nums2中有负数的情况下,就会出现问题,所以首先判断m是不是等于0;

下面是代码:

代码:

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i = n-1;
        int j = 0;
        if(m == 0){
            for(int k =0;k<n;k++)
                nums1[k] = nums2[k];
        }else{
           for(i ;i>=0;i--){
           if(nums1[m+i] == 0 && nums2[i]>nums1[m-1])
               nums1[m+i] = nums2[i];
            else{
               for(j=m-1; j>=0;j--){
                   
                       if(nums1[j]>nums2[i]){
                       nums1[j+1] = nums1[j];
                       }else{
                           nums1[j+1] = nums2[i];
                           m++;
                           break;
                       }
                       if(j==0 &&nums1[j]>nums2[i]){
                           nums1[j] = nums2[i];
                           m++;
                       }
                   }
                   
               }
            }
        }
    
    }
};

下面是另一种方法:

直接写代码吧:

class Solution {
public:
     void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i=0,j=0;
        int temp=m;
         while(i<temp&&j<n)
         {
              if(nums1[i]>nums2[j])
              {
                  nums1.insert(nums1.begin()+i,nums2[j]);
                  temp++;
                  j++;
               }
          i++;
         }
         while(j<n)
         {
          nums1.insert(nums1.begin()+i,nums2[j]);
          i++;
          j++;
         }
         i=m+n;

         while(i<nums1.size())
         {
            nums1.pop_back();
         }  
            
    }
};

猜你喜欢

转载自blog.csdn.net/yige__cxy/article/details/81591344