https://leetcode.com/problems/merge-sorted-array/

题目:

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.

 

思路:

利用好nums1后n个空闲的空间是关键。

AC代码:

 1 class Solution {
 2 public:
 3     void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
 4         int i1 = m - 1, i2 = n - 1, k = m + n - 1;
 5         while (i1>= 0 && i2>=0){
 6             if (nums1[i1] < nums2[i2])
 7             {
 8                 nums1[k--] = nums2[i2--];
 9             }
10             else{
11                 nums1[k--] = nums1[i1--];
12             }
13         }
14         while (i2 >= 0){
15             nums1[k--] = nums2[i2--];
16         }
17 
18         return;
19     }
20 };