【题目】
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]
.
【题意】
给定一个有序数组,其中包含重复数值。给定一个目标target, 返回第一个target值和最后一个target值出现的索引位置。时间复杂度保证O(logn)
【思路】
使用二分查找,分别确定第一个和最后一个的位置。
【代码】
class Solution { public: //获得第一个值的位置 int getFirst(int A[], int n, int target){ int low=0, high=n-1; while(low<=high){ int mid=(low+high)/2; if(A[mid]==target){ if(mid==0||A[mid-1]!=A[mid])return mid; else high=mid-1; } else if(target<A[mid])high=mid-1; else low=mid+1; } return -1; } //获得最后一个值的位置 int getLast(int A[], int n, int target){ int low=0, high=n-1; while(low<=high){ int mid=(low+high)/2; if(A[mid]==target){ if(mid==n-1||A[mid+1]!=A[mid])return mid; else low=mid+1; } else if(target<A[mid])high=mid-1; else low=mid+1; } return -1; } vector<int> searchRange(int A[], int n, int target) { vector<int> result(2, -1); if(n==0)return result; result[0]=getFirst(A, n, target); result[1]=getLast(A, n, target); return result; } };
LeetCode: Search for a Range [033],布布扣,bubuko.com
时间: 2024-11-05 11:24:36