Problem
Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
If target
is not found in the array, return [-1, -1]
.
Follow up: Could you write an algorithm with O(log n)
runtime complexity?
Example 1:
1 | Input: nums = [5,7,7,8,8,10], target = 8 |
Example 2:
1 | Input: nums = [5,7,7,8,8,10], target = 6 |
Example 3:
1 | Input: nums = [], target = 0 |
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums
is a non-decreasing array.-109 <= target <= 109
Analysis
题目给出一个有序数组,还有一个target
,要求找出target在数组中第一次和最后一次出现的下标。其实题目非常简单了,因为数组是有序的,所以也保证了相同的值是靠在一起的,从左往右开始遍历,我们只需要在第一次出现的时候记录下一个下标,然后最后一次出现的时候记录下标,这就是答案了。
Solution
无
Code
1 | class Solution { |
Summary
这道题目的分享到这里,感谢你的支持!