Leetcode Sorted Array (merge sorted array) (*)

Source: Internet
Author: User

translation
给定两个排序的整型数组nums1和nums2,将nums2合并到nums1成一个排序数组。批注:你可以假设nums1中有足够的空间(空间大于或等于m+n)来存放来自nums2的额外元素。nums1和nums2的初始空间分别是m和n。
Original
given, sorted integer  Arrays nums1 and  nums2, merge nums2 into  nums1 Span class= "Hljs-keyword" >as  one sorted array. Note:you may assume that  nums1 have 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 is M and  n respectively.  
Analysis

One idea is to set an array, and then add the data in Nums1 and NUMS2 to the new array by size, and finally assign the array to nums1, but like cheating, test instructions said it was going to nums1, so nums1 didn't change.

So, continue to think of new ways ...

First of all, the relationship is as follows:

1,m和n表示的是nums1和nums2中已经初始化的元素数量,而并非nums1和nums2的空间大小,也就是说nums1中空间足够大,但其中m个空间设置了该设的值,我们在本题中称它为有效数目2,由1得出合并后的总的有效数目为m+n3,因为都是从0开始,所以nums1和nums2的最后一个元素的索引分别是m-1和n-1,合并后的nums1的最后一个元素的索引应该是m+n-14,我们是将nums2并入nums1,所以整体的循环可以从nums2开始5,下面我会阐述为什么内部的循环要从nums1的尾部开始:因为这是vector数组而不是链表,它们是有索引的,索引是从前到后的(从0到m-1)如果在数组前方添加一个数字,那么其后的所有元素都需要往后挪一步而如果在后方添加一个数字,前面的则不需要移动。至于为什么不担心后方空间问题,因为题目说了给nums1的空间足够大。

Forgive me not to give a number paintings vertical line to distinguish each lattice, I believe everyone knows, I have tried, haha ...

Look at the code ...

Code
class  solution {public : void  merge (vector  <int ;  &nums1, int  m, vector  <int ;  &nums2, int  N) {int  i = m-1 , j = n-1 , Position = m        + N-1 ; while  (J >= 0 )  {nums1[position--] = i >= 0  && Nums1[i] > nums2[j]? nums1[i--]        : nums2[j--]; }    }};

Leetcode Sorted Array (merge sorted array) (*)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.