Skip to content

Leetcode刷题,双指针:88 Merge Sorted Array可以优化。 #1060

Open
@LinZhenli

Description

@LinZhenli

如果index2先到达头部,那说明能插入的值都已经插入了,不用再判断了。
所以优化为:

//从尾部开始遍历,先确定尾部
public static void merge2(int[] nums1, int m, int[] nums2, int n) {
int index1 = m - 1, index2 = n - 1;
int indexMerge = m + n - 1;
while ( index2 >= 0) {
if (index1 < 0) {//意思是num1遍历完了,都是num2的值来插入。
nums1[indexMerge--] = nums2[index2--];
}else if (nums1[index1] > nums2[index2]) {//遍历比较,哪个大,哪个放到最后,同时序号递减,小的那个序号一直不动
nums1[indexMerge--] = nums1[index1--];
} else {
nums1[indexMerge--] = nums2[index2--];
}
}
}

Activity

CyC2018

CyC2018 commented on Apr 18, 2021

@CyC2018
Owner

@LinZhenli 已修改,感谢建议!

SAMSONEE

SAMSONEE commented on May 16, 2021

@SAMSONEE

更新的版本还是多了一个判断index2<0的else if分支,while(index2>=0)已经判断过一次了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    opt优化

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @LinZhenli@CyC2018@SAMSONEE

        Issue actions

          Leetcode刷题,双指针:88 Merge Sorted Array可以优化。 · Issue #1060 · CyC2018/CS-Notes