【发布时间】:2019-07-15 07:01:50
【问题描述】:
我最近开始学习 JavaScript 算法。当我遇到这个问题并且我一直在尝试实现它时,我正在尝试二进制搜索,但我一直遇到困难。 该函数接受两个参数(一个排序数组和一个数字)并返回一个包含数字出现次数和计数的object。我得到的occurrence 不是正确的数字,count 是不变的。
这是我到目前为止所做的:
function binarySearchOccurrence(array, element) {
//declare the start index on the left side to zero
let startIndex = 0;
//declare the end index on the right side to the length of array minus 1
let endIndex = array.length - 1;
//set initial count to zero
let count = 0;
let occurrence = 0;
//declare an empty object to hold the result of search and count
const result = {}
//Applying binary search, iterate while start does not meed end
while(startIndex <= endIndex){
//find the middile index
let middle = Math.floor((startIndex + endIndex)/2);
let guessElement = array[middle];
count++;
//if element is present in the middle, increment occurence
if(guessElement === element){
occurrence++;
while(startIndex <= endIndex){
if(guessElement > element){
endIndex = middle - 1;
occurrence++;
break;
} else {
startIndex = middle + 1;
occurrence++;
break;
}
}
//Else look in the left or right side accordingly
} else if (guessElement > element) {
endIndex = middle - 1;
} else {
startIndex = middle + 1;
}
}
result.occurrence = occurrence;
result.count = count;
return result;
}
当我使用这样的数组进行测试时:binarySearchOccurrence([1, 2, 3, 4, 4, 4, 5, 5, 5, 6, 7, 8, 9], 5) 它返回 { occurrence: 6, count: 4 } 而不是 { occurrence: 3, count: 2 };
【问题讨论】:
-
count和occurrence是什么意思?对于您的示例,正确的occurrence和count是什么样的? -
我不明白为什么这么复杂。您似乎从中间开始搜索对象的两侧。为什么不从对象的开头(0)开始搜索直到到达结尾(array.length -1)?
-
@lurker 我已经修改了。
-
@Sablefoste 我正在使用时间复杂度为 O(logn) 的二进制搜索方法。
-
所以
occurrence是它找到的数量。那么count是什么?