当前位置:网站首页>Leetcode 88: merge two ordered arrays

Leetcode 88: merge two ordered arrays

2022-06-28 04:59:00 Swarford

link

subject :
 Insert picture description here
Note that the array is already in ascending order by default .

Method 1 :

Use double pointer p1 p2 Traversing two arrays ;
Process and Merge two ordered linked lists similar
When p1 p2 I haven't traversed to the end yet , Then judge from front to back p1 p2 The element pointed to by the pointer , Put the small one in r Array ;
When any array ends , And then jump out of the loop , Continue adding the array that has not reached the end to r The array can be ;
Last copy to nums1.

class Solution {
    
    public void merge(int[] nums1, int m, int[] nums2, int n) {
    
        int[] r=new int[nums1.length];
        int p1=0;
        int p2=0;
        int curr=0;
        while(p1<m && p2<n){
    
            if(nums1[p1]<nums2[p2]){
    
                r[curr++]=nums1[p1++];
            }else{
    
                r[curr++]=nums2[p2++];
            }
        }
        // End of any array 
        while(p1<m){
    
            r[curr++]=nums1[p1++];
        }
        while(p2<n){
    
            r[curr++]=nums2[p2++];
        }
        System.arraycopy(r,0,nums1,0,n+m);
    }
}

Method 2 :Arrays.sort

First the nums2 Add directly to nums1, And then use Java Bring their own API Sort

class Solution {
    
    public void merge(int[] nums1, int m, int[] nums2, int n) {
    
        for(int i=0;i<n;i++){
    
            nums1[m+i]=nums2[i];
        }
        Arrays.sort(nums1);
    }
}
原网站

版权声明
本文为[Swarford]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/179/202206280414226303.html