[leetcode] 34. Search for a Range解題レポート
1474 ワード
タイトルリンク:https://leetcode.com/problems/search-for-a-range/
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
For example, Given
考え方:二分検索で左右の境界を見つければいい.左右の境界を見つければ判断条件を変えればいい.
コードは次のとおりです.
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<int> searchRange(vector<int>& nums, int target) {
int left = 0, len = nums.size(), right = len - 1, index1=-1,index2 = -1;
vector<int> result(2, -1);
while(left <= right)//
{
int mid = (left+right)/2;
if(nums[mid] < target)
left = mid +1;
else
right = mid -1;
}
index1 = left;
right = len -1;
while(left <= right)// targe
{
int mid = (left+right)/2;
if(nums[mid] <= target)
left = mid + 1;
else
right = mid -1;
}
index2 = left -1;
if(nums[index1] != target || nums[index2] != target)// targe,
return result;
result[0] = index1;
result[1] = index2;
return result;
}
};