[英]What is time complexity of this solution O(N) or O(LogN)?
https://codility.com/programmers/lessons/1-iterations/ https://codility.com/programmers/lessons/1-iterations/
Considering this: 考虑到这一点:
if (largestHole > (bin.length - i) && subHole < (bin.length - i)) {
break;
}
If the length of the largest hole so far is less than the length of the remaining digits to check it breaks the loop 如果到目前为止最大的孔的长度小于要检查的其余数字的长度,则会中断循环
This line let bin = parseInt(N, 10).toString(2);
这行
let bin = parseInt(N, 10).toString(2);
is to convert a number from base 10 to base 2 string, which is what I iterate over. 是将数字从10转换为2的字符串,这就是我迭代的过程。
function solution(N) {
let bin = parseInt(N, 10).toString(2);
let subHole = 0;
let largestHole = 0;
for (var i = 0; i < bin.length; i++) {
if (largestHole > (bin.length - i) && subHole < (bin.length - i)) {
break;
}
if (bin[i] === '0') { subHole++; }
else {
if (subHole > largestHole) {
largestHole = subHole;
}
subHole = 0;
}
}
return largestHole;
}
https://codility.com/programmers/lessons/1-iterations/ https://codility.com/programmers/lessons/1-iterations/
Still O(n). 仍为O(n)。 The complexity doesn't take into account of coefficients.
复杂度不考虑系数。 Also, a O(log n) function would be something like binary search.
另外,O(log n)函数将类似于二进制搜索。
EDIT: a simple explanation of a O(log n) alogrithm: Take binary search for example. 编辑: O(log n)算法的简单说明:以二进制搜索为例。 You have a number x from, say, 1 to 100, and it's hidden in an sorted array containing n numbers from 1 to 100. You start from the middle of the array, depending on the size of the middle number compared to x, you search the left half or the right half of the array.
您有一个从1到100的数字x,它被隐藏在一个包含从1到100的n个数字的排序数组中。您从数组的中间开始,具体取决于中间数字与x的大小,搜索数组的左半部分或右半部分。 The process continues recursively, until you found the number.
该过程以递归方式继续进行,直到找到该数字为止。
For example I want to find 5 in [1,3,5,6,7,9,10]. 例如,我想在[1,3,5,6,7,9,10]中找到5。 I start from the 4th place.
我从第四名开始。 It's 6, and its bigger than 5, so we seach the left half, from 1 to 5. Then, I check the middle position again in the narrowed range, which is 3. It's smaller than 5, so we search the right half.
它是6,大于5,因此我们将左半部分从1到5进行紧缩。然后,在缩小的范围3中再次检查中间位置。它小于5,因此我们搜索右半部分。 At this point we have only one number left - which is 5.
此时,我们只剩下一个数字-5。
The search keeps dividing the array in half, so the worst scenario would take log 2 n (base 2 logarithm of n). 搜索将数组一分为二,因此最坏的情况将是log 2 n(n的以2为底的对数)。 That's a O(log n) function.
那是一个O(log n)函数。
However, as I said, the coefficient of the complexity doesn't matter. 但是,正如我所说,复杂度的系数并不重要。 For example Bubble sort usually takes approximately (n^2)/2 turns, but we simply count that as O(n^2), ignoring the 1/2 coefficient.
例如,冒泡排序通常需要大约(n ^ 2)/ 2圈,但我们将其简单地计算为O(n ^ 2),而忽略了1/2系数。
我同意O(n),但实际上它取决于parseInt函数的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.