Leetcode: Search for a 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].

 

思路:

1. 又是二分法

2. 二分法的框架, 需要考虑的位置有 3 个, 在代码中我标了出来, 分别为 q1, q2, q3

3. q1 是取 <= 还是取 <. 我的经验是, 若是题目要求找到 target, 那么就用 <=, 否则用 <. 我记得在二分搜索题时, 都是用 < 的

4. q2 比较容易, 考虑当 low == high 时, 我们希望游标往哪里走

5. q3, 返回 low/high. q3 的选取与 q2 有关. 还是需要考虑当 low == high 时, 游标会往哪走

 

代码

class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
		vector<int> res;
		if(n <= 0)
			return res;

		int leftIndex = lSearch(A, n, target);
		int rightIndex = rSearch(A, n, target);
		
		res.push_back(leftIndex);
		res.push_back(rightIndex);
		return res;
    }

	int lSearch(int A[], int n, int target) {
		int low = 0, high = n-1;
		while(low <= high) { // q1
			int mid = (low+high)>>1;
			if(A[mid] < target) { // q2
				low = mid+1;
			}else{
				high = mid-1;
			}
		}
		if(A[low] != target)
			return -1;
		return low; // q3
	}
	int rSearch(int A[], int n, int target) {
		int low = 0, high = n-1;
		while(low <= high) { // q1
			int mid = (low+high)>>1;
			if(A[mid] > target) { // q2
				high = mid-1;
			}else{
				low = mid +1;
			}
		}
		if(A[high] != target)
			return -1;
		return high; // q3
	}
};

  

posted @ 2014-01-08 16:59  SangS  阅读(1669)  评论(0编辑  收藏  举报