[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 ...
随机推荐
- Tarjan算法分解强连通分量(附详细参考文章)
Tarjan算法分解强连通分量 算法思路: 算法通过dfs遍历整个连通分量,并在遍历过程中给每个点打上两个记号:一个是时间戳,即首次访问到节点i的时刻,另一个是节点u的某一个祖先被访问的最早时刻. 时 ...
- SpringBoot启动流程及其原理
Spring Boot.Spring MVC 和 Spring 有什么区别? 分别描述各自的特征: Spring 框架就像一个家族,有众多衍生产品例如 boot.security.jpa等等:但他们的 ...
- unicode转换为中文
unicode转换为中文 \u5f53\u5730\u65f6\u95f42019\u5e747\u670813\u65e5\uff0c\u82f1\u56fd\u8d1d\u5fb7\u798f\u ...
- LeetCode 1004. Max Consecutive Ones III
原题链接在这里:https://leetcode.com/problems/max-consecutive-ones-iii/ 题目: Given an array A of 0s and 1s, w ...
- 002_Visual Studio (gnuplot)显示数组波形
视频教程:https://v.qq.com/x/page/e3039v4j6zs.html 资料下载:https://download.csdn.net/download/xiaoguoge11/12 ...
- 如何把上传图片时候的文件对象转换为图片的url !
getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { url = window.createO ...
- 如何调试 Windows 服务
概要 本文分步介绍了如何使用 WinDbg 调试程序 (windbg.exe) 调试 Windows 服务. 要调试 Windows 服务,可以在服务启动后将 WinDbg 调试程序附加到托管该服务的 ...
- 关于新版本cube.js 集成preosto 的一个说明
实际上cubejs cli 是可以使用的,只是官方文档对于dbtype 说明的问题 使用如下命令我们可以创建prestodb 的基本项目 cubejs create -d prestodb myd ...
- pgloader 学习(二)特性矩阵&&命令行
pgloader 对于各种数据库支持的还是很完整的,同时有一套自己的dsl 特性矩阵 操作命令 命令格式 pgloader [<options>] [<command-file> ...
- ELK教程3:logstash的部署、SpringBoot整合ELK+Filebeat
本篇文章主要讲解如下安装Logstash,logstash依赖于Java环境,首先安装Java,安装脚本如下: yum install java logstash安装 Logstash的安装脚本如下: ...