1. 程式人生 > >LeetCode 34. 在排序陣列中查詢元素的第一個和最後一個位置 python

LeetCode 34. 在排序陣列中查詢元素的第一個和最後一個位置 python

給定一個按照升序排列的整數陣列 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(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
try: start = nums.index(target) except: start = -1 end = nums.index(target)+nums.count(target)-1 if start >=0 else -1 return [start,end]