You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

询问一种非双指针的两个有序数组合并算法是否可行

Is This Sorted Array Merging Approach Correct?

Short answer: No, this approach is not correct — it fails in several common scenarios due to flawed initialization and logic handling. Let’s break down the issues with concrete examples and explain where the algorithm goes wrong.

Key Problems with the Algorithm

1. Default Initialization Causes Invalid Values in Results

The variables prevMax and currMax are initialized to default(int) (which is 0). When merging arrays with all positive or all negative elements, this initial 0 gets incorrectly inserted into the result set.

Example:
Let’s merge a = [1, 3, 5, 7, 9] (sorted) and b = [2, 4] (sorted):

  • At i=0, currMax = 2, currMin = 1. The code checks prevMax (0) != currMax (2) and prevMax < currMin (0 < 1), so it adds 0 and 1 to the result. The correct merged array should start with 1, not 0.

2. Flawed Logic for Traversing Beyond the Shorter Array

Once the loop exceeds the length of the shorter array, the code tries to compare the current element of the longer array with currMax (from the previous iteration), but this leads to duplicate values and incorrect ordering.

Example:
Continuing with the same a = [1,3,5,7,9] and b = [2,4]:

  • At i=2 (beyond b’s length), the code calculates currMin = Math.Min(currMax (4), a[2] (5)) = 4, currMax = 5. It then checks prevMax (4) != currMax (5) and prevMax < currMax, so it adds 4 and 4 to the result. This inserts a duplicate 4 instead of adding 5 directly (the correct next element).

3. Unnecessary Final currMax Addition

The line result.Add(currMax) after the loop often leads to duplicate values. In your sample input, this works by coincidence (the final currMax is the largest element, and the loop didn’t add it yet), but in other cases, it repeats the last element.

Example:
If we merge a = [1,2] and b = [3,4]:

  • After the loop completes, prevMax is already 4, so adding currMax (4) again results in [1,2,3,4,4] instead of the correct [1,2,3,4].

Why the Traditional Two-Pointer Approach Works

The standard two-pointer method avoids these issues by:

  • Initializing pointers to the start of each array, not relying on default values.
  • Comparing elements from each array one at a time, adding the smaller element to the result and advancing the corresponding pointer.
  • Handling remaining elements of the longer array by appending them directly (since they’re already sorted).

This ensures correctness without edge-case bugs from initialization or incorrect min/max tracking.

内容的提问来源于stack exchange,提问作者Tal Cohen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:34:53