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

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]


输出某个数的区间

C++:
 1 class Solution {
 2 public:
 3     vector<int> searchRange(vector<int>& nums, int target) {
 4         int first = binarySearch(nums,target) ;
 5         int last = binarySearch(nums,target+1) ;
 6         if (first == nums.size() || nums[first] != target){
 7             return vector<int>(2,-1) ;
 8         }
 9         vector<int> res ;
10         res.push_back(first) ;
11         res.push_back(max(first,last-1)) ;
12         return res ;
13     }
14     
15     int binarySearch(vector<int> nums, int target) {
16         int left = 0 ;
17         int right = nums.size() ;
18         while(left < right){
19             int mid = left + (right - left) / 2 ;
20             if (nums[mid] >= target){
21                 right = mid ;
22             }else{
23                 left = mid + 1 ;
24             }
25         }
26         return left ;
27     }
28 };


原文地址:https://www.cnblogs.com/mengchunchen/p/10333862.html