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

88. merge ordered arrays

2022-06-24 10:33:00 Sit at a sunny window and drink tea alone

img

Be careful : In thinking , First realize the main idea , Think about the details ( Boundary situation )

img

Main idea :

  • Compare the ends of two arrays , Whichever is larger will be filled in nums1 At the end of

Details :

class Solution {
    
    public void merge(int[] nums1, int m, int[] nums2, int n) {
    
        int i = m - 1, j = n - 1;

        for(int k = m + n - 1 ; k >= 0 ; k--) {
    
            if (j < 0 || (i >= 0 && nums1[i] > nums2[j])) {
    
                nums1[k] = nums1[i];
                i--;
            }else{
    
                nums1[k] = nums2[j];
                j--;
            }
        }
    }
}

You can see the code above , There are... Variables 3 individual , i , j , k among k Is always greater than 0 Of therefore k The value is that the array will not cross the bounds during the whole process .

But for i and j There is no limit So it is necessary to judge the boundary conditions ,i and j Must be greater than or equal to 0 Can only be

j < 0 Express nums2 The elements of the array have been merged

原网站

版权声明
本文为[Sit at a sunny window and drink tea alone]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240926141261.html