function findSmallestPositiveInteger(A) {


    // sort array from smallest to largest number
     A.sort((a, b) => a - b)
     
    // remove duplicates because they just would take memory
    const noDups =Array.from(new Set(A).keys())
    
    let smallestPositiveInteger=1
    
    let previous = noDups[0]
    if(previous <= smallestPositiveInteger && previous>0)
            smallestPositiveInteger++
    
    for(let i =1;i<noDups.length;i++){
      const v = noDups[i]
      if(previous > 0){
         const diffWithPrevious = v - previous
         // the logic for this early return is that we might not need to traverse
         // the whole array for example imagine this example 
         // [1,2,5,6,8,...n]
         // its clear that there is a gap between 5 and 2 so we can just 
         // conclude that 2+1 is the smallest postive integer not in our array 
         if(diffWithPrevious > 1) return previous +1;      
      }
      
      // check if smallest positive integer in array is not 1
      // if so return 1 
      if(previous == 0 && v > 1 ) return 1
      
      if(v <= smallestPositiveInteger && v>0)
         smallestPositiveInteger++
       previous = v
    }

    return smallestPositiveInteger
}


const arr =[-1,-2,1,3,10,9,3,2,3,3,10,2,7,99,100,10000,500,50,60,70,33]

console.log(findSmallestPositiveInteger(arr))

推荐答案

将数组中的整数放入查找 struct ,然后try 从1开始的自然数,直到找到不在数组中的整数:

function findSmallestPositiveInteger(arr) {
    const lookup = new Set(arr);
    let i = 1;
    while (lookup.has(i)) {
        i++;
    }
    return i;
}

Javascript相关问答推荐

CSS背景过滤器忽略转换持续时间(ReactJS)

JavaScript替换子 node 导致它们更改为[对象HTMLTable SectionElement]

当我使用jQuery时,我的图标显示为[对象对象]

如何使用JavaScript对切换的声音设置音量

React redux状态未在React-Router库中呈现

更新Reduxstore 中的状态变量,导致整个应用程序出现不必要的重新渲染

通过在页面上滚动来移动滚动条

useNavigation更改URL,但不呈现或显示组件

网页自检测外部元素无法加载

google docs boldText直到按行执行应用脚本错误

将字符串UTC Date转换为ngx—counting leftTime配置值的数字

我的角模板订阅后不刷新'

Ember.js 5.4更新会话存储时如何更新组件变量

在使用HighChats时如何避免Datatables重新初始化错误?

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

删除加载页面时不存在的元素(JavaScript)

Socket.IO在刷新页面时执行函数两次

Clip-Path在网页浏览器(Mozilla、Edge、Chrome)上不能正常工作,但在预览版Visual Code Studio HTML、CSS、JS上却能很好地工作

我怎样才能得到一个数组的名字在另一个数组?