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 nums1 and nums2 is m and n respectively.
Title tag: Array
The topic gives us two ordered arrays, let's merge sort, and nums1 has enough space for us to store two array. Since is to put in the nums1, then if we compare nums1 and NUMS2 figures, if the number of NUMS2 is small, it is necessary to put the NUMS2 number into the nums1, we also have to store the number of nums1, so we need extra space. So, we can go back to start from the end of NUMS1, then set two pointers to point to the last number of the two array, which can be stored directly into the NUMS1 after the size is finished. Note that the final need to check, nums2 whether there are the remaining number, some words need to deposit into the nums1.
Java Solution:
Runtime beats 38.77%
Completion Date: 04/05/2017
Keywords: Array
Key points: Merge sort;two pointers; traverse back from end to start
1 Public classSolution2 {3 Public voidMergeint[] nums1,intMint[] Nums2,intN)4 {5 /*if m = 0, meaning nums1 ' s elements is all done. Need one more when loop after this6 To take care of the left elements of NUMS2.7 if n = 0, meaning nums2 ' s elements is done, the rest of the Nums1 ' s elements is in the8 Right place . No need to take care of them.9 */Ten while(M > 0 && N >0) One { A if(Nums1[m-1] > Nums2[n-1])//if number 1 > number 2 - { - //save Nums1 ' s element into Nums1 's last "empty" spot. theNums1[m+n-1] = nums1[m-1]; -m--; - } - Else //If number 1 <= number 2 + { - //save Nums2 ' s element into Nums1 's last "empty" spot +Nums1[m+n-1] = nums2[n-1]; An--; at } - } - - - //Check if Nums2 ' s elements is not finished. - while(N > 0) in { - //Save Nums2 ' s rest elements into nums1 toNums1[m+n-1] = nums2[n-1]; +n--; - } the } *}
Resources:
Http://www.cnblogs.com/springfor/p/3872640.html
Leetcode algorithm topic List- leetcode algorithms Questions list
Leetcode 88. Merge Sorted Array (merge ordered array)