题目描述:

Given an array of integers 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].

For example,

Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

解题思路:

这题我用的方法比较笨:从两端搜索数组,两个都是target数才跳出。具体的就看代码吧。

代码:

 1 class Solution {
 2 public:
 3     vector<int> searchRange(vector<int>& nums, int target) {
 4         int left = 0, right = nums.size()-1;
 5         vector<int> ret = {-1, -1};
 6         while(right >= left){
 7             if(nums[right] == nums[left] && nums[left] == target){
 8                 ret[0] = left;
 9                 ret[1] = right;
10                 break;
11             }
12             if(nums[left] != target)
13                 left++;
14             if(nums[right] != target)
15                 right--;
16         }
17         return ret;
18     }
19 };

 

 

 

posted on 2018-02-27 23:16  宵夜在哪  阅读(97)  评论(0编辑  收藏  举报