今天下午,我试着解决Codility的演示测试。在思考了很多如何提高性能(并进行了一点搜索)之后,我创建了以下代码:
function solution(A) {
let array = [...Array(1000001).keys()];
const onlyPositives = A.filter(n => n>0);
if(onlyPositives.length == 0) return 1
onlyPositives.forEach(a => {
if(array[a] != null)
array[a] = null;
});
array[0] = null;
return array.findIndex(e => e != null);
}
还有人有别的主意吗?
发布于 2020-03-20 12:03:51
O(n)解决方案javascript。使用两个循环。第一个循环将所有大于0的元素放入map/object第二个循环中,检查map中是否存在值。
function solution(A) {
let obj = {};
let min = 1;
//iterate over all items in the array and store the value in a object;
for (let i = 0, len=A.length; i < len; i++) {
const num = A[i];
if (num > 0) {
obj[num] = true;
}
}
//start with min===1 check if it's in the object
// if it is if it's in the object then increment min and repeat until min not in object.
while (obj[min]) {
min++;
}
//this will return the smallest value not in array bigger or equal to 1
return min;
}
发布于 2019-05-12 09:31:33
另一种处理唯一积极的事情的方法。我的JS解决方案得到了100分。基本上,我生成一个新数组,它的键将是原始数组的值,并将每个数组设置为某个真值。这做了两件事:它从新数组的迭代循环中取出负值,还允许您从最小的值开始向上循环,并返回给您未定义的第一个索引。
function solution(A) {
orderedArr = [];
for (let i = 0; i < A.length; i++) {
if (!orderedArr[A[i]]) {
orderedArr[A[i]] = true;
}
}
if (orderedArr.length === 0) return 1;
for (let i = 1; i < orderedArr.length; i++) {
if (!orderedArr[i]) {
return i;
}
}
return orderedArr.length;
}
发布于 2020-03-24 06:28:18
function solution(A) {
const numbers = []
for (let i = 0; i < A.length; i++) {
numbers[A[i]] = true
}
if (numbers.length === 0) {
return 1
}
for (let i = 1; i < numbers.length; i++) {
if(numbers[i] === undefined) {
return i
}
}
return numbers.length
}
https://stackoverflow.com/questions/50956475
复制相似问题