-
Notifications
You must be signed in to change notification settings - Fork 6
/
34. Find First and Last Position of Element in Sorted Array.java
132 lines (111 loc) · 3.14 KB
/
34. Find First and Last Position of Element in Sorted Array.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums is a non-decreasing array.
-109 <= target <= 109
*/
//Solution
class Solution {
public int[] searchRange(int[] arr, int target) {
int[] retarray = {-1, -1};
//check for first occurrence if target first
int start = search(arr,target,true);
int end = search(arr,target,false);
retarray[0] = start;
retarray[1] = end;
return retarray;
}
int search(int[] arr, int target, boolean findStartIndex) {
int ans = -1;
int start = 0;
int end = arr.length - 1;
while (start <= end) {
//int mid = (start + end)/2; //might be possible the start + end exceeds the range of int
//hence it may give to error
//best way to code is
int mid = start + (end - start) / 2;
if (target < arr[mid]) {
end = mid - 1;
} else if (target > arr[mid]) {
start = mid + 1;
} else {
//potential ans found
ans = mid;
if (findStartIndex) {
end = mid - 1;
} else {
start = mid + 1;
}
}
}
return ans;
}
}
//Another Solution:
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] arr = new int[2];
arr[0] = startIndex(nums,target);
arr[1] = endIndex(nums,target);
return arr;
}
public int startIndex(int[] nums,int target){
int start = 0;
int ans = 0;
boolean find = false;
int end = nums.length - 1;
while(start <= end){
int mid = start + (end -start)/2;
if(nums[mid] > target){
end = mid-1;
}else if(nums[mid] < target){
start = mid+1;
}else{
ans = mid;
find = true;
end = mid-1;
}
}
if(find){
return ans;
}else{
return -1;
}
}
public int endIndex(int[] nums,int target){
int start = 0;
int ans = 0;
boolean find = false;
int end = nums.length - 1;
while(start <= end){
int mid = start + (end -start)/2;
if(nums[mid] > target){
end = mid - 1;
}else if(nums[mid] < target){
start = mid + 1;
}else{
ans = mid;
find = true;
start = mid + 1;
}
}
if(find){
return ans;
}else{
return -1;
}
}
}