34. Search for a Range
Posted andywu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]
.
给定一个整型已排序数组,找到一个给定值在其中的起点与终点。 你的算法复杂度必须低于O(logn)。 如果目标在数组中不会被发现,返回[-1, -1]。 例如,给定[5, 7, 7, 8, 8, 10],目标值为8,返回[3, 4]。
1 public int[] searchRange(int[] nums, int target) { 2 int[] result = {-1,-1}; 3 if (nums.length == 0) return result; 4 int low = 0, high = nums.length - 1; 5 while (low < high) { 6 int mid = (low + high) / 2; 7 if (nums[mid] < target) low = mid + 1; 8 else high = mid; 9 } 10 if (nums[low]!=target) return result; 11 else result[0]=low; 12 13 high = nums.length-1; // We don‘t have to set i to 0 the second time. 14 while (low < high) 15 { 16 int mid = (low + high) /2 + 1; // Make mid biased to the right 17 if (nums[mid] > target) high = mid - 1; 18 else low = mid; // So that this won‘t make the search range stuck. 19 } 20 result[1] = high; 21 return result; 22 }
以上是关于34. Search for a Range的主要内容,如果未能解决你的问题,请参考以下文章