[LeetCode] 34. Search for a Range 搜索一个范围(Find First and Last Position of Element in Sorted Array)
原题目:Search for a Range, 现在题目改为: 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 = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
给一个有序整数数组中,寻找相同目标值的起始和结束位置,限定了时间复杂度为O(logn)。
解法:二分法,典型的二分查找法的时间复杂度,先对原数组使用二分查找法,找出其中一个目标值的位置,然后向两边搜索找出起始和结束的位置。
Java:
public class Solution {
public int[] searchRange(int[] A, int target) {
int start = Solution.firstGreaterEqual(A, target);
if (start == A.length || A[start] != target) {
return new int[]{-1, -1};
}
return new int[]{start, Solution.firstGreaterEqual(A, target + 1) - 1};
} //find the first number that is greater than or equal to target.
//could return A.length if target is greater than A[A.length-1].
//actually this is the same as lower_bound in C++ STL.
private static int firstGreaterEqual(int[] A, int target) {
int low = 0, high = A.length;
while (low < high) {
int mid = low + ((high - low) >> 1);
//low <= mid < high
if (A[mid] < target) {
low = mid + 1;
} else {
//should not be mid-1 when A[mid]==target.
//could be mid even if A[mid]>target because mid<high.
high = mid;
}
}
return low;
}
}
Python:
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# Find the first idx where nums[idx] >= target
left = self.binarySearch(lambda x, y: x >= y, nums, target)
if left >= len(nums) or nums[left] != target:
return [-1, -1]
# Find the first idx where nums[idx] > target
right = self.binarySearch(lambda x, y: x > y, nums, target)
return [left, right - 1] def binarySearch(self, compare, nums, target):
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid
else:
left = mid + 1
return left def binarySearch2(self, compare, nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid - 1
else:
left = mid + 1
return left def binarySearch3(self, compare, nums, target):
left, right = -1, len(nums)
while left + 1 < right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid
else:
left = mid
return left if left != -1 and compare(nums[left], target) else right
C++:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
const auto start = lower_bound(nums.cbegin(), nums.cend(), target);
const auto end = upper_bound(nums.cbegin(), nums.cend(), target);
if (start != nums.cend() && *start == target) {
return {start - nums.cbegin(), end - nums.cbegin() - 1};
}
return {-1, -1};
}
}; class Solution2 {
public:
vector<int> searchRange(vector<int> &nums, int target) {
const int begin = lower_bound(nums, target);
const int end = upper_bound(nums, target); if (begin < nums.size() && nums[begin] == target) {
return {begin, end - 1};
} return {-1, -1};
} private:
int lower_bound(vector<int> &nums, int target) {
int left = 0;
int right = nums.size();
// Find min left s.t. A[left] >= target.
while (left < right) {
const auto mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
} int upper_bound(vector<int> &nums, int target) {
int left = 0;
int right = nums.size();
// Find min left s.t. A[left] > target.
while (left < right) {
const auto mid = left + (right - left) / 2;
if (nums[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 34. Search for a Range 搜索一个范围(Find First and Last Position of Element in Sorted Array)的更多相关文章
- [Swift]LeetCode34. 在排序数组中查找元素的第一个和最后一个位置 | 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 ...
- [array] leetcode - 34. Search for a Range - Medium
leetcode - 34. Search for a Range - Medium descrition Given an array of integers sorted in ascending ...
- Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)
本人编程小白,如果有写的不对.或者能更完善的地方请个位批评指正! 这个是leetcode的第34题,这道题的tag是数组,需要用到二分搜索法来解答 34. Find First and Last Po ...
- 乘风破浪:LeetCode真题_034_Find First and Last Position of Element in Sorted Array
乘风破浪:LeetCode真题_034_Find First and Last Position of Element in Sorted Array 一.前言 这次我们还是要改造二分搜索,但是想法却 ...
- Find First and Last Position of Element in Sorted Array - LeetCode
目录 题目链接 注意点 解法 小结 题目链接 Find First and Last Position of Element in Sorted Array - LeetCode 注意点 nums可能 ...
- 刷题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] 74. Search a 2D Matrix 搜索一个二维矩阵
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
Search for a Range Given a sorted array of integers, find the starting and ending position of a give ...
- leetcode@ [34] Search for a Range (STL Binary Search)
https://leetcode.com/problems/search-for-a-range/ Given a sorted array of integers, find the startin ...
随机推荐
- P5431 【【模板】乘法逆元2】
卡常毒瘤题.交了一页的我. 首先容易想出暴力的做法,直接逆元累加,复杂度\(O(nlogn)\). for(register int i=1;i<=n;++i){ ll a=read(); an ...
- [转] C++ explicit关键字详解
本文转自tiankong19999 首先, C++中的explicit关键字只能用于修饰只有一个参数的类构造函数, 它的作用是表明该构造函数是显示的, 而非隐式的, 跟它相对应的另一个关键字是impl ...
- less-4
首先来了解语句构造方法: 输入id=1’显示正确,输入id=1”显示错误(如下图),可以看到后面有个),说明这里跟前面less-3一样,也是用)来闭合,只不过这里从单引号变成了双引号 输入id=1”) ...
- 15-Flutter移动电商实战-商品推荐区域制作
1.推荐商品类的编写 这个类接收一个List参数,就是推荐商品的列表,这个列表是可以左右滚动的. /*商品推荐*/class Recommend extends StatelessWidget { ...
- centos7最小化安装无法tab补全
yum install -y bash-completion 安装完后reboot重启生效
- 封装原生promise函数
阿里面试题: 手动封装promise函数 <!DOCTYPE html> <html lang="en"> <head> <meta ch ...
- vue 项目的文件/文件夹上传下载
前言:因自己负责的项目(jetty内嵌启动的SpringMvc)中需要实现文件上传,而自己对java文件上传这一块未接触过,且对 Http 协议较模糊,故这次采用渐进的方式来学习文件上传的原理与实践. ...
- THUWC2020 划船记
PS:THUWC2020在2019年 Day 1 考场外的太懒了不写了. 三题题目大意: T1: T2: 给定一个\(n(\leq 10^5)\)个结点的有向图,每条边有个limit,表示经过这条边l ...
- 使用css3变量创建炫酷悬停效果
原文地址:www.zcfy.cc/article/stunning-hover-effects-with-css-variables 效果: 主要使用css中的var做动画效果,代码如下: <! ...
- CSP内容安全策略总结及如何抵御 XSS 攻击
跨域脚本攻击 XSS 是最常见.危害最大的网页安全漏洞.为了防止它们,要采取很多编程措施,非常麻烦.很多人提出,能不能根本上解决问题,浏览器自动禁止外部注入恶意脚本?这就是"网页安全政策&q ...