给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1中,使得 num1 成为一个有序数组。
注意:
你可以假设 nums1有足够的空间(空间大小大于或等于m + n)来保存 nums2 中的元素。在 nums1 和 nums2 中初始化的元素的数量分别是 m 和 n。

详见:https://leetcode.com/problems/merge-sorted-array/description/

Java实现:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i=m-1,j=n-1,index=m+n-1;
        while(i>=0&&j>=0){
            if(nums1[i]>nums2[j]){
                nums1[index--]=nums1[i--];
            }
            else{
                nums1[index--]=nums2[j--];
            }
        }
        while(i>=0){
            nums1[index--]=nums1[i--];           
        }
        while(j>=0){
            nums1[index--]=nums2[j--];
        }
    }
}

 

相关文章:

  • 2022-12-23
  • 2021-09-01
  • 2022-01-01
  • 2021-08-05
  • 2022-02-08
  • 2022-12-23
  • 2021-08-11
  • 2021-11-25
猜你喜欢
  • 2022-12-23
  • 2021-08-23
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-03
相关资源
相似解决方案