Leetcode#34. Find First and Last Position of Element in Sorted Array
Problem
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:
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 <= 10^5
10^9 <= nums[i] <= 10^9
nums
is a non-decreasing array.10^9 <= target <= 10^9
Solve
使用標準的Binary Search 來做這題
先用二分法找到target
因為target可能有重複,找到後,再前後延伸搜索
1 | class Solution: |
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Imisky!
評論