首页 > 其他 > 详细

(34)Search for a Range

时间:2015-02-08 21:49:43      阅读:297      评论: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 public class SearchForRange {
 2     public static int[] searchRange(int[] A, int target) {
 3         // search for left bound
 4         int start, end, mid;
 5         start = 0;
 6         end = A.length - 1;
 7         int[] bound = new int[2];
 8         while (start + 1 < end) {
 9             mid = start + (end - start) / 2;
10             if (A[mid] == target)
11                 end = mid;
12             else if (A[mid] < target)
13                 start = mid;
14             else
15                 end = mid;
16         }
17 
18         if (A[start] == target)
19             bound[0] = start;
20         else if (A[end] == target)
21             bound[0] = end;
22         else {
23             bound[0] = bound[1] = -1;
24             return bound;
25         }
26 
27         System.out.println("left start:" + start + " end:" + end);
28 
29         // search for right bound
30         start = 0;
31         end = A.length - 1;
32         while (start + 1 < end) {
33             mid = start + (end - start) / 2;
34             if (A[mid] == target)
35                 start = mid;
36             else if (A[mid] < target)
37                 start = mid;
38             else
39                 end = mid;
40         }
41 
42         System.out.println("right start:" + start + " end:" + end);
43                 //important : should judge end firstly
44         if (A[end] == target)
45             bound[1] = end;
46         else if (A[start] == target)
47             bound[1] = start;
48         else {
49             bound[0] = bound[1] = -1;
50             return bound;
51         }
52         return bound;
53     }54 }

https://oj.leetcode.com/problems/search-for-a-range/ 

(34)Search for a Range

原文:http://www.cnblogs.com/luochuanghero/p/4280525.html

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