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

JavaScript查找数组首个缺失正整数函数故障排查

Fix for First Missing Positive Integer Function

Hey there! The issue with your code comes down to how you're handling zero values in the array. Right now, your first loop only moves negative numbers to the left, leaving zeros in the slice of positive numbers you process later. Zeros aren't positive integers, but they can throw off your marking logic and lead to incorrect results—like returning 1 when the actual missing positive is 4.

What's Going Wrong

Let’s take an example where your code would fail: suppose your large array is [0,1,2,3]. Your current code keeps the zero in the positive slice (arr = [0,1,2,3]). When processing this slice:

  • The zero doesn’t mark any index (since arr[-1] is undefined)
  • The 1 tries to mark index 0, but since the zero isn’t greater than 0, it stays positive
  • Your loop checks index 0 first, sees it’s positive, and returns 1—even though 1 is present and the correct missing positive is 4.

The Fix

Adjust your first loop to move all non-positive numbers (zeros and negatives) to the left. This way, the slice you process (arr) only contains positive integers, which is all we care about for finding the missing positive.

Change this line:

if(A[i] < 0){

To:

if(A[i] <= 0){

I also added a check to avoid accessing indices outside the bounds of arr when marking values—this makes the code safer and prevents unnecessary undefined checks.

Corrected Code

let firstMissingPositive = function(A){
 if(A.length === 1 && A[0] < 0){
 return 1
 }
 let j=0;
 for (let i = 0; i < A.length; i++) {
 // Move all non-positive numbers (zeros and negatives) to the left
 if(A[i] <= 0){
 let temp = A[j]
 A[j] = A[i]
 A[i] = temp;
 j++;
 }
 }
 let arr = A.slice(j);
 for (let i = 0; i < arr.length; i++) {
 let index = arr[i] - 1;
 // Only mark valid indices within the array bounds
 if (index >= 0 && index < arr.length && arr[index] > 0) {
 arr[index] = -arr[index];
 }
 }
 let k=0;
 while (true){
 if(k >= arr.length || arr[k] > 0){
 break;
 }
 k++;
 }
 return ++k;
}

Testing the Corrected Code

Let’s test the problematic case [0,1,2,3]:

  1. The first loop moves the zero to the left, so arr = [1,2,3]
  2. Processing arr:
    • 1 marks index 0 as -1
    • 2 marks index 1 as -2
    • 3 marks index 2 as -3
  3. The loop checks each index: all are negative, so k reaches 3 (equal to arr.length)
  4. Returns 3+1=4, which is correct.

All your original test cases still work as expected:

  • [1,2,0] returns 3
  • [3,4,-1,1] returns 2
  • [-8,-7,-6] returns 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:52:43