首页 > 其他 > 详细

34. Search for a Range (Array; Divide-and-Conquer)

时间:2015-10-03 13:03:20      阅读:258      评论: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. 相同元素返回最左元素:start总是在<target位置,所以从-1开始
  2. 相同元素返回最右元素:end总是在>target位置,所以从n开始

二者的结束条件都是start+1==end

class Solution {
public:
    vector< int > searchRange(int A[], int n, int target) {
        result.clear();
        binarySearchLeft(A,-1,n,target);
        if(result[0]!=-1) binarySearchRight(A,-1,n,target);
        return result;
    }
    
    void binarySearchLeft(int A[], int start, int end, int target){ //find the first value == target
        if (start+1 == end){
            if(end >= n || A[end]!=target){
                result.push_back(-1);
                result.push_back(-1);
            } 
            else result.push_back(end);
            return;
        }
        
         int mid = start + ((end-start)>>1);
         
         if (A[mid] < target)
             binarySearchLeft(A, mid, end, target);
         else
             binarySearchLeft(A, start, mid, target);      
    }
    
    void binarySearchRight(int A[], int start, int end, int target){ //find the first value == target
        if (start+1 == end){
             result.push_back(start); 
             return;
        }
             
         int mid = start + ((end-start)>>1);
         
         if (A[mid] > target)
             binarySearchRight(A, start, mid, target);
         else
             binarySearchRight(A, mid, end, target);     
    }
private:
    vector< int >  result;
};

 

34. Search for a Range (Array; Divide-and-Conquer)

原文:http://www.cnblogs.com/qionglouyuyu/p/4853217.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!