本人编程小白,如果有写的不对、或者能更完善的地方请个位批评指正!

这个是leetcode的第34题,这道题的tag是数组,需要用到二分搜索法来解答

34. Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6Output: [-1,-1]

这道题目的难点在于O(log n),看到了O(log n)想到的基本就是二分搜索法,但怎么实现呢?大致有以下两种思路:

方法一:

思路:

先做一遍二分搜索,如果不能找到target的话返回(-1,-1)如果能找到的话然后向左、向右搜索进而找到最小和最大的target,返回index

这种解法的时间复杂度平均是O(log(n)),但当所有在数组中的数字都是一样的并且也都等于target的时候最差是O(n)

Python 代码实现:

class Solution:
def searchRange(self, A, target):
left = 0; right = len(A) - 1
while left <= right:
mid = (left + right) // 2
if A[mid] > target:
right = mid - 1
elif A[mid] < target:
left = mid + 1
else:
list = [0, 0]
if A[left] == target:
list[0] = left
if A[right] == target:
list[1] = right
for i in range(mid, right+1):
if A[i] != target:
list[1] = i - 1; break
for i in range(mid, left-1, -1):
if A[i] != target:
list[0] = i + 1; break
return list
return [-1, -1]

方法二:

思路:

做两遍二分搜索,如果不能找到target的话返回(-1,-1)如果能找到的话第一遍返回最小的index,第二遍返回最大的index,这样的话可以保证在最差的情况下时间复杂度是O(log(n))。

那么这两种二分法的搜索到底怎么实现呢?具体方法见参考文献【1】里面的2.1和2.2。

我们希望实现找到第一个与target相等的元素和最后一个与target相等的元素

(1)找到第一个与target相等的元素,如果没有的话返回-1:

def search_first_target(self, nums, target):
left,right = 0,len(nums)-1
while (left <= right):
mid = (left + right) >> 1
if (nums[mid] >= target): # 注意1
right = mid - 1
else:
left = mid + 1
if nums[left] == target:
return left # 注意2
else:
return -1

(2)找到最后一个与target相等的元素,如果没有的话返回-1:

def search_last_target(self, nums, target):
left,right = 0,len(nums)-1
while (left <= right):
mid = (left + right) >> 1
if (nums[mid] > target): # 注意1
right = mid - 1
else:
left = mid + 1
if nums[right] == target:
return right # 注意2
else:
return -1

最后的实现只是需要把以上两段代码合并到一起即可:

时间复杂度:log(n)

Python 代码实现:

 class Solution(object):
def searchRange(self, nums, target):
l,r = 0, len(nums)-1
left,right = -1,-1
result_left, result_right = -1, -1
while(l <= r):
mid = r+(l-r)//2
if (nums[mid] > target):
r = mid - 1
elif (nums[mid] < target):
l = mid + 1
elif (nums[mid] == target):
r = mid - 1
result_left = nums[mid]
if result_left == target:
left = l
else:
return -1,-1
l,r = 0, len(nums)-1
while(l <= r):
mid = r+(l-r)//2
if (nums[mid] > target):
r = mid - 1
elif(nums[mid] < target):
l = mid + 1
elif(nums[mid] == target):
l = mid + 1
result_right = nums[mid]
if result_right == target:
right = r
return left, right

