Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has 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 are m and n respectively.

合并两个有序数组,合并的结果全放在nums1数组中,nums1数组的长度至少为两个数组元素个数之和。

思路:这就跟归并排序一样。

第一种:使用额外数组作为辅助数组。最后将元素赋值给nums1,而不是将nums1指向辅助数组。

public void merge(int[] nums1, int m, int[] nums2, int n) {
      if(m==0&&n==0)  return;
        if(nums1==null||m==0) {
            for(int i=0;i<n;i++)
                nums1[i]=nums2[i];
            return ;}
        if(nums2==null||n==0) return ;
        int[] tem=new int[m+n];
        int i=0;
        int j=0;
        int k=0;
        while(j<n&&i<m){
            if(nums1[i]<nums2[j])
                tem[k++]=nums1[i++];
            else
                tem[k++]=nums2[j++];
        }
        
        while(i<m){
            tem[k++]=nums1[i++];
        }
        while(j<n){
            tem[k++]=nums2[j++];
        }
        
      for(i=0;i<m+n;i++)
                nums1[i]=tem[i];
                
               
View Code

相关文章:

  • 2022-01-20
  • 2021-06-26
  • 2021-10-19
  • 2021-06-03
  • 2021-12-26
  • 2021-12-29
  • 2022-02-07
猜你喜欢
  • 2021-09-27
相关资源
相似解决方案