• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode Medium: 34. Search for a Range

一、题目

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]
题目意思就是给定一个升序的数组和一个target,找出target在此数组中的起始位置和终止位置。
二、思路
此题是easy题二分法的变种,基本思路一样,不同的是如果target == nums [ mid ]时,需要往两边扩展进行搜索,看是否有和 target 相同的数字。
三、代码
 
#coding:utf-8
class Solution:
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        left = 0
        right = len(nums)-1
        result = [-1,-1]
        while left <= right:
            mid = (left + right)//2
            if nums[mid] > target:
                right = mid - 1
            elif nums[mid] < target:
                left = mid + 1
            else:
                result[0] = mid
                result[1] = mid
                i = mid - 1
                while nums[i] == target and i >= 0:
                    result[0] = i
                    i-=1
                i = mid + 1
                while nums[i] == target and i < len(nums):
                    result[1] = i
                    i+=1
                break

        print(result)
        return result
if __name__ == '__main__':
    nums = [5,7,7,8,8,10]
    ss = Solution()
    ss.searchRange(nums,8)

  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-05-01 09:48  乐晓东随笔  阅读(129)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3