数据结构算法操作试题(C++/Python)——在排序数组中查找元素的第一个和最后一个位置

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)——在排序数组中查找元素的第一个和最后一个位置,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录


1. 题目

leetcode 链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

2. 解答

python: 28ms, 12mb, 100%

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        left = 0
        right = len(nums) - 1
        equalIndex = -1
        while left <= right:
            midIndex = (left + right) / 2
            if nums[midIndex] == target: 
                equalIndex = midIndex
                break
            elif target < nums[midIndex]: right = midIndex - 1
            elif target > nums[midIndex]: left = midIndex + 1
        if equalIndex == -1: return [-1, -1]
        else:
            return self.getIndexList(nums, equalIndex)
        
    def getIndexList(self, nums, index):
        retIndexList = [0, len(nums) - 1]
        for i in range(index - 1, -1, -1):
            if nums[i] != nums[index]:
                retIndexList[0] = i + 1
                break
        for i in range(index + 1, len(nums)):
            if nums[i] != nums[index]:
                retIndexList[1] = i - 1
                break
        return retIndexList

其他方法看 leetcode 链接 评论区~