[LeetCode]题解(python):034-Search for a Range
2024-10-14 17:50:11
题目来源
https://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]
.
题意分析
Input: a list and a target(int)
Output: a list with the first index and the last index of target in the input list
Conditions:时间复杂度为0(logn),两个index分别为起始和最后位置
题目思路
本题可采用二分查找的算法,复杂度是0(logn),首先通过二分查找找到taregt出现的某一个位置,然后以这个位置,以及此时的(first,last)来二分查找最左出现的位置和最右出现的位置
PS:注意边界条件
AC代码(Python)
_author_ = "YE"
# -*- coding:utf-8 -*-
class Solution(object):
def findRight(self, nums, first, mid):
if nums[first] == nums[mid]:
return mid
nmid = (first + mid) // 2
if nmid == first:
return first
if nums[nmid] == nums[first]:
return self.findRight(nums, nmid, mid)
else:
return self.findRight(nums,first, nmid) def findLeft(self, nums, mid, last):
if nums[mid] == nums[last]:
return mid
nmid = (mid + last) // 2
if nmid == mid:
return last
if nums[nmid] == nums[last]:
return self.findLeft(nums, mid, nmid)
else:
return self.findLeft(nums,nmid + 1, last) def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
last = len(nums)
first = 0
while first < last:
mid = (first + last) // 2
# print(first,mid,last)
if nums[mid] == target:
# print(self.findLeft(nums,first, mid))
# print(self.findRight(nums,mid,last - 1))
return [self.findLeft(nums,first, mid), self.findRight(nums,mid,last - 1)]
elif nums[mid] < target:
first = mid + 1
else:
last = mid return [-1,-1]
最新文章
- PHP语法
- stray&#39;\241&#39;in program
- 使用supervisor监控进程
- FreeBSD 安裝 Tomcat JAVA JDK1.6 筆記
- spring-boot系列:初试spring-boot
- 不重复查询mysql
- WinForm------自定义YearMonthEdit组件
- TFS2013团队使用纪要
- A start job is running for xxx to stop
- C# 全选中数字文本框内容
- openstack学习(1)
- 第八章:四大组件之Content Provider
- 虚拟机安装centos7
- 精读JavaScript模式(二)
- Linux-(touch,cat,nl,more|less,head|tail)
- Informatica 常用组件Lookup缓存之五 使用动态查找高速缓存
- 棒谷科技java岗笔试题与初试题
- Kafka的架构设计(目前翻译最好的一稿)
- ES6编程规范
- [BZOJ 3108] 图的逆变换