作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/

题目描述

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 = 8
Output: [3,4]

Example 2:

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

题目大意

在一个数组中,找出某个target值开始的最左边和最右边的索引,如果target不存在,那么就返回[-1, -1]。

解题方法

二分查找

本来见到这个题,第一感觉肯定就是二分查找左右区间,并且题目很明显的说了O(logn)的时间复杂度,那么明显就是要求使用二分。

题目要求找到开始的索引和结束索引,所以就是C++的lower_bound和upper_bound。代码我觉得应该是要背下来的,这两个函数只有一点不同,就是nums[mid]与target的判断,lower_bound倾向于找左边的元素,所以只有nums[mid] < target时才移动左指针;而upper_bound倾向于找右边的元素,所以当nums[mid] <= target就向右移动左指针了。

lower_bound返回的是开始的第一个满足条件的位置,而upper_bound返回的是第一个不满足条件的位置。所以,当两个相等的时候代表没有找到,如果找到了的话,需要返回的是[left, right - 1].

时间复杂度是O(logn),空间复杂度是O(1).超过了100%的提交。

class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left = self.lowwer_bound(nums, target)
right = self.higher_bound(nums, target)
if left == right:
return [-1, -1]
return [left, right - 1] def lowwer_bound(self, nums, target):
# find in range [left, right)
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) / 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
return left def higher_bound(self, nums, target):
# find in range [left, right)
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) / 2
if nums[mid] <= target:
left = mid + 1
else:
right = mid
return left

其实,在python中有封装好的二分查找模块,就是bisect模块。我第一个提交就是使用这个模块快速写出来提交的,如果是比赛的话尽量用别人封装好的。

时间复杂度是O(logn),空间复杂度是O(1).超过了100%的提交。

class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left = bisect.bisect_left(nums, target)
right = bisect.bisect_right(nums, target)
if left == right:
return [-1, -1]
return [left, right - 1]

C++代码自己手写lower_bound和upper_bound函数如下:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int low = lower_bound(nums, target);
int high = upper_bound(nums, target);
if (low == high)
return {-1, -1};
else
return {low, high - 1};
}
int lower_bound(vector<int>& nums, int target) {
const int N = nums.size();
// [l, r)
int l = 0, r = N;
while (l < r) {
int mid = l + (r - l) / 2;
if (nums[mid] >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
int upper_bound(vector<int>& nums, int target) {
const int N = nums.size();
// [l, r)
int l = 0, r = N;
while (l < r) {
int mid = l + (r - l) / 2;
if (nums[mid] <= target) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}
};

C++代码使用lower_bound()和upper_bound()函数的代码如下:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto low = lower_bound(nums.begin(), nums.end(), target);
auto high = upper_bound(nums.begin(), nums.end(), target);
if (low == high) return {-1, -1};
return {low - nums.begin(), high - nums.begin() - 1};
}
};

日期

2018 年 10 月 21 日 —— 新的一周又开始了
2019 年 1 月 11 日 —— 小光棍节?

【LeetCode】34. Find First and Last Position of Element in Sorted Array 解题报告(Python & C++)的更多相关文章

  1. Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)

    本人编程小白,如果有写的不对.或者能更完善的地方请个位批评指正! 这个是leetcode的第34题,这道题的tag是数组,需要用到二分搜索法来解答 34. Find First and Last Po ...

  2. [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 ...

  3. [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 ...

  4. (二分查找 拓展) 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 ...

  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】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

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

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

随机推荐

  1. windows和linux文本的编码格式不一样所出的错

    windows下编写的python脚本上传的linux下执行会出现错误: usr/bin/python^M: bad interpreter: No such file or directory 原因 ...

  2. docker 使用加速器下载

    因为docker官网的镜像地址docker.hum.com是在国外的 所以下载速度比较慢,国内有一些镜像源是比较快的,内容是和docker官网的一致 常用的加速器有 docker-cn 阿里云加速器 ...

  3. Scrapy爬虫框架的安装和使用

    Scrapy是一个十分强大的爬虫框架,依赖的库比较多,至少需要依赖的库有Twisted 14.0.lxml 3.4和pyOpenSSL 0.14.在不同的平台环境下,它所依赖的库也各不相同,所以在安装 ...

  4. UE4 C++工程以Game模式启动

    UE4版本:4.24.3源码编译版本 Windows10 + VS2019环境 UE4 C++工程,默认情况下VS中直接运行是启动Editor模式: 有时为了调试等目的需要以Game模式启动,可以避免 ...

  5. HTML 基本标签2

    HTML标题通过<h1>-<h6>标签定义(<h1>定义最大的标题,<h6>定义最小的标题) <html>用于定义HTML文档 HTML段落 ...

  6. accent, accept

    accent A colon (:) is used to represent a long vowel, e.g. sheet /ʃiːt/ and shit /ʃit/. The word bed ...

  7. Java Swing布局管理器GridBagLayout的使用示例 [转]

    GridBagLayout是java里面最重要的布局管理器之一,可以做出很复杂的布局,可以说GridBagLayout是必须要学好的的, GridBagLayout 类是一个灵活的布局管理器,它不要求 ...

  8. soapui pro 5.1.2 的破解方法

    Protection-4.6,和scz.key这两个文件能破解5.1.2的SoapUI 的Pro版本,mac 和 windows均可.1.拷贝Protection-4.6.jar到soapui安装的l ...

  9. SpringBoot+MybatisPlus实现批量添加的两种方式

    第一种: 因为Mysql数据每次发送sql语句的长度不能超过1M,所以,每次发送insert语句以固定长度发送: 将sql语句在provider中,以固定长度装入List集合中,然后返回service ...

  10. 【力扣】剑指 Offer 50. 第一个只出现一次的字符

    在字符串 s 中找出第一个只出现一次的字符.如果没有,返回一个单空格. s 只包含小写字母. 示例: s = "abaccdeff"返回 "b" s = &qu ...