New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js] 第249天 从一个无序的整数数组中,找出最小和最大数之间缺失的数字,要求最小的时间复杂度 #1675
Comments
const findNum = function(arr) {
let newArr = new Array()
let maxNum = Math.max(...arr)
let minNum = Math.min(...arr)
for(let i = minNum; i < maxNum; i++){
if(!arr.find(e => e == i)){
newArr.push(i)
}
}
return newArr
} |
function getArr(arr) { |
可以使用线性扫描来找出最小和最大数之间缺失的数字,并且时间复杂度为 O(n),其中 n 为数组中元素的个数。 具体的做法如下: 首先找到数组中的最小值和最大值。 创建一个长度为最大值和最小值之间差值加1的布尔类型数组,用来记录每个数字是否出现过。 遍历原始数组,将出现过的数字在布尔类型数组中标记为 true。 遍历布尔类型数组,找到第一个为 false 的位置,即为最小和最大数之间缺失的数字。 以下是 JavaScript 的实现示例代码: function findMissingNumber(nums) { |
const findHideNumbers = numbers => {
const state = {}
for(const number of numbers) state[number] = true
const sortedNumber = Object.keys(state)
const min = sortedNumber[0]
const max = sortedNumber.pop()
const hideNumbers = []
for (let i = min; i < max; i++) {
if (!state[i]) hideNumbers.push(i)
}
return hideNumbers
}
findHideNumbers([2,1,7,5,3,10]) // output: [4, 6, 8, 9] |
第249天 从一个无序的整数数组中,找出最小和最大数之间缺失的数字,要求最小的时间复杂度
我也要出题
The text was updated successfully, but these errors were encountered: