Given sorted integer Arrays nums1 and nums2, merge nums2 intonums1 as one sorted a Rray.
Note:
Assume that nums1 have enough space (size that's greater or equal tom +n) to hold Addit ional elements from nums2. The number of elements initialized innums1 andnums2 is m and n respectively.
Test Case:
Runtime Error Message:Last executed input:Input:[1,2,3,0,0,0], 3, [2,5,6], 3Output:[1,2,3,5,6]expected:[1,2,2,3,5,6]
The wrong solution:
Class Solution {public: void merge (vector<int>& nums1, int m, vector<int>& nums2, int n) { c2/>set<int> result; for (int i = 0;i<m;i++) { result.insert (nums1[i]); } for (int i = 0;i<n;i++) { result.insert (nums2[i]); } Nums1.clear (); Set<int>::iterator iter = Result.begin (); for (; Iter!=result.end (); iter++) { nums1.push_back (*iter);}} };
My solution: Above is the same element is not loaded into the multiset on the line
Class Solution {public: void merge (vector<int>& nums1, int m, vector<int>& nums2, int n) { c2/>multiset<int> result; for (int i = 0;i<m;i++) { result.insert (nums1[i]); } for (int i = 0;i<n;i++) { result.insert (nums2[i]); } Nums1.clear (); Set<int>::iterator iter = Result.begin (); for (; Iter!=result.end (); iter++) { nums1.push_back (*iter);}} };
A short solution:
Class Solution {public: void merge (int a[], int m, int b[], int n) { int k = m + N; while (k--> 0) a[k] = (n = = 0 | | (M > 0 && a[m-1] > b[n-1])) ? A[--M]: b[--n];} ;
Good readability:
Class Solution {public: void merge (int a[], int m, int b[], int n) { int i=m-1; int j=n-1; int k = m+n-1; while (i >=0 && j>=0) { if (A[i] > B[j]) a[k--] = a[i--]; else a[k--] = b[j--]; } while (j>=0) a[k--] = b[j--]; }};
Python solution:
Class solution:# @param a a list of integers# @param m an integer, length of a# @param B A List of integers # @param n an integer, length of b# @return No (void) def merge (self, A, M, B, N): x=a[0:m] y=b[0:n]
x.extend (y) x.sort () a[0:m+n]=x
Python solution 2:thats Why do we love Python
def merge (self, A, M, B, N): a[m:] = b[:n] a.sort ()
Leetcode-Merge Sorted Array