美文网首页
[二分法模板] 34. Find First and Last

[二分法模板] 34. Find First and Last

作者: Mree111 | 来源:发表于2019-10-19 12:45 被阅读0次

    Description

    给定sorted list & target num,返第一次&最后一次出现的位置

    复习Binary Search模板
    class Solution:  
        def searchRange(self, nums: List[int], target: int) -> List[int]:
            def search(nums,target,first=True):
                start = 0
                end = len(nums)-1
                while start +1 < end:
                    mid = (start+end)//2
                    if target > nums[mid]:
                        start = mid
                    elif target < nums[mid]:
                        end = mid
                    else:
                        if first is True:
                            end = mid
                        else:
                            start = mid
                if first is True:
                    if nums[start] == target:
                        res = start
                    elif nums[end] ==target:
                        res = end 
                    else:
                        res = -1
                else:
                    
                    if nums[end] ==target:
                        res = end 
                    elif nums[start] == target:
                        res = start
                    else:
                        res = -1
                    
                return res
            
            if len(nums)==0:
                return [-1,-1]
            
            fin_start = search(nums,target,first=True)
            fin_end = search(nums,target,first=False)
                
            return [fin_start,fin_end]
    

    相关文章

      网友评论

          本文标题:[二分法模板] 34. Find First and Last

          本文链接:https://www.haomeiwen.com/subject/saggmctx.html