We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
题目:
请使用 二分搜索算法 编写函数 binarySearch,实现类似 indexOf 的功能。要求:
binarySearch
indexOf
/** * @param {array} arr - 按升序排列的普通数组 * @param {number} target - 需要在 arr 中搜索的目标值 * @return {number} 返回 target 在 arr 中的索引值,如不存在,则返回 -1 */ function binarySearch(arr, target) { // 你的代码 }
测试数据:
const test = [1, 3, 8, 9, 27, 34, 128, 275]; binarySearch(test, 128); // 6 binarySearch(test, 30); // -1
参考答案:
function binarySearch(arr, target) { let startIdx = 0; let endIdx = arr.length - 1; let midIdx = Math.floor((startIdx + endIdx) / 2); while(endIdx - startIdx > 1) { switch(target) { case arr[startIdx]: return startIdx; case arr[endIdx]: return endIdx; case arr[midIdx]: return midIdx; } if (target > arr[midIdx]) { // 右边找 startIdx = midIdx; } else if (target < arr[midIdx]) { // 左边找 endIdx = midIdx; } midIdx = Math.floor((startIdx + endIdx) / 2); } return -1; }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目:
请使用 二分搜索算法 编写函数
binarySearch
,实现类似indexOf
的功能。要求:测试数据:
参考答案:
The text was updated successfully, but these errors were encountered: