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

后端 未结 15 2241
暖寄归人
暖寄归人 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 08:04

    Javascript implementation of PMCarpan's algorithm

    function getMissingInt(array) {
      const segArray = array.filter((a) => a > 0);
      for (let i = 0; i < segArray.length; i++) {
        const value = Math.abs(segArray[i]);
        if (value <= segArray.length && segArray[value - 1] > 0) {
          segArray[value - 1] *= -1;
        }
      }
      for (let i = 0; i < segArray.length; i++) {
        if (segArray[i] > 0) {
          return i + 1;
        }
      }
      return segArray.length + 1;
    }
    console.log(getMissingInt([1, -1, -5, -3, 3, 4, 2, 8]));
    console.log(getMissingInt([3, 4, -1, 1]));
    console.log(getMissingInt([1, 2, 0]));

提交回复
热议问题