88. Merge Sorted Array

Given two sorted integer arraysnums1andnums2, mergenums2intonums1as one sorted array.

Note:
You may assume thatnums1has enough space (size that is greater or equal tom+n) to hold additional elements fromnums2. The number of elements initialized innums1andnums2aremandnrespectively.

问题描述:将两个有序数组合并成一个有序数组。

思路:创建第三个数组,将其它两个数组有序的插入第三个数组中。然后根据需求变化。


代码如下:

classSolution{public:voidmerge(vector<int>&nums1,intm,vector<int>&nums2,intn){vector<int>result;inti=0;intj=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