1. 程式人生 > >LeetCode34:Find First and Last Position of Element in Sorted Array(二分法)

LeetCode34:Find First and Last Position of Element in Sorted Array(二分法)

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

LeetCode:連結

首先要弄懂自己寫的二分法:連結

方法一:使用二分法找到目標值,然後以此目標值為中心,向左右兩邊擴充套件,但要考慮邊界的情況。或是找到nums[mid]==target,然後從區間[low、high]的邊緣向內縮小,來確定範圍。

方法二(最優解):同樣使用二分法,先找到左端點,然後繼續使用二分法去探查右端點

一定要注意,查詢左端點返回的是左指標,查詢右端點返回的是右指標!

如果找不到,比如12沒有,最終end是9, start是10;比如0沒有,最終start是0, end是-1!所有最終二分法的start和end都回歸到這種結果!!!!

class Solution:
    def searchRange(self, nums, target):
        def binarySearchLeft(nums, target):
            low, high = 0, len(nums) - 1
            while low <= high:
                mid = (low + high) // 2
                if target > nums[mid]: 
                    low = mid + 1
                else: 
                    high = mid - 1
            # 左邊界返回的是low
            return low

        def binarySearchRight(nums, target):
            low, high = 0, len(nums) - 1
            while low <= high:
                mid = (low + high) // 2
                if target >= nums[mid]: 
                    low = mid + 1
                else: 
                    high = mid - 1
            # 找右邊界返回的是high
            return high
            
        left, right = binarySearchLeft(nums, target), binarySearchRight(nums, target)
        return (left, right) if left <= right else [-1, -1]