Question
Given a sorted array of integers, 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
Solution
Use binary search, first, find left position, then, find right position.
1 public class Solution { 2 public int[] searchRange(int[] nums, int target) { 3 int[] result = new int[2]; 4 result[0] = -1; 5 result[1] = -1; 6 if (nums == null || nums.length < 1) 7 return result; 8 int start = 0, end = nums.length - 1, mid, first, last; 9 // Find first position of target 10 while (start + 1 < end) { 11 mid = (end - start) / 2 + start; 12 if (nums[mid] >= target) 13 end = mid; 14 else 15 start = mid; 16 } 17 if (nums[start] == target) 18 result[0] = start; 19 else if (nums[end] == target) 20 result[0] = end; 21 22 // Find last position of target 23 start = 0; 24 end = nums.length - 1; 25 while (start + 1 < end) { 26 mid = (end - start) / 2 + start; 27 if (nums[mid] <= target) 28 start = mid; 29 else 30 end = mid; 31 } 32 if (nums[end] == target) 33 result[1] = end; 34 else if (nums[start] == target) 35 result[1] = start; 36 return result; 37 } 38 }
时间: 2024-11-06 14:10:14