[Leetcode][Python]34: Search for a Range

本文提供了一种解决LeetCode上搜索范围问题的有效算法。该算法利用二分查找原理,在O(logn)的时间复杂度内找到目标值在有序数组中的起始和结束位置。通过实例演示了如何处理重复元素的情况,确保准确返回目标值的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'

34: Search for a Range
https://oj.leetcode.com/problems/search-for-a-range/

Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

===Comments by Dabay===
二分查找。
当target在中间的时候,往两边扩展。
'''

class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return a list of length 2, [index1, index2]
def searchRange(self, A, target):
def expend(nums, index):
left = right = index
while left - 1 >= 0 and nums[left - 1] == nums[index]:
left -= 1
while right + 1 < len(nums) and nums[right + 1] == nums[index]:
right += 1
return [left, right]

l, r = 0, len(A) - 1
while l <= r:
m = (l + r) /2
if A[m] == target:
return expend(A, m)
elif A[m] < target:
l = m + 1
else:
r = m - 1
else:
return [-1, -1]


def main():
sol = Solution()
nums = [2,2]
target = 2
print sol.searchRange(nums, target)


if __name__ == '__main__':
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)

转载于:https://www.cnblogs.com/Dabay/p/4271401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值