Given an array of integers, find the first missing positive integer in linear time and constant space

后端 未结 15 2537
暖寄归人
暖寄归人 2021-02-01 07:17

In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. This question was asked by Stri

15条回答
  •  眼角桃花
    2021-02-01 07:56

    JavaScript:

    let findFirstMissingNumber = ( arr ) => {
          // Sort array and find the index of the lowest positive element.
          let sortedArr = arr.sort( (a,b) => a-b );
          const lowestPositiveIndex = arr.findIndex( (element) => element > 0 );
    
          // Starting from the lowest positive element
          // check upwards if we have the next integer in the array.
          let i = lowestPositiveIndex;
          while( i < sortedArr.length ) {
            if ( sortedArr[ i + 1 ] !== sortedArr[ i ] + 1 ) {
              return sortedArr[ i ] + 1
            } else {
              i += 1;
            }
          }
        }
    
        console.log( findFirstMissingNumber( [3, 4, -1, 1, 1] ) ); // should give 2
        console.log( findFirstMissingNumber( [0, 1, 2, 0] ) ); // should give 3

提交回复
热议问题