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.
Subscribe to see which companies asked this question
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { for(int i=0;i<n;i++){ nums1[m++]=nums2[i]; } sort(nums1.begin(),nums1.end()); } };
看看大神的做法:
class Solution { public: void merge(int A[], int m, int B[], int n) { int temp[m+n]; int i = 0, j = 0, t = 0; while(i < m && j < n) { if(A[i] < B[j]) temp[t++] = A[i++]; else temp[t++] = B[j++]; } while(i < m) temp[t++] = A[i++]; while(j < n) temp[t++] = B[j++]; while(--t >= 0) A[t] = temp[t]; } };
原文:http://www.cnblogs.com/LUO77/p/5033720.html