
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given targetvalue.
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:
1 2
|
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
|
Example 2:
1 2
|
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class { public int[] searchRange(int[] nums, int target) { int[] arr = {-1,-1}; if (nums == null || nums.length == 0) { return arr; } int start = 0; int end = nums.length - 1; while (start <= end) { if (nums[start] != target) { start++; } else { arr[0] = start; } if (nums[end] != target) { end--; } else { arr[1] = end; } if (arr[0] == start && arr[1] == end) { return arr; } } return arr; } }
|
近期评论