zoukankan      html  css  js  c++  java
  • leetcode-mid-sorting and searching-34 Search for a Range

    mycode   63.98%

    class Solution(object):
        def searchRange(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            if target in nums:
                start = nums.index(target)
                end = start
                for i in nums[start+1:]:
                    if i == target :
                        end += 1
                    else:
                        return [start,end]
                return [start,end]
            else:
                return [-1,-1]

    参考

    思路:类似于二分法,先用[low,high]找到包含target的子段,再用[L,R]找到包含target的两端

    class Solution(object):
        def searchRange(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            low, high = 0, len(nums)-1
            while low <= high:
                mid = (low+high)//2
                if nums[mid] == target:
                    L, R = mid, mid
                    while L >= low and nums[L] == target:
                        L -= 1
                    while R <= high and nums[R] == target:
                        R += 1
                    return [L+1, R-1]
                if nums[low] <= target < nums[mid]:
                    high = mid - 1
                else:
                    low = mid + 1
            return [-1, -1]
  • 相关阅读:
    模块系统
    控制结构
    基本语法
    Go-技篇第一 技巧杂烩
    微服务的4个设计原则和19个解决方案
    kcp-go源码解析
    windows.go
    服务端跨域处理 Cors
    Snowflake 全局唯一Id 生成
    面试?或许你应该这样
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10974968.html
Copyright © 2011-2022 走看看