设为首页 加入收藏

TOP

Search for a Range
2015-07-20 17:23:01 来源: 作者: 【 】 浏览:2
Tags: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:
    int begin = -1, end = -1;
    vector
  
    searchRange(int A[], int n, int target) {
       vector
   
    ans; find(A,0,n-1,target); ans.push_back(begin); ans.push_back(end); return ans; } void find(int A[], int l, int r, int target){ if(l > r) return ; int mid = (l+r) >> 1; if(A[mid] == target){ if(begin == -1 || begin > mid) begin = mid; end = max(mid, end); find(A,l,mid-1,target); find(A,mid+1,r,target); } else if(A[mid] < target) find(A,mid+1,r,target); else find(A,l,mid-1,target); } };
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Uva11988 Broken Keyboard (a.k.a.. 下一篇Dictionary and Array value cann..

评论

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

·MySQL 基础入门视频 (2025-12-26 23:20:22)
·小白入门:MySQL超详 (2025-12-26 23:20:19)
·关于 MySQL 数据库学 (2025-12-26 23:20:16)
·SOLVED: Ubuntu 24.0 (2025-12-26 22:51:53)
·Linux 常用命令最全 (2025-12-26 22:51:50)