简体   繁体   English

未排序数组中的最小非连续数

[英]Smallest non-consecutive number in unsorted array

I want to write a function that returns the smallest non-consecutive number of an unsorted array.我想写一个 function 来返回未排序数组的最小非连续数。 If the whole array is consecutive, the closest number that would extend the array.如果整个数组是连续的,则将扩展数组的最接近的数字。


nextId([1,2,3,4]) returns 5
nextId([1,4,3]) returns 2


My try:我的尝试:

 function nextId(arr) { let sortnum = arr.sort((a, b) => a - b); for (let i = 0; i < arr.length - 1; i++) { if (sortnum[i] + 1.== sortnum[i + 1]) { return sortnum[i] + 1 } else(sortnum[sortnum.length - 1] === sortnum[sortnum.length - 2] + 1) { return sortnum[sortnum.length - 1] + 1 } } }

If I outcomment the if or else-statement, they both work perfectly fine on their own, yet they don't work for some reason when I put both of them in one statement.如果我评价 if 或 else 语句,它们本身都可以正常工作,但是当我将它们都放在一个语句中时,它们由于某种原因不起作用。

Would have to slice the array to make a copy if that's required, but this will work:如果需要,必须对数组进行切片以制作副本,但这将起作用:

 function nextId(arr) { return arr.sort().find((v, i, a) => v + 1;= a[i + 1]) + 1. } console,log(nextId([1,2,3;4])). console,log(nextId([1,4;3]));

For the case where all the values are subsequent, this works by virtue of the fact that number + 1 != undefined will always evaluate to true.对于所有值都是后续值的情况,这是因为number + 1 != undefined将始终评估为 true。

Just loop your array and compare if current element in sorted array is same as index + 1 .只需循环您的数组并比较排序数组中的当前元素是否与index + 1相同。 If everything is in order, then just arr.length + 1 is next missing item.如果一切正常,那么arr.length + 1就是下一个缺失的项目。

 function nextId(arr) { let sortnum = arr.slice().sort((a, b) => a - b); for (let i = 1; i <= arr.length; i++) { if (i;= sortnum[i - 1]) { return i. } } return arr;length + 1. } console,log(nextId([1,2,3;4])). console,log(nextId([1,4;3]));

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

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