当前位置:网站首页>2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array
2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array
2022-07-07 13:39:00 【weixin_ fifty-one million one hundred and eighty-seven thousand】


1、 The left and right intervals should be searched separately , The time complexity is O ( l o g N ) O(logN) O(logN)
2、 When looking for the right boundary , Shrink left to right ; When looking for the left boundary , The right side shrinks to the left .
class Solution {
public:
int getR(vector<int>& nums, int target){
int l = 0, r = nums.size()-1;
int rightborder = -1;
while (l <= r){
int mid = l + (r - l)/2;
if (nums[mid] == target){
l = mid + 1;
rightborder = mid;
}else if (nums[mid] > target){
r = mid - 1;
}else {
l = mid + 1;
}
}
return rightborder;
}
int getL(vector<int>& nums, int target){
int l = 0, r = nums.size()-1;
int leftborder = -1;
while (l <= r){
int mid = l + (r - l)/2;
if (nums[mid] == target){
r = mid - 1;
leftborder = mid;
}else if (nums[mid] > target){
r = mid - 1;
}else {
l = mid + 1;
}
}
return leftborder;
}
vector<int> searchRange(vector<int>& nums, int target) {
int leftborder = getL(nums, target);
int rightborder = getR(nums, target);
return {
leftborder, rightborder};
}
};
边栏推荐
猜你喜欢

Fast development board pinctrl and GPIO subsystem experiment for itop-imx6ull - modify the device tree file

靠卖概念上市,认养一头牛能走多远?

2022-7-6 Leetcode 977.有序数组的平方

Redis只能做缓存?太out了!

如何让join跑得更快?

Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
![供应链供需预估-[时间序列]](/img/2c/82d118cfbcef4498998298dd3844b1.png)
供应链供需预估-[时间序列]

数据库系统概论-第一章绪论【概念模型、层次模型和三级模式(外模式、模式、内模式)】

LIS longest ascending subsequence problem (dynamic programming, greed + dichotomy)

数字ic设计——SPI
随机推荐
Signal strength (RSSI) knowledge sorting
How far can it go to adopt a cow by selling the concept to the market?
【堡垒机】云堡垒机和普通堡垒机的区别是什么?
[1] Basic knowledge of ros2 - summary version of operation commands
Simple and easy-to-use code specification
QQ的药,腾讯的票
一文读懂数仓中的pg_stat
为租客提供帮助
室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
Build a secure and trusted computing platform based on Kunpeng's native security
我那“不好惹”的00后下属:不差钱,怼领导,抵制加班
Read PG in data warehouse in one article_ stat
Use of polarscatter function in MATLAB
单片机原理期末复习笔记
Write it down once Net a new energy system thread surge analysis
How to make join run faster?
Realize the IP address home display function and number home query
.net core 关于redis的pipeline以及事务
[learning notes] segment tree selection
LeetCode_ Binary search_ Medium_ 153. Find the minimum value in the rotation sort array