-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
63 lines (45 loc) · 1.57 KB
/
Solution.java
File metadata and controls
63 lines (45 loc) · 1.57 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
/**
@lc id : 34
@problem : Find First and Last Position of Element in Sorted Array
@author : rohit
@url : https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
@difficulty : medium
*/
class Solution {
public int findEndingIndex(int[] nums, int target){
int index = -1;
int start = 0;
int end = nums.length - 1;
while(start <= end){
int mid = start + (end - start) / 2;
if(nums[mid] == target)
index = mid;
if(nums[mid] <= target)
start = mid + 1;
else end = mid - 1;
}
return index;
}
public int findStartingIndex(int[] nums, int target){
int index = -1;
int start = 0;
int end = nums.length - 1;
while(start <= end){
int mid = start + (end - start) / 2;
if(nums[mid] == target)
index = mid;
//If we have found target, still we want to go on left side
//If we haven't found, and target is smaller than mid, go left
if(nums[mid] >= target)
end = mid - 1;
else start = mid + 1;
}
return index;
}
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
result[0] = findStartingIndex(nums, target);
result[1] = findEndingIndex(nums, target);
return result;
}
}