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

题目地址:

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

求长 n n n数组 a a a中出现的第一个和最后一个 x x x的下标。如果不存在则返回两个 − 1 -1 1

寻找数组从左到右第一个大于等于 x x x的数,接着寻找从左到右最后一个小于等于 x x x的数。如果找不到,就返回{-1, -1}。可以用二分法。代码如下:

class Solution {
 public:
  vector<int> searchRange(vector<int>& a, int x) {
    int l = 0, r = (int)a.size() - 1;
    if (l > r) return {-1, -1};
    while (l < r) {
      int mid = l + (r - l >> 1);
      if (a[mid] >= x)
        r = mid;
      else
        l = mid + 1;
    }

    if (a[l] != x) return {-1, -1};
    vector<int> res{l};
    r = (int)a.size() - 1;
    while (l < r) {
      int mid = l + (r - l + 1 >> 1);
      if (a[mid] <= x)
        l = mid;
      else
        r = mid - 1;
    }
    res.push_back(l);
    return res;
  }
};

时间复杂度 O ( log ⁡ n ) O(\log n) O(logn),空间 O ( 1 ) O(1) O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值