Subject description:
Given two ordered arrays of integers and nums2 nums1, incorporated into the nums2 nums1 in an ordered array such as a num1.
Description:
And initializing the number of elements nums1 nums2 of m and n.
You can assume nums1 sufficient space (space equal to or greater than m + n) to save the elements of nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m =. 3
nums2 = [2,5,6], n-=. 3
Output: [1,2,2,3,5,6]
Problem-solving ideas:
Alternatively nums1 with nums2 of 0, and then sort of nums1
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
nums1[m:] = nums2
nums1.sort()
Comments area Answer:
reverse comparison, the larger value into the back nums1
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i=m-1,j=n-1,t=m+n-1;
while(i>=0 && j>=0){
if(nums1[i]>nums2[j]){
nums1[t--]=nums1[i--];
}else{
nums1[t--]=nums2[j--];
}
}
while(i>=0) nums1[t--]=nums1[i--];
while(j>=0) nums1[t--]=nums2[j--];
}
};