*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  * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
 4  * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
 5  * - 更多详情请见官方网站:http://www.jiuzhang.com/
 6  */
 7 
 8 public class Solution {
 9     public int[] searchRange(int[] A, int target) {
10         int start, end, mid;
11         int[] bound = new int[2]; 
12         
13         // search for left bound
14         start = 0; 
15         end = A.length - 1;
16         while (start + 1 < end) {
17             mid = start + (end - start) / 2;
18             if (A[mid] == target) {
19                 end = mid;     //让右指针right(也就是这里的end)往左边靠拢,也就是找到第一个等于target的数。
20             } else if (A[mid] < target) {
21                 start = mid;
22             } else {
23                 end = mid;
24             }
25         }
26         if (A[start] == target) {
27             bound[0] = start;
28         } else if (A[end] == target) {
29             bound[0] = end;
30         } else {
31             bound[0] = bound[1] = -1;
32             return bound;
33         }
34         
35         // search for right bound
36         start = 0;
37         end = A.length - 1;
38         while (start + 1 < end) {
39             mid = start + (end - start) / 2;
40             if (A[mid] == target) {
41                 start = mid;  //让左指针left(也就是这里的start)往右边靠拢,直到start+1<end,找到最后一个等于target的数。
42             } else if (A[mid] < target) {
43                 start = mid;
44             } else {
45                 end = mid;
46             }
47         }
48         if (A[end] == target) {
49             bound[1] = end;
50         } else if (A[start] == target) {
51             bound[1] = start;
52         } else {
53             bound[0] = bound[1] = -1;
54             return bound;
55         }
56         
57         return bound;
58     }
59 }

 

posted @ 2015-09-24 09:23  Hygeia  阅读(198)  评论(0编辑  收藏  举报