-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind_First_and_Last.java
More file actions
40 lines (36 loc) · 1.22 KB
/
Find_First_and_Last.java
File metadata and controls
40 lines (36 loc) · 1.22 KB
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
36
37
38
39
40
// Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
// If target is not found in the array, return [-1, -1].
// You must write an algorithm with O(log n) runtime complexity.
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = {-1, -1};
int leftIndex = binarySearch(nums, target, true);
int rightIndex = binarySearch(nums, target, false);
if (leftIndex <= rightIndex) {
result[0] = leftIndex;
result[1] = rightIndex;
}
return result;
}
private int binarySearch(int[] nums, int target, boolean left) {
int low = 0;
int high = nums.length - 1;
int index = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
index = mid;
if (left) {
high = mid - 1;
} else {
low = mid + 1;
}
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return index;
}
}