参考文献:

    1.分析了二分法的不同情况,写的不错:https://www.cnblogs.com/luoxn28/p/5767571.html

     2. http://blog.csdn.net/int64ago/article/details/7425727

Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)的更多相关文章

  1. [LeetCode] 34. Find First and Last Position of Element in Sorted Array == [LintCode] 61. Search for a Range_Easy tag: Binary Search

    Description Given a sorted array of n integers, find the starting and ending position of a given tar ...

  2. [LeetCode] 34. Find First and Last Position of Element in Sorted Array 在有序数组中查找元素的第一个和最后一个位置

    Given an array of integers nums sorted in ascending order, find the starting and ending position of ...

  3. (二分查找 拓展) leetcode 34. Find First and Last Position of Element in Sorted Array && lintcode 61. Search for a Range

    Given an array of integers nums sorted in ascending order, find the starting and ending position of ...

  4. 【LeetCode】34. Find First and Last Position of Element in Sorted Array 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 二分查找 日期 题目地址:https://leetc ...

  5. [leetcode]34.Find First and Last Position of Element in Sorted Array找区间

    Given an array of integers nums sorted in ascending order, find the starting and ending position of ...

  6. leetcode [34] Find First and Last Position of Element in Sorted Array

    Given an array of integers nums sorted in ascending order, find the starting and ending position of ...

  7. 刷题34. Find First and Last Position of Element in Sorted Array

    一.题目说明 题目是34. Find First and Last Position of Element in Sorted Array,查找一个给定值的起止位置,时间复杂度要求是Olog(n).题 ...

  8. leetcode个人题解——#34 Find First and Last Position of Element in Sorted Array

    思路:先二分查找到一个和target相同的元素,然后再左边二分查找左边界,右边二分查找有边界. class Solution { public: , end = -; int ends; int lS ...

  9. 34. Find First and Last Position of Element in Sorted Array + 二分

    题意懒得抄了,大概是:在升序数组中给定整数target,找到第一个和最后一个target的索引,找到返回{index1, index2},否则返回{-1, -1}: 时间复杂度要求:O(logn) 分 ...

随机推荐

  1. JS解决在提交form表单时某个值不存在 alter弹窗点确定不刷新界面

    <form action="" method="post" onsubmit="return checkname()"> < ...

  2. Myeclipse加载php插件

    下载PHPEclipse-1.2.3.200910091456PRD-bin.zip 解压缩后.发现内容包含:两个目录features和plugins,一个xml文件site.xml 全部扔进myec ...

  3. layer弹出层不居中解决方案(转)

    @感谢参考文章 原文内容: 一.问题描述 用layer做操作结果提示时,发现如果页面超出屏幕的高度时,弹出的提示不是屏幕居中,而是在页面高度的中间,如果一个页面的高度比较大,就看不到提示了. 还有一种 ...

  4. 控制请求重复提交的方法总结(Token)

    重复提交的定义: 重复提交指的是同一个请求(请求地址和请求参数都相同)在很短的时间内多次提交至服务器,从而对服务器造成不必要的资源浪费,甚至在代码不健壮的情况还会导致程序出错. 重复提交的原因或触发事 ...

  5. Linux 学习笔记 2:文件系统

    1.文件系统层次结构 系统目录内容: /: 根目录(之后的/都是目录分隔符) /home:用户目录 /bin: Unix常用命令,如bash, date, cat, tar等 /sbin: 管理员命令 ...

  6. apache的.htaccess文件作用和相关配置

    首先.htaccess什么? .htaccess是一个纯文本文件,它里面存放着Apache服务器配置相关的指令. 当我们使用apache部署一个网站代码准备部署到网上的时候,我们手中的apache的h ...

  7. 设计模式学习心得<代理模式 Proxy>

    在代理模式(Proxy Pattern)中,一个类代表另一个类的功能.这种类型的设计模式属于结构型模式. 在代理模式中,我们创建具有现有对象的对象,以便向外界提供功能接口. 概述 意图 为其他对象提供 ...

  8. QTcpSocket 相关知识总结

    1.  连接服务器 m_tcpSocket->connectToHost("127.0.0.1", 9877); connected = m_tcpSocket->wa ...

  9. 内核中的 ACCESS_ONCE()

    参考资料: https://blog.csdn.net/ganggexiongqi/article/details/24603363 这个真特么玄学了...

  10. Go的并发调度原理

    Go语言是为并发而生的语言,Go语言是为数不多的在语言层面实现并发的语言:也正是Go语言的并发特性,吸引了全球无数的开发者.   并发(concurrency)和并行(parallellism) 并发 ...