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. (0ms)
数组nums1和数组nums2 的大小都已经知道,分别是m和n,所以nums1需要容纳nums2的元素,大小为m+n,如果从头开始比较,则会有更多的移动次数,从后往前比较速度更快。
1 void merge(int* nums1, int m, int* nums2, int n) { 2 if(!nums1 || !nums2 ) return ; 3 4 int i = m + n -1; 5 int j = m - 1; 6 int k = n - 1; 7 8 while(j >= 0 && k >= 0) 9 { 10 if(nums1[j] <= nums2[k]) 11 { 12 nums1[i] = nums2[k--]; 13 } 14 else 15 { 16 nums1[i] = nums1[j--]; 17 } 18 19 i--; 20 } 21 22 while(j >= 0) 23 { 24 nums1[i--] = nums1[j--]; 25 } 26 27 while(k >= 0) 28 { 29 nums1[i--] = nums2[k--]; 30 } 31 32 }
浙公网安备 33010602011771号