Description
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 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]
Explanation
Use binary search twice to solve the problem. The first binary search to find the first occurrence of the target. The second binary search to find the second occurrence of the target.
Java Solution
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
if (nums == null || nums.length == 0) {
return result;
}
// first binary search to find the first occurence of the target
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
end = mid;
} else if (nums[mid] > target) {
end = mid;
} else {
start = mid;
}
}
if (nums[end] == target) {
result[0] = end;
}
if (nums[start] == target) {
result[0] = start;
}
// second binary search to find the last occurence of the target
start = 0;
end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
start = mid;
} else if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}
if (nums[start] == target) {
result[1] = start;
}
if (nums[end] == target) {
result[1] = end;
}
return result;
}
}
Python Solution
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
range_start = -1
range_end = -1
if (nums == None or len(nums) == 0):
return [range_start, range_end]
start = 0
end = len(nums) - 1
while start + 1 < end:
mid = start + (end - start) // 2
if nums[mid] < target:
start = mid
elif nums[mid] > target:
end = mid
else:
start = mid
if nums[end] == target:
range_end = end
elif nums[start] == target:
range_end = start
start = 0
end = len(nums) - 1
while start + 1 < end:
mid = start + (end - start) // 2
if nums[mid] < target:
start = mid
elif nums[mid] > target:
end = mid
else:
end = mid
if nums[start] == target:
range_start = start
elif nums[end] == target:
range_start = end
return [range_start, range_end]
- Time complexity: O(log(N)).
- Space complexity: O(1).
It is a best solution found that very popular and helpful:
https://www.youtube.com/watch?v=2kvrD3zY-04&ab_channel=EricProgramming
Hi GoodTecher,
I really like your leetcode video tutorials..hope you continue making more tutorials. 🙂
Thank you, Deepa. I have been getting busy recently. Will do after that 🙂