Algorithm Spices
latest
  • Preface
  • Data Structure
  • LeetCode Tags
  • LeetCode Template
    • 1. BFS
    • 2. Binary Search
    • 3. Combinations
    • 4. DFS
    • 5. Hash Table
    • 6. Permutations
    • 7. Reverse Linked List
    • 8. Sliding Window
    • 9. Tree Traversal
  • Patterns for Coding Questions
Algorithm Spices
  • Docs »
  • LeetCode Template »
  • 2. Binary Search
  • Edit on GitHub

2. Binary Search¶

思路:左闭右开 [l, r) ,根据题目去判断,有很多变化题型

def binary_search(nums, target):
    l, r = 0, len(nums)
    while l < r:
        m = l + (r - l) // 2  # python不会溢出,c++会
        if nums[m] < target:
            l = m + 1
        else:
            r = m
    return l


print(binary_search([1, 3, 5, 6, 9], 5))

参考题目:LeetCode 69. Sqrt(x)

Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2

Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
             the decimal part is truncated, 2 is returned.
class Solution:
    def mySqrt(self, x: int) -> int:
        l, r = 1, x
        while l <= r:
            m = l + (r - l) // 2
            if m * m > x:
                r = m - 1
            else:
                l = m + 1
        return r
Next Previous

© Copyright 2020, XiuFu Guo Revision bcfae9b1.

Built with Sphinx using a theme provided by Read the Docs.