本文共 1009 字,大约阅读时间需要 3 分钟。
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]
.
class Solution {public: vector searchRange(int A[], int n, int target) { vector re(2, -1); if(n == 0) return re; int low = 0; int high = n - 1; while(low <= high) { int mid = (low + high) >> 1; if(A[mid] == target) { low = mid; while(low - 1>= 0 && A[low - 1] == target) --low; while(mid + 1 <= high && A[mid + 1] == target) ++mid; re[0] = low; re[1] = mid; return re; } else if(A[mid] < target) low = mid + 1; else high = mid - 1; } return re; }};找到这个值,则向左右延伸到其边界。
转载地址:http://relji.baihongyu.com/