topic:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1, making num1 an sorted array. illustrate: Initialize nums1 and nums2 with m and n elements, respectively. You can assume that nums1 has enough space (the space size is greater than or equal to m + n) to hold the elements in nums2. Example: enter: 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:
From the back of the array, take the largest data in order.
Code:
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int a=n+m-1, i=m-1, j=n-1; while(i>=0 && j>=0) { if(nums1[i]>=nums2[j]) nums1[a--]=nums1[i--]; else nums1[a--]=nums2[j--]; } if(j>=0) { while(j>=0) { nums1[a--]=nums2[j--]; } } return; } };