当前位置:网站首页>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};
}
};
边栏推荐
- Leecode3. Longest substring without repeated characters
- 提升树莓派性能的方法
- 室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
- Introduce six open source protocols in detail (instructions for programmers)
- QQ medicine, Tencent ticket
- Detr introduction
- Esp32 construction engineering add components
- Shell batch file name (excluding extension) lowercase to uppercase
- 记一次 .NET 某新能源系统 线程疯涨 分析
- LeetCode简单题分享(20)
猜你喜欢
随机推荐
信号强度(RSSI)知识整理
User management summary of mongodb
move base参数解析及经验总结
Esp32 series column
为租客提供帮助
How did Guotai Junan Securities open an account? Is it safe to open an account?
Scripy tutorial classic practice [New Concept English]
Learning breakout 2 - about effective learning methods
Mongodb meets spark (for integration)
Mongodb replication (replica set) summary
MongoDB的导入导出、备份恢复总结
一文读懂数仓中的pg_stat
clion mingw64中文乱码
"New red flag Cup" desktop application creativity competition 2022
Xshell connection server changes key login to password login
Pcap learning notes II: pcap4j source code Notes
我那“不好惹”的00后下属:不差钱,怼领导,抵制加班
室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
Read PG in data warehouse in one article_ stat
Mongodb slice summary