88. Merge two sorted arrays Merge Sorted array

Source: Internet
Author: User

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.

There are two arrays, and the previous part of array 1 is useful data, followed by 0, to merge the array 2 array into the array 1.

Because the previous section of array 1 holds useful data, you need to traverse the array in the opposite direction

  
 
  1. public class Solution {
  2. public void merge ( int [] nums1 , int m int [] NUMS2 int n ) {
  3. int index = nums1.Length - 1;
  4. int index1 = m - 1;
  5. int index2 = n - 1;
  6. while (index1 >= 0 && index2 >= 0)
  7. {
  8. if (nums1[index1] > nums2[index2])
  9. {
  10. nums1[index] = nums1[index1];
  11. index--;
  12. index1--;
  13. }
  14. else
  15. {
  16. nums1[index] = nums2[index2];
  17. index--;
  18. index2--;
  19. }
  20. }
  21. while (index1 >= 0)
  22. {
  23. nums1[index--] = nums1[index1--];
  24. }
  25. while (index2 >= 0)
  26. {
  27. nums1[index--] = nums2[index2--];
  28. }
  29. }
  30. }



Null

88. Merge two sorted arrays 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.