设为首页 加入收藏

TOP

leetcode――Search for a Range 排序数组中寻找目标下标范围(AC)
2015-11-21 02:03:12 来源: 作者: 【 】 浏览:6
Tags:leetcode Search for 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 [-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) {
        assert(A!=NULL && n!=0);
        vector
   
     result; int start = 0, end = n-1, mid; while(start <= end) { mid = (start+end)/2; if(A[mid] == target) { while(mid>=0 && A[mid]==target) mid--; result.push_back(++mid); while(mid<=n-1 && A[mid]==target) mid++; result.push_back(--mid); return result; } else if(A[mid] < target) start = mid+1; else end = mid-1; } result.push_back(-1); result.push_back(-1); return result; } };
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇编程趣味题3 下一篇poj3249 Test for Job --- 拓扑排..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: