数据结构算法操作试题(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 链接 评论区~