# 4ms C++ solution with single loop

• This code relies on the simple observation that once all of the numbers from `nums2` have been merged into `nums1`, the rest of the numbers in `nums1` that were not moved are already in the correct place.

``````class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - 1, j = n - 1, tar = m + n - 1;
while (j >= 0) {
nums1[tar--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
}
}
};``````

• how about the size is greater than m+n?,this is a problem you don`t consider

• good implement!!

• concise and nice

• @ajin There are totally m+n elements; the size won't greater than m+n.

• great!!!! good idea

• tar--

Genious :)

• I'm wondering why sorted array means sorted in ascending order. Can anyone help to explain?

• This post is deleted!

• it’s perfect

• @Caramel You can think of it as a merge sort from a smaller one, and as long as you open up an array of Spaces

• This is not a valid C++ solution.

• this is a bad question, if question says merged in ascending, then this is indeed a simple question, but the real hard part is to even decide what order the two arrays are sorted. e.g. array 1 {3,3,3,}, array 2 {2,2,1}, when you merge them in ascending order, you'll get 2,2,3,3,3, then here comes 1 (end of array 2), what would you do???

• ``````        nums1[tar--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
``````

Can someone explain what this line means?

Is it:
is (i >0) && nums1[i] > nums2[i]?

if so -> assign nums1's value to the post decrementation of nums1 at tar and then decrement nums1

else do it for nums2?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.