88. Merge Sorted Array
Question
Total Accepted: 80830 Total
Submissions: 274120 Difficulty: Easy
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 nums1and nums2 are m and n respectively.
Subscribe to see which companies asked this question
Hide Tags
Show Similar Problems
//思路首先:题目说的很清楚nums1已经预留了足够的空间,但是只有前面m个数是实际要合并的数 //在处理的时候将nums1中前m个数取出到临时空间tmpnums1 //从tmpnums1和nums2中将较小者放进nums1 class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { if(nums2.empty()) return; vector<int> tmpnums1(nums1.begin(),nums1.begin()+m); int i=0,mm=0,nn=0; while(mm<m && nn<n) { if( tmpnums1[mm]<=nums2[nn]) { nums1[i]=tmpnums1[mm]; mm++; }else{ nums1[i]=nums2[nn]; nn++; } i++; } while(mm<m) { nums1[i]=tmpnums1[mm]; mm++; i++; } while(nn<n) { nums1[i]=nums2[nn]; nn++; i++; } } };
别人家的解法:
非常好的思路:从两个数组的最后开始比较,直接放在了最后,因为已经知道了两个数组的长度,所以最后的坐标是 m+n-1 而每次比较后 n或m自减1
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { while(n)//数组2先放完即可终止,如果数组1都是较小者,则不动即可 {//好巧妙 if(!m || nums1[m-1]<=nums2[n-1])//m如果已经到0,说明nums1已经放完则只需nums2全部放入nums1中即可,如果m不为0,则根据大小判断即可 nums1[m+n-1]=nums2[n-- -1]; else nums1[m+n-1]=nums1[m-- -1]; } } };
时间: 2024-12-31 06:56:48