Leetcode in Java && Oracle
422 subscribers
8 photos
397 files
400 links
Second channel: @codeforces_java

Let's Develop Together!
Download Telegram
image_2022-08-21_00-15-48.png
66.3 KB
#medium
#N34. Find First and Last Position of Element in Sorted Array
problem link
#solution
class Solution {
public int[] searchRange(int[] nums, int target) {
int res[] = new int[2];
res[0]=first(nums, target);
res[1]=last(nums, target);
return res;
}
public int first(int[] nums, int target){
int idx=-1, l=0, r=nums.length-1, mid;
while(l<=r){
mid=l+(r-l)/2;
if(nums[mid]==target) idx=mid;
if(nums[mid]>=target) r=mid-1;
else l=mid+1;
}
return idx;
}
public int last(int[] nums, int target){
int idx=-1, l=0, r=nums.length-1, mid;
while(l<=r){
mid=l+(r-l)/2;
if(nums[mid]==target) idx=mid;
if(nums[mid]>target) r=mid-1;
else l=mid+1;
}
return idx;
}
}
🔥2👍1