Given a sorted array of integers, 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
题意:
给定一个有序数组,其中可能包含一些重复数字,给定一个数字,求其第一次和最后一次出现的坐标,要求 O(log n)。
思路:
有序数组+ O(log n),很显然二分搜索啦。
C++:
1 class Solution { 2 public: 3 4 int Bsearch(vector<int>& nums, int len, int start, int end, int tar, bool flag) 5 { 6 if(start > end) 7 return -1; 8 9 int mid = (start + end) / 2; 10 11 if(nums[mid] == tar) 12 { 13 if(flag) 14 { 15 if((mid > 0 && nums[mid - 1] != tar) || mid == 0) 16 { 17 return mid; 18 } 19 else 20 { 21 return Bsearch(nums, len, start, mid - 1, tar, flag); 22 } 23 } 24 else 25 { 26 if((mid < len - 1 && nums[mid + 1] != tar) || mid == len - 1) 27 { 28 return mid; 29 } 30 else 31 { 32 return Bsearch(nums, len, mid + 1, end, tar, flag); 33 } 34 } 35 36 } 37 else if(nums[mid] < tar) 38 { 39 return Bsearch(nums, len, mid + 1, end, tar, flag); 40 } 41 else 42 { 43 return Bsearch(nums, len, start, mid - 1, tar, flag); 44 } 45 } 46 47 vector<int> searchRange(vector<int>& nums, int target) { 48 49 int len = nums.size(); 50 vector<int> ret; 51 if(len == 0) 52 return ret; 53 54 ret.push_back(Bsearch(nums, len, 0, len - 1, target, true)); 55 ret.push_back(Bsearch(nums, len, 0, len - 1, target, false)); 56 57 return ret; 58 } 59 };
时间: 2024-11-02 13:06:59