leetcode34. Search for a Range
问题描述:
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]
问题思路:
这道题要求我们找到target在数组中的下标范围,若不存在则返回[-1, -1], 给出的数组为递增数组
考察我们如何判定该坐标为范围开始坐标以及范围结束坐标
注意边界:当target出现在最后一个位置的时候
代码:
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> ret(2,-1); for(int i = 0; i < nums.size(); i++){ if(nums[i] == target){ if(ret[0] == -1){ ret[0] = i; } continue; } if(nums[i] != target && ret[0] != -1 && ret[1] == -1) ret[1] = i-1; } if(ret[0] != -1 && ret[1] == -1){ ret[1] = nums.size() - 1; } return ret; } };