Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Autosaved
Table of Contents
stylenone

二分查找

LC 704. Binary Search 二分查找

https://leetcode.com/problems/binary-search/

给定一个【有序】【不重复】数组和一个目标值,找到这个元素的索引;如果不存在,返回 -1

Code Block
languagego
func search(nums []int, target int) int {
    left, right := 0, len(nums)-1
    
    for left <= right {
        mid := left + (right - left) / 2
        
        if nums[mid] == target {
            return mid
        } else if nums[mid] < target {
            left = mid + 1
        } else { // nums[mid] > target
            right = mid - 1
        }
    }
    
    return -1 // not found
}

LC.278 First Bad Version 二分查找【寻找左侧边界】

与上一题的区别在于,如果存在【重复】元素,返回最左侧边界

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

LeetCode 版本:借用二分完成(只是肯定不存在返回 -1 的情况了,只是用来做对数器验证下)

Code Block
languagego
func search_left

或者标准一点,用牛客的进行测试

https://www.nowcoder.com/questionTerminal/28d5a9b7fc0b4a078c9a6d59830fb9b9