LeetCode: Search for a Range

LeetCode: Search for a Range

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

/**
* Created by hzhou on 2015/5/28.
* Email: [email protected]
* <p>
* Given a sorted array of integers, find the starting and ending position of a given target value.
* <p>
* Your algorithm's runtime complexity must be in the order of O(log n).
* <p>
* If the target is not found in the array, return [-1, -1].
* <p>
* For example,
* Given [5, 7, 7, 8, 8, 10] and target value 8,
* return [3, 4].
*/
public class SearchForARange {
public int[] searchRange(int[] nums, int target) {
int[] result = new int[]{-1, -1};
if (nums == null || nums.length == 0 || target < nums[0] || target > nums[nums.length - 1]) {
return result;
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
result[0] = i;
int crt = nums[i];
while (nums[i] == crt) {
i++;
}
result[1] = i - 1;
break;
}
}
return result;
}
}