【LeetCode】34. Find First and Last Position of Element in Sorted Array 解题报告(Python & C++)
作者: 负雪明烛
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++)的更多相关文章
- Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)
本人编程小白,如果有写的不对.或者能更完善的地方请个位批评指正! 这个是leetcode的第34题,这道题的tag是数组,需要用到二分搜索法来解答 34. Find First and Last Po ...
- [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 ...
- [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 ...
- (二分查找 拓展) 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 ...
- [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 ...
- 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 ...
- 刷题34. Find First and Last Position of Element in Sorted Array
一.题目说明 题目是34. Find First and Last Position of Element in Sorted Array,查找一个给定值的起止位置,时间复杂度要求是Olog(n).题 ...
- 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...
- leetcode个人题解——#34 Find First and Last Position of Element in Sorted Array
思路:先二分查找到一个和target相同的元素,然后再左边二分查找左边界,右边二分查找有边界. class Solution { public: , end = -; int ends; int lS ...
随机推荐
- chmod文件权限分配问题
一. 文件(文件夹)的权限问题 一个文件或者文件夹,使用它的人有三类:root.当前用户和其他用户,例如,我们可以通过 ls -l xxx.xxx 来查看文件 "xxx.xxx" ...
- 如何利用官方SDK文件来辅助开发
如何利用官方SDK文件来辅助开发 1.首先要先知道什么是SDK? SDK或者SDK包指的是,半导体厂商针对自己研发的芯片,同步推出的一个软件开发工具包. 它可以简单的为某个程序设计语言提供应用程序接口 ...
- Demo04分解质因数
package 习题集1;import java.util.Scanner;//将一个正整数分解质因数.例如输入90,打印出90=2*3*3*5public class Demo04 { public ...
- MybatisPlus使用Wrapper实现查询功能
Wrapper---条件查询器 :使用它可以实现很多复杂的查询 几个案例 环境: 参照博客:MybatisPlus入门程序 1.条件查询 1.1 查询name不为空的用户,并且邮箱不为空的用户,年龄大 ...
- openwrt编译ipk包提示缺少feeds.mk文件
问题具体表现如下 这个问题困扰了我两个多星期,总算解决了.解决方案如下: 首先,先应该把配置菜单调好. 我的硬件是7620a,要编译的ipk包为helloworld,所以应该使用 make menuc ...
- Java事务与JTA
一.什么是JAVA事务 通俗的理解,事务是一组原子操作单元,从数据库角度说,就是一组SQL指令,要么全部执行成功,若因为某个原因其中一条指令执行有错误,则撤销先前执行过的所有指令.更简答的说就是:要么 ...
- oracle 日期语言格式化
TO_DATE ('17-JUN-87', 'dd-mm-yy', 'NLS_DATE_LANGUAGE = American')
- 【编程思想】【设计模式】【结构模式Structural】组合模式composite
Python版 https://github.com/faif/python-patterns/blob/master/structural/composite.py #!/usr/bin/env p ...
- 使用$.post方式来实现页面的局部刷新功能
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- Apifox(2)快速上手apifox
快速上手 使用场景 Apifox 是接口管理.开发.测试全流程集成工具,使用受众为整个研发技术团队,主要使用者为前端开发.后端开发和测试人员. 前端开发 接口文档管理 接口数据 Mock 接口调试 前 ...