forked from super30admin/Binary-Search-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem1.java
More file actions
67 lines (56 loc) · 2.18 KB
/
Copy pathProblem1.java
File metadata and controls
67 lines (56 loc) · 2.18 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
// Time Complexity : O(log n) where n is the number of elements in the input array;
// Space Complexity : O(1);
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
/**
* Approach : We will use binary search to find the first and last positions of the target element in the input array.
* We will first find the first occurrence of the target element using binary search.
* Then we will find the last occurrence of the target element using binary search.
* We will return the first and last positions of the target element in the input array.
*/
class Solution {
public int[] searchRange(int[] nums, int target) {
int first = binarySearchFirst(nums, target, 0, nums.length - 1);
if (first == -1)
return new int[] { -1, -1 };
int last = binarySearchLast(nums, target, first, nums.length - 1);
return new int[] { first, last };
}
private int binarySearchFirst(int[] nums, int target, int low, int high) {
int mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (target == nums[mid]) {
if (mid == 0 || nums[mid - 1] != target) {
return mid;
} else {
high = mid - 1;
}
} else if (target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
private int binarySearchLast(int[] nums, int target, int low, int high) {
int mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (target == nums[mid]) {
if (mid == nums.length -1 || nums[mid + 1] != target) {
return mid;
} else {
low = mid + 1;
}
} else if (target < nums[mid]) {
high = mid - 1;
} else {
low = mid +1;
}
}
return -1;
}
}