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

Leetcode daily question: merge two ordered arrays

2022-07-05 17:48:00 Sharp blade CC

Alt
link : Merge two ordered arrays


This question has a requirement : Can I use O(m+n) The time complexity of ?

Of course there are !

Ideas : Point to the tail of two arrays with two pointers ! This is the key !
Then traverse from back to front . You can know the title ,nums1 It must be the size of m+n Of , And nums1 The second half of the is empty , Direct coverage has no effect .
So it's going to be nums2 Elements in and nums1 The comparison in , Let whoever is old go in first .

class Solution {
    
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    
        int p1=m-1,p2=n-1;
        int i=1;
        while(p1>=0||p2>=0)
        {
    
            if(p1<0)
            {
    
                nums1[m+n-i]=nums2[p2];
                p2--;
                i++;
            }
            else if(p2<0)
            {
    
                break;
            }
            else if(nums1[p1]<=nums2[p2])
            {
    
                nums1[m+n-i]=nums2[p2];
                i++;
                p2--;
            }
            else 
            {
    
                nums1[m+n-i]=nums1[p1];
                p1--;
                i++;
            }
        }
    }
};

 Insert picture description here

原网站

版权声明
本文为[Sharp blade CC]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051717245066.html