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

Leetcode-Search for a range

时间:2014-11-21 06:57:04      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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].

Have you met this question in a real interview?
 
Analysis:
We need to do two binary search. The first finds out the left boundary and the second finds out the right boundary.
if mid==target, we then check whether mid-1==target, if yes, we then continue to search [start,mid-1] until we find the left boundary.
Solution:
 1 public class Solution {
 2     public int[] searchRange(int[] A, int target) {
 3         int[] res = new int[]{-1,-1};
 4         if (A.length==0) return res;
 5 
 6         int start = 0, end = A.length-1;       
 7       
 8         //Find left range.
 9 
10         while (start<=end){
11             int mid = (start+end)/2;
12             if (A[mid]==target){
13                 //find right range also.
14                 if (mid+1==A.length || A[mid+1]!=target) res[1] = mid;
15                
16                 //Check left
17                 if (mid-1==-1 || A[mid-1]!=target){
18                     res[0]=mid;
19                     break;
20                 } else {
21                     end = mid-1;
22                     continue;
23                 }
24             } else if (A[mid]>target) end = mid-1;
25             else start = mid+1;
26         }
27 
28         if (start>end) return res;
29         if (res[0]!=-1 && res[1]!=-1) return res;
30 
31         //Find right
32         start = 0;
33         end = A.length-1;
34         while (start<=end){
35             int mid = (start+end)/2;
36             if (A[mid]==target){
37                 //Check right
38                 if (mid+1==A.length || A[mid+1]!=target){
39                     res[1]=mid;
40                     break;
41                 } else {
42                     start = mid+1;
43                     continue;
44                 }
45             } else if (A[mid]>target) end = mid-1;
46             else start = mid+1;
47         }
48 
49         return res;        
50     }
51 }

 

Leetcode-Search for a range

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/lishiblog/p/4111920.html

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