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

源码地址:
https://github.com/jediL/LeetCodeByPython

其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容