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

Search for a Range

时间:2015-01-01 17:19:32      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

这道题没什么好说的,二分法查找

class Solution {
public:
	vector<int> range;
    vector<int> searchRange(int A[], int n, int target) {
          range.push_back(-1);
		  range.push_back(-1);
		  if(n == 0)
		  return range;
          int max,min,middle;
		  max = n-1;
		  min =0;
		  middle = (max + min)/2;
		  while(min <= max)
		  {
             if(A[middle] > target)
             {
                 max    = middle -1;
				 middle =  (min + max)/2;
			 }
			 else if(A[middle] < target)
			 {
                 min    = middle + 1;
				 middle =  (min + max)/2;

			 }
			 else 
			 {
                break;
			 }

		  }
          if(A[middle] != target)
		  	return range;
		  min = middle;
		  while(1)
		  {
             if(min - 1 >=0)
             {
                if(A[min-1] != target)
                {
                  break;
				}
				min = min-1;
			 }
			 else
			 {
                 break;
			 }
		  }
		  max = middle;
		  while(1)
		  {
             if(max + 1 <n)
             {
                if(A[max + 1 ] != target)
                {
                  break;
				}
				max = max + 1;
			 }
			 else
			 {
                 break;
			 }
		  }
		  range.clear();
		  range.push_back(min);
		  range.push_back(max);
		  return range;
		
        
    }
  

	
};

  

Search for a Range

标签:

原文地址:http://www.cnblogs.com/xgcode/p/4197349.html

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