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]
用两次binary search,第一次找到左边界l,第二次binary search在[l, r] 中找右边界,注意要reset r = nums.length
time: O(logN), space: O(1)
class Solution { public int[] searchRange(int[] nums, int target) { int[] res = {-1, -1}; int l = 0, r = nums.length - 1; if(nums == null || nums.length == 0) return res; while(l < r) { int m = l + (r - l) / 2; if(nums[m] < target) l = m + 1; else r = m; } if(nums[l] != target) return res; res[0] = l; r = nums.length; while(l < r) { int m = l + (r - l) / 2; if(nums[m] > target) r = m; else l = m + 1; } res[1] = r - 1; return res; } }
二刷:
class Solution { public int[] searchRange(int[] nums, int target) { int[] res = {-1, -1}; if(nums == null || nums.length == 0) return res; int left = 0, right = nums.length - 1; while(left + 1 < right) { // find first position int mid = left + (right - left) / 2; if(nums[mid] == target) right = mid; else if(nums[mid] > target) right = mid; else left = mid; } res[0] = (nums[left] == target) ? left : (nums[right] == target ? right : -1); left = 0; right = nums.length - 1; while(left + 1 < right) { // find last position int mid = left + (right - left) / 2; if(nums[mid] == target) left = mid; else if(nums[mid] > target) right = mid; else left = mid; } res[1] = (nums[right] == target) ? right : (nums[left] == target ? left : -1); return res; } }
三刷:
class Solution { public int[] searchRange(int[] nums, int target) { int[] res = {-1, -1}; if(nums == null || nums.length == 0) { return res; } int left = 0, right = nums.length - 1; while(left + 1 < right) { // find first position int mid = left + (right - left) / 2; if(nums[mid] >= target) { right = mid; } else { left = mid; } } res[0] = nums[left] == target ? left : (nums[right] == target ? right : -1); left = 0; right = nums.length - 1; while(left + 1 < right) { // find last position int mid = left + (right - left) / 2; if(nums[mid] <= target) { left = mid; } else { right = mid; } } res[1] = nums[right] == target ? right : (nums[left] == target ? left : -1); return res; } }