题目来源


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]

最新文章

  1. PHP语法
  2. stray&#39;\241&#39;in program
  3. 使用supervisor监控进程
  4. FreeBSD 安裝 Tomcat JAVA JDK1.6 筆記
  5. spring-boot系列:初试spring-boot
  6. 不重复查询mysql
  7. WinForm------自定义YearMonthEdit组件
  8. TFS2013团队使用纪要
  9. A start job is running for xxx to stop
  10. C# 全选中数字文本框内容
  11. openstack学习(1)
  12. 第八章:四大组件之Content Provider
  13. 虚拟机安装centos7
  14. 精读JavaScript模式(二)
  15. Linux-(touch,cat,nl,more|less,head|tail)
  16. Informatica 常用组件Lookup缓存之五 使用动态查找高速缓存
  17. 棒谷科技java岗笔试题与初试题
  18. Kafka的架构设计(目前翻译最好的一稿)
  19. ES6编程规范
  20. [BZOJ 3108] 图的逆变换

热门文章

  1. CentOS6.4 配置HAProxy+Keepalived
  2. 【BZOJ】1008: [HNOI2008]越狱(快速幂)
  3. UOJ#61. 【UR #5】怎样更有力气
  4. java向图片上写字,两个图片合并的方法
  5. zabbix自定义键值原理
  6. 转载:hdu 动态规划题集
  7. 你们以为运营商只是HTTP插点广告而已么?
  8. Sql Group by 使用
  9. PHP 中和 HTTP 相关的函数及使用
  10. Nginx 笔记与总结(5)访问日志管理:计划任务 + 日志切割