I. TopicsMerge Sorted ArrayTotal Accepted: 52295 Total Submissions: 173663 My Submissions
Given sorted integer Arrays nums1 and nums2, merge nums2 into nums1 as one sorted Array.
Note:
Assume that nums1 have enough space (size that's greater or equal to m + n) to hold add Itional elements from nums2. The number of elements initialized in nums1and nums2 is m and n respectively.
Show TagsHas you met this question in a real interview? Yes No
Discuss
two. Problem solving skillsThis problem is a comparison of water, there is no very complex algorithm, but a technical problem. If you simply consider merging two arrays from small to the Earth, each time you insert a number in the NUM1, you need to move the elements backwards by one bit, so that the time complexity of the process is O (m*n). since the number of elements in the two array is known, and the merged array is also incremented, that is, the maximum value of the sorted array is placed on the last side, so we can traverse backwards, that is, place the maximum value in the m+n-1 position of the first array, and then place the maximum value in m+ N-2 position, and so on, so that when the element is placed in the appropriate position, there is no need to move the element, the time complexity of this method is O (m+n).
Three. Implementing the Code
#include <iostream> #include <vector>using std::vector;class solution{public: void Merge (vector< int>& nums1, int m, vector<int>& nums2, int n) { int resultindex = m + n-1; m--; n--; while (M >= 0 | | n >= 0) { if (M < 0) { nums1[resultindex--] = nums2[n--]; Continue; } if (n < 0) { nums1[resultindex--] = nums1[m--]; Continue; } if (M >= 0 && n >= 0) { if (Nums1[m] > Nums2[n]) { nums1[resultindex--] = nums1[m--]; continue; } else { nums1[resultindex--] = nums2[n--]; Continue;}}}} ;
Four. ExperienceThis problem is only a technical question, sometimes in the past to deal with the time when the operation is not very good, you can consider from the back to the process.
Copyright, welcome reprint, reproduced Please indicate the source, thank you
Leetcode_merge Sorted Array