简体   繁体   English

使用Javascript查找数组中最小的未使用数字

[英]Find the lowest unused number in an array using Javascript

I have an array full of numbers.我有一个充满数字的数组。 Here's an example:下面是一个例子:

myArray = [0,1,2,4,5];

I need to find the lowest unused number starting from 1, so in this case it will be 3.我需要找到从 1 开始的最低未使用数字,所以在这种情况下它将是 3。

I've been reading up of using indexOf but I'm unsure how to use it for my specific purpose.我一直在阅读使用indexOf但我不确定如何将它用于我的特定目的。

Assuming the array isn't sorted, you always start at 0, and taking into account your desire to find a highest number if there isn't one missing:假设数组未排序,您总是从 0 开始,并考虑到您希望在没有丢失的情况下找到最高数字:

var k = [6, 0, 1, 2, 4, 5];

k.sort(function(a, b) { return a-b; });   // To sort by numeric

var lowest = -1;
for (i = 0;  i < k.length;  ++i) {
  if (k[i] != i) {
    lowest = i;
    break;
  }
}
if (lowest == -1) {
    lowest = k[k.length - 1] + 1;
}
console.log("Lowest = " + lowest);

Logs answer 3. If 3 was also in there, would log 7 since no other number is missing.日志回答 3。如果 3 也在那里,则将记录 7,因为没有其他数字丢失。

If you aren't always starting at zero, use an offset:如果您并不总是从零开始,请使用偏移量:

var k = [6, 2, 3, 4, 5];

k.sort(function(a, b) { return a-b; });   // To sort by numeric

var offset = k[0];
var lowest = -1;
for (i = 0;  i < k.length;  ++i) {
  if (k[i] != offset) {
    lowest = offset;
    break;
  }
  ++offset;
}
if (lowest == -1) {
    lowest = k[k.length - 1] + 1;
}
console.log("Lowest = " + lowest);

Logs answer 7 since none are missing after 2 which starts the sequence.日志回答 7,因为在开始序列的 2 之后没有丢失。

This takes a sequence starting from a number (like 1 in your example) and returns the lowest unused number in the sequence.这需要一个从数字开始的序列(如您的示例中的 1),并返回序列中最低的未使用数字。

function lowestUnusedNumber(sequence, startingFrom) {
  const arr = sequence.slice(0);
  arr.sort((a, b) => a - b);

  return arr.reduce((lowest, num, i) => {
    const seqIndex = i + startingFrom;
    return num !== seqIndex && seqIndex < lowest ? seqIndex : lowest
  }, arr.length + startingFrom);
}

Example:例子:

> lowestUnusedNumber([], 1)
1
> lowestUnusedNumber([1,2,4], 1)
3
> lowestUnusedNumber([3], 1)
1

In exchange for readability, it's slightly less optimized than the other example because it loops over all items in the array instead of breaking as soon as it finds the missing item.作为可读性的交换,它的优化程度略低于其他示例,因为它遍历数组中的所有项目,而不是在找到丢失的项目后立即中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM