forked from super30admin/Binary-Search-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirstAndLastInSortedArray.java
57 lines (54 loc) · 1.79 KB
/
FirstAndLastInSortedArray.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Time Complexity :O(logn)
// Space Complexity :O(1)
// Did this code successfully run on Leetcode :Yes
// Any problem you faced while coding this :
class Solution {
public int[] searchRange(int[] nums, int target) {
int n = nums.length;
int low = 0;
int high = n - 1;
if (nums == null || n == 0)
return new int[] { -1, -1 };
if (target < nums[0] || target > nums[n - 1])
return new int[] { -1, -1 };
int firstIndex = binarySearchFirst(nums, low, high, target);
if (firstIndex == -1)
return new int[] { -1, -1 };
int lastIndex = binarySearchLast(nums, firstIndex, high, target);
return new int[] { firstIndex, lastIndex };
}
private int binarySearchFirst(int[] nums, int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
if (mid == 0 || nums[mid] != nums[mid - 1]) {
return mid;
} else {
high = mid - 1;
}
} else if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
private int binarySearchLast(int[] nums, int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
if (mid == high || nums[mid] != nums[mid + 1]) {
return mid;
} else {
low = mid + 1;
}
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}