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.
使用快排进行排序:
1 class Solution { 2 public: 3 4 void quicksort(vector<int>& a,int left,int right) 5 { 6 if(left>right) 7 return; 8 int piv = a[left]; 9 int i = left; 10 int j = right; 11 12 while(i!=j) 13 { 14 //从右边开始 15 while(a[j] >= piv && i < j) 16 j--; 17 while(a[i] <= piv && i < j) 18 i++; 19 20 if(i<j) 21 { 22 /*int t = a[i]; 23 a[i]=a[j]; 24 a[j]=t;*/ 25 swap(a[i],a[j]); 26 } 27 } 28 a[left] = a[i]; 29 a[i] = piv; 30 31 quicksort(a,left,i-1); 32 quicksort(a,i+1,right); 33 } 34 void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { 35 int i,j; 36 for(i = m,j=0;i<m+n;++i) 37 { 38 nums1[i] = nums2[j++]; 39 } 40 quicksort(nums1,0,m+n-1); 41 } 42 };
时间: 2024-11-16 22:03:53