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 SearchforaRange {
2 public int[] searchRange(int[] A, int target) {
3 int low = findLow(A, target, 0, A.length - 1);
4 int high = findHigh(A, target, 0, A.length - 1);
5 int[] ret = new int[2];
6 ret[0] = low;
7 ret[1] = high;
8 return ret;
9 }
10
11 private int findLow(int[] A, int target, int l, int r) {
12 int mid = 0;
13 int ret = -1;
14 while (l <= r) {
15 mid = (l + r) / 2;
16 if (A[mid] == target) {
17 ret = mid;
18 int next = findLow(A, target, l, mid - 1);
19 if (next != -1) {
20 ret = next;
21 }
22 break;
23 } else if (A[mid] < target) {
24 l = mid + 1;
25 } else {
26 r = mid - 1;
27 }
28
29 }
30 return ret;
31 }
32
33 private int findHigh(int[] A, int target, int l, int r) {
34 int mid = 0;
35 int ret = -1;
36 while (l <= r) {
37 mid = (l + r) / 2;
38 if (A[mid] == target) {
39 ret = mid;
40 int next = findHigh(A, target, mid + 1, r);
41 if (next != -1) {
42 ret = next;
43 }
44 break;
45 } else if (A[mid] < target) {
46 l = mid + 1;
47 } else {
48 r = mid - 1;
49 }
50 }
51 return ret;
52 }
53 }
非递归解法:以寻找左边界为例,这个解法的思路就是一直向左进行二分查找,直到找到最左的目标元素或者最左的目标元素的下一个元素。因此,二分查找结束之后,需要判断找到的元素到底是目标元素还是他的第一个不满足的元素,然后根据情况返回下标。代码实现如下:
1 public class Solution {
2 public int[] searchRange(int[] A, int target) {
3 int left = findLeft(A, target);
4 int right = findRight(A, target);
5 return new int[] { left, right };
6 }
7
8 private int findLeft(int[] A, int target) {
9 int i = 0, j = A.length - 1;
10 while (i < j) {
11 int mid = (i + j) / 2;
12 if (A[mid] < target) {
13 i = mid + 1;
14 } else {
15 j = mid - 1;
16 }
17 }
18 if (A[i] == target) return i;
19 if (i < A.length - 1 && A[i + 1] == target) return i + 1;
20 return -1;
21 }
22
23 private int findRight(int[] A, int target) {
24 int i = 0, j = A.length - 1;
25 while (i < j) {
26 int mid = (i + j) / 2;
27 if (A[mid] > target) {
28 j = mid - 1;
29 } else {
30 i = mid + 1;
31 }
32 }
33 if (j >= 0 && A[j] == target)
34 return j;
35 if (j > 0 && A[j - 1] == target)
36 return j - 1;
37 return -1;
38 }
39 }