javascript - 如何更有效地查看数组?Javascript
问题描述
我一直在做很多关于 codility 的实践测试,虽然我所有的解决方案都有效,但它们总是有隐藏的压力测试,其中包括大量数组,例如下面的代码需要使用数组 A 并找到数组中缺少的最低正数序列。
例如:给定 A = [1, 3, 6, 4, 1, 2],函数应返回 5。5 是i
循环中递增的值。i
只要在数组中找不到索引,函数就会返回。
它可以正常工作,但 codility 使用 1-100,000 数组对其进行了测试,并且在 6 秒限制时超时。由于同样的原因,我在练习测试中的大部分代码往往会失败。非常感谢任何帮助。
console.log(solution([1, 3, 6, 4, 1, 2]));
function solution(A) {
let i = 0
for (i = 1; i <= A.length ; i++){
if(A.includes(i) == false){
return i
}
}
return i
}
解决方案
There is no way to look through N
items in less than O(n)
which is what you're doing. The issue is you're looking through the array N
times as well - this means you run N*N
times and can be improved.
The most "typical" way to improve this approach is to use a Set
or similar data structure with amortised (usually) constant-time access to elements. In your case this would look like:
console.log(solution([1, 3, 6, 4, 1, 2]))
function solution(A) {
// build existing elements, in O(N)
const values = new Set(A)
let i = 0
for (i = 1; i <= A.length; i++){
if(!values.has(i)){
return i
}
}
return i
}
This runs in O(N)
(creating the set) + O(N)
iterating the array and performing constant time work each time.
推荐阅读
- google-sheets - 如何按总和将谷歌工作表范围分成几部分
- css - 使css网格响应,如果浏览器字体大小改变
- reactjs - 如何控制antd中的时间选择器列表?
- java - SAKAI 无法部署到 TOMCAT
- php - PHP 函数的返回和回显工作方式不同。为什么?
- spring - Nginx HTTPS->HTTP 在 Spring 中出现 403“需要 SSL”错误
- django - Django:如何获取与登录用户相关的所有数据
- git - 我们如何在 Azure DevOps 构建管道中读取 GIT 提交消息?
- laravel - POST:来自 Laravel 中 Messenger Bot 的 500 内部服务器错误
- python - OpenCV RBG2HSV 转换与 float32 图像的差异