-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_34.java
More file actions
37 lines (30 loc) · 922 Bytes
/
Copy pathLeetCode_34.java
File metadata and controls
37 lines (30 loc) · 922 Bytes
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
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] ans = {-1,-1};
//firstOccurence->
ans[0] = search(nums,target, true);// finding firstIdx = true
if(ans[0] != -1) // lastOccurence->
ans[1] = search(nums,target, false); // finding firstIdx = false;
return ans;
}
int search(int[] nums, int target, boolean isFirstIdx){
int ans = -1;
int start = 0;
int end = nums.length-1;
while(start<=end){
int mid = start + (end- start)/2;
if(target > nums[mid]) start = mid +1;
else if(target < nums[mid]) end = mid -1;
else {
ans = mid;
if(isFirstIdx){
end = mid -1;
}
else{
start = mid+1;
}
}
}
return ans;
}
}