题目如下:

比较简单的一道题,由于输入数据是升序的,所以解题可以采用双指针的方法,参考代码如下:
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
le = len(nums)
if le == 0:
return [-1, -1]
left = 0
right = le - 1
res = [-1, -1]
lflag = True
rflag = True
while left < le and right >= 0:
if left <= right:
if nums[left] == target and lflag:
res[0] = left
lflag = False
elif lflag:
if left + 1 < le:
left = left + 1
else:
return res
if nums[right] == target and rflag:
res[1] = right
rflag = False
elif rflag:
if right - 1 >= 0:
right = right - 1
else:
return res
if not rflag and not lflag:
return res
else:
return res
源码地址:
https://github.com/jediL/LeetCodeByPython
其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)
ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)
网友评论