美文网首页
LeetCode88--合并两个有序数组

LeetCode88--合并两个有序数组

作者: Cuttstage | 来源:发表于2019-04-20 23:41 被阅读0次

题目:
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

思路:
为了实现O(1)的空间复杂度,从两个数组的最后开始遍历到头。这样,前面的元素就不会被覆盖

代码:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int index1 = m-1, index2 = n-1;
        int mergeIndex = m + n - 1;
        while ( index1 >= 0 || index2 >= 0 ) {
            if( index1 < 0 ){
                nums1[mergeIndex--] = nums2[index2--];
            }else if( index2 < 0){
                nums1[mergeIndex--] = nums1[index1--];
            }else if( nums1[index1] < nums2[index2] ){
                nums1[mergeIndex--] = nums2[index2--];
            }else{
                nums1[mergeIndex--] = nums1[index1--];
            }
        }
    }
}

相关文章

网友评论

      本文标题:LeetCode88--合并两个有序数组

      本文链接:https://www.haomeiwen.com/subject/rqwrgqtx.html