leetcode 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.
Subscribe to see which companies asked this question
一直没有理解题意,意思是把num2插入到nums1中,但是nums1保持m个元素,nums2保持n个元素。
后来发现只要先保持nums1 n个元素,然后把nums2插进去,然后排序就好了,我这样做算是作弊吗?
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]; } };