CS-Notes icon indicating copy to clipboard operation
CS-Notes copied to clipboard

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

Open LinZhenli opened this issue 4 years ago • 2 comments

如果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--]; } } }

LinZhenli avatar Mar 13 '21 12:03 LinZhenli

@LinZhenli 已修改,感谢建议!

CyC2018 avatar Apr 18 '21 17:04 CyC2018

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

SAMSONEE avatar May 16 '21 12:05 SAMSONEE