Leetcode 34 Find First and Last Position of Element in Sorted Array | Binary Search Decoded

preview_player
Показать описание
Here is the solution to "Find First and Last Position of Element in Sorted Array" leetcode question. Hope you have a great time going through it.

💯💯 Best Technical Resume Template for College Students For Jobs & Internships

Check this out 🔽🔽🔽🔽

🔴 Connect with me here:

🔥🔥🔥🔥👇👇👇 For discussion/feedback/humour/doubts/new openings

👉 Solutions

🔥🔥🔥🔥👇👇👇 For discussion/feedback/humour/doubts/new openings

🔴 Checkout the series: 🔥🔥🔥

🔥🔥🔥 Leetcode Monthly Contest Playlist

Рекомендации по теме
Комментарии
Автор

class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[]{-1, -1};

int first = findFirst( nums, target);
int last = findLast( nums, target);

if(first!=-1 && last!=-1){
res[0]=first;
res[1]=last;
}

return res;
}



public int findFirst(int[] nums, int target){

// simple Binary Search code
int left=0, right=nums.length-1;
int res=-1;

while(left<=right){

int mid = left + (right-left)/2;

if(nums[mid]==target){
res = mid;
//continue BS in left dir
right = mid-1;
}

else if(nums[mid]>target){
right=mid-1;
}

else{
left = mid+1;
}

}

return res;

}

public int findLast(int[] nums, int target){

// simple BS code
int left=0, right=nums.length-1;
int res=-1;

while(left<=right){

int mid = left + (right-left)/2;

if(nums[mid]==target){
res = mid;
//continue BS in right dir
left = mid+1;
}

else if(nums[mid]>target){
right=mid-1;
}

else{
left = mid+1;
}

}

return res;

}

}

JameS
join shbcf.ru