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

Search for a Range

时间:2016-07-05 09:57:57      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

Given a sorted array of n integers, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1].

Example

Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

分析:

用binary search分别找出最左和最右index就可以了。

 1 public class Solution {
 2     /** 
 3      *@param A : an integer sorted array
 4      *@param target :  an integer to be inserted
 5      *return : a list of length 2, [index1, index2]
 6      */
 7     public int[] searchRange(int[] A, int target) {
 8         int[] indexes = new int[2];
 9 
10         if (A == null || A.length <= 0) {
11             indexes[0] = -1;
12             indexes[1] = -1;
13             return indexes;
14         }
15         indexes[0] = getLeftIndex(A, target);
16         indexes[1] = getRightIndex(A, target);
17         return indexes;
18     }
19 
20     public int getLeftIndex(int[] A, int target) {
21         int start = 0;
22         int end = A.length - 1;
23         while (start <= end) {
24             int mid = (start + end) / 2;
25             if (A[mid] == target) {
26                 if (mid == 0 || A[mid] != A[mid - 1]) {
27                     return mid;
28                 } else {
29                     end = mid - 1;
30                 }
31             } else if (A[mid] > target) {
32                 end = mid - 1;
33             } else {
34                 start = mid + 1;
35             }
36         }
37         return -1;
38     }
39 
40     public int getRightIndex(int[] A, int target) {
41         int start = 0;
42         int end = A.length - 1;
43         while (start <= end) {
44             int mid = (start + end) / 2;
45             if (A[mid] == target) {
46                 if (mid == A.length - 1 || A[mid] != A[mid + 1]) {
47                     return mid;
48                 } else {
49                     start = mid + 1;
50                 }
51             } else if (A[mid] > target) {
52                 end = mid - 1;
53             } else {
54                 start = mid + 1;
55             }
56         }
57         return -1;
58     }
59 }

 

Search for a Range

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5642324.html

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