【算法模板】二分查找

2022-05-12 10:40:34 浏览数 (2)

二分查找

logn复杂度

  • binary_search:点查
  • left_bound:左边界
  • right_bound:右边界
代码语言:javascript复制
func binary_search(nums []int, target int) int {
	left, right := 0, len(nums)-1
	for left <= right {
		mid := left   (right-left)/2
		if nums[mid] < target {
			left = mid   1
		} else if nums[mid] > target {
			right = mid - 1
		} else if nums[mid] == target {
			return mid
		}
	}
	return -1
}

func left_bound(nums []int, target int) int {
	left, right := 0, len(nums)-1
	for left <= right {
		mid := left   (right-left)/2
		if nums[mid] < target {
			left = mid   1
		} else if nums[mid] > target {
			right = mid - 1
		} else if nums[mid] == target {
			right = mid - 1
		}
	}
	if left >= len(nums) || nums[left] != target {
		return -1
	}
	return left
}

func right_bound(nums []int, target int) int {
	left, right := 0, len(nums)-1
	for left <= right {
		mid := left   (right-left)/2
		if nums[mid] < target {
			left = mid   1
		} else if nums[mid] > target {
			right = mid - 1
		} else if nums[mid] == target {
			left = mid   1
		}
	}
	if right < 0 || nums[right] != target {
		return -1
	}
	return right
}

0 人点赞