python 取数组最后一个_34.leetcode题目讲解(Python):在排序数组中查找元素的第一个和最后一个位置...

题目如下:

题目

比较简单的一道题,由于输入数据是升序的,所以解题可以采用双指针的方法,参考代码如下:

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

其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]

(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建议,欢迎交流 :-D,

也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值