美文网首页
7 - Medium - 搜索范围

7 - Medium - 搜索范围

作者: 1f872d1e3817 | 来源:发表于2018-07-06 12:53 被阅读0次

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

你的算法时间复杂度必须是 O(log n) 级别。

如果数组中不存在目标值,返回 [-1, -1]。

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]

左右夹逼

class Solution:
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if not nums:
            return [-1, -1]
        left, right = 0, len(nums) - 1
        while nums[left] != target or nums[right] != target:
            no_change = True
            if nums[left] != target:
                no_change = False
                left += 1
            if nums[right] != target:
                right -= 1
                no_change = False
            if no_change or left >= right:
                break
        if left < len(nums) and nums[left] == target:
            return [left, right]
        else:
            return [-1, -1]

36ms,二分查找

class Solution:
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        start = self.firstGreaterEqaul(nums, target)
        if start==len(nums) or nums[start]!=target:
            return [-1, -1]
        return [start, self.firstGreaterEqaul(nums, target+1)-1]
    def firstGreaterEqaul(self, nums, target):
        lo, hi = 0, len(nums)
        while lo<hi:
            mid = (hi+lo)//2
            if nums[mid]<target:
                lo = mid + 1
            else:
                hi = mid
        return lo

相关文章

  • 7 - Medium - 搜索范围

    给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。...

  • Missing Ranges

    medium, Array/String Question: 给定范围[0,99]的有序整数序列,范围丢失的范围 ...

  • hadoop学习2

    Linux 的搜索命令 命令:find 任何搜索搜索范围越大占用的资源越多 所以在搜索的时候尽量缩小搜索的范围 语...

  • 搜索需求怎么写

    【散文快写】 搜索前 1、搜索入口在哪里?2、是否需要用户筛选搜索范围;搜索逻辑是否要指定范围; 搜索中 3、 搜...

  • LeetCode | 0098. Validate Binary

    LeetCode 0098. Validate Binary Search Tree验证二叉搜索树【Medium】...

  • leetcode:二分搜索(medium)

    leetcode 33. Search in Rotated Sorted Array Problems: Sup...

  • leetcode_搜索范围

    给定一个按照升序排列的整数数组nums,和一个目标值target。找出给定目标值在数组中的开始位置和结束位置。 你...

  • Geohash之范围搜索

    概述 很多时候,我们都会遇到这样的需求:查找某个点周边多少距离的点。从本质来说,是一个缓冲区分析+空间查找,本文结...

  • 文件搜索命令 find grep

    文件搜索命令 find <非常强大> find 命令 find [搜索范围] [搜索条件] 搜索文件 find /...

  • [译] Twitter的搜索设计,23种潜藏的高级搜索

    最近在设计公司产品的搜索框,对一些产品的搜索模式进行了调研。在Medium上找到一篇关于Twitter搜索的文章,...

网友评论

      本文标题:7 - Medium - 搜索范围

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