88. 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 nums1 and nums2 are m and n respectively.
问题描述:将两个有序数组合并成一个有序数组。
思路:创建第三个数组,将其它两个数组有序的插入第三个数组中。然后根据需求变化。
代码如下:
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { vector<int> 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++; } } if(i < m) { for(;i < m; i++ ) { result.push_back(nums1[i]); } } if(j < n) { for(;j < n; j++) { result.push_back(nums2[j]); } } swap(result,nums1); } };
2016-08-05 23:36:14
时间: 2024-10-10 21:51:28