aboutsummaryrefslogtreecommitdiff
path: root/trim_binary_tree.cpp
blob: 3f4168a0120aa00a1602cb61e4b694613c13a13e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "leetcode.h"

class Solution {
public:
  vector<int> searchRange(vector<int> &nums, int target) {
    int s = 0, e = nums.size() - 1;
    vector<int> ans(2, -1);
    // first position
    while (s <= e) {
      int m = s + (e - s) / 2;
      if (nums[m] < target)
        s = m + 1;
      else if (nums[m] > target)
        e = m - 1;
      else {
        if (m == s || nums[m] != nums[m - 1]) {
          ans[0] = m;
          break;
        } else {
          e = m - 1;
          ans[0] = m - 1;
        }
      }
    }
    // second position
    s = 0, e = nums.size() - 1;
    while (s <= e) {
      int m = s + (e - s) / 2;
      if (nums[m] < target)
        s = m + 1;
      else if (nums[m] > target)
        e = m - 1;
      else {
        if (m == e || nums[m] != nums[m + 1]) {
          ans[1] = m;
          break;
        } else {
          s = m + 1;
          ans[1] = m + 1;
        }
      }
    }
    return ans;
  }
};

int main() {}