LeetCode OJ: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.
没什么难度,但是需要注意的一点就是可能会出现 m 和 n 与nums1以及nums2的大小不相等的情况,代码如下:
1 class Solution { 2 public: 3 void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { 4 int i, j; 5 i = 0, j = 0; 6 if(m < nums1.size()) nums1 = vector<int>(nums1.begin(), nums1.begin() + m); 7 if(n < nums2.size()) nums2 = vector<int>(nums2.begin(), nums2.begin() + n); 8 for(; i < nums1.size() && j < n; ++i){ 9 if(nums2[j] < nums1[i]){ 10 nums1.insert(nums1.begin() + i, nums2[j]); 11 j++; 12 } 13 } 14 for(; j < n; ++j){ 15 nums1.push_back(nums2[j]); 16 } 17 } 18 };