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
二分查找也称折半查找算法,它是一种简单易懂的快速查找算法。例如我随机写0-100之间的一个数字,让你猜我写的是什么?你每猜一次,我就会告诉你猜的大了还是小了,直到猜中为止。
该算法要求待查找的数组已排序,实现步骤如下:
function binarySearch(items, item) { var low = 0, high = items.length - 1, mid, elem while(low <= high) { mid = Math.floor((low+high)/2) elem = items[mid] if(elem < item) { low = mid + 1 } else if(elem > item) { high = mid - 1 } else { return mid } } return -1 } // 测试 var arr = [2,3,1,4] // 快排 quickSort(arr) binarySearch(arr, 3) // 2 binarySearch(arr, 5) // -1
测试成功
二分查找易错点:
low <= high
<=
mid
Math.floor((low+high)/2)
low
high
low = mid + 1
high = mid - 1
二分查找局限性:
时间复杂度: O(logn)
空间复杂度:O(1)
leetcode
The text was updated successfully, but these errors were encountered:
第一次在 瓶子君这边写题解。
二分查找我更加喜欢 C++ STL 里面的 lower_bound 写法,可以最大语义化的实现二分查找。
function find(nums, target) { let left = 0; let right = nums.length; // 范围是 [left, right) while(left < right) { let mid = left + Math.floor((right-left)/2); if(nums[mid] < target) { left = mid+1; } else { right = mid; } } return left !== nums.length && nums[left] === target; // 如果元素存在并且重复,则left指向重复的第一个一个位置;如果不存在,则left返回的是可以插入的位置。 }
function find(nums, target) { let left = 0; let right = nums.length; // 范围是 [left, right) while(left < right) { let mid = left + Math.floor((right-left)/2); if(nums[mid] < target) { left = mid+1; } else { right = mid; } } return left; }
变体:查找最后一个小于 target 的位置,返回 left-1 即可
left-1
Sorry, something went wrong.
No branches or pull requests
二分查找也称折半查找算法,它是一种简单易懂的快速查找算法。例如我随机写0-100之间的一个数字,让你猜我写的是什么?你每猜一次,我就会告诉你猜的大了还是小了,直到猜中为止。
该算法要求待查找的数组已排序,实现步骤如下:
测试成功
二分查找易错点:
low <= high
,注意是<=
mid
的取值是Math.floor((low+high)/2)
low
high
每次更新的时候,low = mid + 1
high = mid - 1
二分查找局限性:
时间复杂度: O(logn)
空间复杂度:O(1)
leetcode
The text was updated successfully, but these errors were encountered: