欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > Leetcode 34 Find First and Last Position of Element in Sorted Array

Leetcode 34 Find First and Last Position of Element in Sorted Array

2025/2/23 10:30:31 来源:https://blog.csdn.net/xxxmmc/article/details/143623881  浏览:    关键词:Leetcode 34 Find First and Last Position of Element in Sorted Array

题意:找到非严格递增的数组中和target相等的左右边界
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/

解答: 经典二分,找左右边界,要查看l是否满足题意

class Solution {
public:vector<int> searchRange(vector<int>& a, int t) {if (a.empty()) return {-1, -1};int first = findFirst(a, t);int second = findLast(a , t);return {first, second};}int findFirst(vector<int>& a, int t) {int l = 0;int r = a.size() - 1;while (l < r) {int mid = l + (r - l) / 2;if(a[mid] >= t) {r = mid;} else {l = mid + 1;}}return a[l] == t ? l : -1;}int findLast(vector<int>& a, int t) {int l = 0;int r = a.size() - 1;while (l < r) {int mid = l + (r - l) + 1 / 2;if(a[mid] <= t) {l = mid;} else {r = mid - 1;}}return a[l] == t ? l : -1;}};

算法复杂度:O(2logN), N是数组长度,空间复杂度O(1)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词