L34 Find First and Last Position of Element in Sorted Array
Problem:
Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
example:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Solution
Binary Search:
There are two parts for this question: search left and search right.
for the left part, since we need to find the most left index, so when nums[mid] < target, left = mid; the point always stay at most left.
TC: log n; SC:O1
public int[] searchRange(int[] nums, int target){
if(nums == null || nums.length == 0) return new int{-1, -1};
int[] res = new int[2];
res[0] = searchLeft(nums, target);
res[1] = searchRight(nums, target);
return res;
}
private int searchLeft(int[]nums, int target){
int left = 0, right = nums.length-1;
while(left+1 < right){
int mid = left + (right - left) / 2;
if(nums[mid] >= target){
right = mid;
}else{
left = mid;
}
}
if(nums[left] == target) return left;
return nums[right] == target? right : -1;
}
private int searchRight(int[]nums, int target){
int left = 0, right = nums.length - 1;
while(left + 1 < right){
int mid = left + (right - left) / 2;
if(mid <= target){
left = mid;
}else{
right = mid;
}
}
if(nums[right] == target) return right;
return nums[left] == target ? left : -1;
}
Last updated
Was this helpful?