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 nrespectively.
- 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 = 3nums2 = [2,5,6], n = 3Output: [1,2,2,3,5,6]
想法:新建一个vector,遍历,逐个比较,结果小的就放入vector中。
class Solution {public: void merge(vector & nums1, int m, vector & nums2, int n) { vector result; int i = 0; int j = 0; while( i < m && j < n ){ if(nums1[i] <= nums2[j]){ result.push_back(nums1[i]); i++; }else{ result.push_back(nums2[j]); j++; } } while(i < m){ result.push_back(nums1[i]); i++; } while(j < n){ result.push_back(nums2[j]); j++; } nums1 = result; }};