34. Find First and Last Position of Element in Sorted Array leetCode
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
C++:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int>result;
int firstIndex= firstOcc(nums,target);
int lastIndex = lastOcc(nums,target);
result.push_back(firstIndex);
result.push_back(lastIndex);
return result;
}
int firstOcc(vector<int>& nums, int target){
int start = 0;
int end = nums.size()-1;
int mid=start+(end-start)/2;
int ans = -1;
while(start <= end){
if(target==nums[mid]){
ans = mid;
end = mid-1;
}
else if(target >nums[mid]){
start = mid+1;
}
else{
end = mid-1;
}
mid=start+(end-start)/2;
}
return ans;
}
int lastOcc(vector<int>& nums, int target){
int start = 0;
int end = nums.size()-1;
int ans = -1;
int mid=start+(end-start)/2;
while(start <= end){
if(target == nums[mid]){
ans = mid;
start = mid+1;
}
else if(target > nums[mid]){
start = mid+1;
}
else{
end = mid-1;
}
mid=start+(end-start)/2;
}
return ans;
}
};
Java:
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] index = new int[2];
if (nums == null || nums.length == 0) {
return new int[] {-1, -1};
index[0] = firstOccurrence(nums, target);
index[1] = lastOccurrence(nums, target);
return index;
}
private int firstOccurrence(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
int ans = -1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
ans = mid;
end = mid - 1; // keep searching on the left
} else if (nums[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return ans;
}
private int lastOccurrence(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
int ans = -1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
ans = mid;
start = mid + 1; // keep searching on the right
} else if (nums[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return ans;
}
}
Comments
Post a Comment