码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Search for a Range

时间:2015-11-05 23:50:51      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:(链接)

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].

解题思路:

二分查找

 1 class Solution {
 2 public:
 3     vector<int> searchRange(vector<int>& nums, int target) {
 4         vector<int> result;
 5         int len = nums.size();
 6         int first = 0;
 7         int last = len - 1;
 8         while (first <= last) {
 9             int mid = first + (last - first) / 2;
10             if (nums[mid] == target) {
11                 int l1 = mid;
12                 int l2 = mid;
13                 while (--l1 >= 0 && nums[l1] == target);
14                 while (++l2 < len && nums[l2] == target);
15                 result.push_back(++l1);
16                 result.push_back(--l2);
17                 break;
18             } else if (target < nums[mid]) {
19                 last = mid - 1;
20             } else {
21                 first = mid + 1;
22             }
23         }
24         
25         if (result.size() == 0) {
26             result.push_back(-1);
27             result.push_back(-1);
28         }
29         
30         return result;
31     }
32 };

 

[LeetCode]Search for a Range

标签:

原文地址:http://www.cnblogs.com/skycore/p/4941164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!