Leetcode 34: Search for a Range
Given an array of integers 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].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
1 public class Solution { 2 public int[] SearchRange(int[] nums, int target) { 3 int[] result = {Int32.MaxValue, Int32.MinValue}; 4 5 BinarySearch(nums, target, 0, nums.Length - 1, true, result); 6 BinarySearch(nums, target, 0, nums.Length - 1, false, result); 7 8 result[0] = result[0] == Int32.MaxValue ? -1 : result[0]; 9 result[1] = result[1] == Int32.MinValue ? -1 : result[1]; 10 11 return result; 12 } 13 14 private void BinarySearch(int[] nums, int target, int start, int end, bool up, int[] result) 15 { 16 if (start > end) return; 17 18 if (start == end) 19 { 20 if (nums[start] == target) 21 { 22 result[0] = Math.Min(result[0], start); 23 result[1] = Math.Max(result[1], start); 24 } 25 26 return; 27 } 28 29 int mid = start + (end - start) / 2; 30 if (nums[mid] == target) 31 { 32 result[0] = Math.Min(result[0], mid); 33 result[1] = Math.Max(result[1], mid); 34 35 if (up) 36 { 37 BinarySearch(nums, target, mid + 1, end, up, result); 38 } 39 else 40 { 41 BinarySearch(nums, target, start, mid - 1, up, result); 42 } 43 } 44 else if (nums[mid] < target) 45 { 46 BinarySearch(nums, target, mid + 1, end, up, result); 47 } 48 else 49 { 50 BinarySearch(nums, target, start, mid - 1, up, result); 51 } 52 } 53 }

浙公网安备 33010602011771号