704. 二分查找
- https://leetcode.cn/problems/binary-search/description/
描述
- 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
提示
- 你可以假设 nums 中的所有元素是不重复的。
- n 将在 [1, 10000]之间。
- nums 的每个元素都将在 [-9999, 9999]之间。
Typescript 版算法实现
1 ) 方案1
function search(nums: number[], target: number): number {
let low: number = 0; // 最小下标
let high: number = nums.length - 1; // 最大下标
while(low <= high) {
const mid: number = Math.floor((low + high) / 2);
const current: number = nums[mid];
if (current === target) return mid;
if(current < target) low = mid + 1;
if (current > target) high = mid - 1;
}
return -1
}
Python3 版算法实现
1 ) 方案1
def binary_search(nums, target):
low = 0 # 最小下标
high = len(nums) - 1 # 最大下标
while low <= high:
mid = (low + high) // 2
current = nums[mid]
if current == target:
return mid
if current < target:
low = mid + 1
if current > target:
high = mid - 1
return -1
def test_binary_search():
test_cases = [
([1, 2, 3, 4, 5], 3, 2),
([1, 2, 3, 4, 5], 6, -1),
([1, 2, 3, 4, 5], 1, 0),
([1, 2, 3, 4, 5], 5, 4),
([], 1, -1),
([1], 1, 0),
([1], 2, -1),
([1, 3, 5, 7, 9], 7, 3),
([1, 3, 5, 7, 9], 2, -1),
([1, 3, 5, 7, 9], 9, 4),
([1, 3, 5, 7, 9], 0, -1),
]
for i, (nums, target, expected) in enumerate(test_cases):
result = binary_search(nums, target)
if result == expected:
print(f"Test Case {i + 1}: PASS (For list {nums} and target {target}, expected {expected}, got {result})")
else:
print(f"Test Case {i + 1}: FAIL (For list {nums} and target {target}, expected {expected}, got {result})")
if __name__ == "__main__":
test_binary_search()
Golang 版算法实现
1 ) 方案1
package main
import (
"fmt"
)
// 二分查找函数
func binarySearch(nums []int, target int) int {
low := 0 // 最小下标
high := len(nums) - 1 // 最大下标
for low <= high {
mid := (low + high) / 2
current := nums[mid]
if current == target {
return mid
}
if current < target {
low = mid + 1
}
if current > target {
high = mid - 1
}
}
return -1
}
func testBinarySearch() {
testCases := []struct {
nums []int
target int
want int
}{
{[]int{1, 2, 3, 4, 5}, 3, 2},
{[]int{1, 2, 3, 4, 5}, 6, -1},
{[]int{1, 2, 3, 4, 5}, 1, 0},
{[]int{1, 2, 3, 4, 5}, 5, 4},
{[]int{}, 1, -1},
{[]int{1}, 1, 0},
{[]int{1}, 2, -1},
{[]int{1, 3, 5, 7, 9}, 7, 3},
{[]int{1, 3, 5, 7, 9}, 2, -1},
{[]int{1, 3, 5, 7, 9}, 9, 4},
{[]int{1, 3, 5, 7, 9}, 0, -1},
}
for i, tc := range testCases {
result := binarySearch(tc.nums, tc.target)
if result == tc.want {
fmt.Printf("Test Case %d: PASS (For list %v and target %d, expected %d, got %d)\n", i+1, tc.nums, tc.target, tc.want, result)
} else {
fmt.Printf("Test Case %d: FAIL (For list %v and target %d, expected %d, got %d)\n", i+1, tc.nums, tc.target, tc.want, result)
}
}
}
func main() {
testBinarySearch()
}
总结
- 折半搜索,是在有序数组中查找每个元素的搜索算法,减而治之
- 思路
- 从数组中间元素开始,如果中间元素正好是目标值,则搜索结束,返回中间元素下标
- 如果目标值大于或小于中间元素,则在大于或小于中间元素的那一半进行搜索,搜索方式同上
- 如果搜到最后,还没有,返回-1
- 时间复杂度 O(logn)
- 每次比较,搜索范围缩半
- 劈成2半的问题都是O(logn)
1600



被折叠的 条评论
为什么被折叠?



