-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstAndLastOccurence.java
More file actions
72 lines (69 loc) · 1.87 KB
/
FirstAndLastOccurence.java
File metadata and controls
72 lines (69 loc) · 1.87 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
67
68
69
70
71
72
// 34. Find First and Last Position of Element in Sorted Array
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = {-1, -1};
result[0] = findFirst(nums, target);
result[1] = findLast(nums, target);
return result;
}
private int findFirst(int[] nums, int target){
int left = 0;
int right = nums.length - 1;
int index = -1;
while(left <= right){
int mid = left + (right - left) / 2;
if(nums[mid] >= target){
right = mid - 1;
}else{
left = mid + 1;
}
if(nums[mid] == target){
index = mid;
}
}
return index;
}
private int findLast(int[] nums,int target){
int left = 0;
int right = nums.length - 1;
int index = -1;
while(left <= right){
int mid = left + (right - left) / 2;
if(nums[mid] <= target){
left = mid + 1;
}else{
right = mid - 1;
}
if(nums[mid] == target){
index = mid;
}
}
return index;
}
}
// class Solution {
// public int[] searchRange(int[] nums, int target) {
// int first = -1;
// int last = -1;
// for(int i = 0; i < nums.length; i++){
// if(nums[i] == target){
// if(first == -1){
// first = i;
// }
// last = i;
// }
// }
// int[] result = new int[2];
// if(first == 0){
// result[0] = -1;
// }
// else if(last == 0){
// result[1] = -1;
// }
// else{
// result[0] = first;
// result[1] = last;
// }
// return result;
// }
// }