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]
解题思路:
既然要实现O(log n)的时间复杂度,应该是会用到二分法。将一个数组从中间切开,分成两部分,左右两边分别实行二分查找。
注意:二分法使用的关键点,在while循环里面需要定义一个可以跳出while循环的判断条件
模板
//二分法模板
while(left<=right) {
mid = (left+right)/2;
if(找到了目标) {
break;
}
if(nums[mid]<target) {
left = mid+1;
}
else {
right = mid-1;
}
}
解题代码:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.size() == 0) return {-1, -1};
int left=0, right=nums.capacity()-1, mid_left=-1, mid_right=-1;
int mid = nums.capacity() / 2;
int left1, right1, left2, right2;
int flag=0;
//divide array into two parts
while(left<=right) {
if(target < nums[mid]) {
right =mid - 1;
mid = (left+right) / 2;
}
else if(target > nums[mid]) {
left = mid + 1;
mid = (left+right) / 2;
}
else {
flag=1;
left1=left, right1=mid;
left2=mid, right2=right;
break;
}
}
if(flag==1) {
//left part
while(left1<=right1) {
mid_left = (left1+right1)/2;
if(nums[mid_left]==target) {
if((mid_left>=1 && nums[mid_left-1]!=target) || (mid_left==0)) {
break;
}
}
if(nums[mid_left]<target) {
left1 = mid_left+1;
}
else {
right1 = mid_left-1;
}
}
//right part
while(left2<=right2) {
mid_right=(left2+right2)/2;
if(nums[mid_right]==target) {
if((mid_right==(nums.capacity()-1)) || (mid_right<(nums.capacity()-1) && nums[mid_right+1]!=target)) {
break;
}
}
if(nums[mid_right]>target) {
right2 = mid_right-1;
}
else {
left2 = mid_right+1;
}
}
return {mid_left, mid_right};
}
return {-1, -1};
}
};