Znajdź pierwszą i ostatnią pozycję elementu w sortowanej tablicy
class Solution {
public int[] searchRange(int[] array, int target){
int[] index = {-1, -1};
int start = 0;
int end = array.length-1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (array[mid] >= target) end = mid - 1;
else start = mid + 1;
if (array[mid] == target) index[0] = mid;
}
// resetting the start and end
start = 0;
end = array.length-1;
while (start <= end){
int mid = start + (end-start) / 2;
if (array[mid] <= target) start = mid+1;
else end = mid-1;
if (array[mid] == target) index[1] = mid;
}
return index;
}
}
Prabhu Kiran Konda