Find First and Last Position of Element in Sorted Array
class Solution {
public int[] searchRange(int[] nums, int target){
int[] ans = new int[2];
ans[0] = searchElementIndex(nums, target, true);
ans[1] = searchElementIndex(nums, target, false);
return ans;
}
public int searchElementIndex(int[] nums, int target, boolean findFirstIndex){
int index = -1;
int start = 0;
int end = nums.length-1;
while (start <= end) {
int mid = start + (end-start) / 2;
if (findFirstIndex){
if (nums[mid] >= target) end = mid-1;
else start = mid+1;
}else {
if (nums[mid] <= target) start = mid+1;
else end = mid-1;
}
if (nums[mid]==target) index = mid;
}
return index;
}
}
Find First and Last Position of Element in Sorted Array
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* searchRange(int* nums, int numsSize, int target, int* returnSize){
}
class Solution {
public int[] searchRange(int[] nums, int target) {
int si=0;
int ei=nums.length-1;
int[] ans=new int[]{-1,-1};
while(si<=ei){
int mid=si+(ei-si)/2;
if(nums[mid]==target){
si=mid-1;ei=mid+1;
// search for first index with while loop in -ve direction
while(si>=0&&nums[si]==target){si--;}
ans[0]=si+1;
// search for ending index in +ve direction
while(ei<nums.length&&nums[ei]==target){ei++;}
ans[1]=ei-1;
return ans;
}
else if(target>nums[mid]){
si=mid+1;
}
else ei=mid-1;
}
return ans;
}
}