leetcode测试地址:https://leetcode.com/problems/search-for-a-range/#/description
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]
.
Subscribe to see which companies asked this question.
package go.jacob.day621;
/**
* [leetcode]34. Search for a Range
*
* @author Administrator
*
*/
public class Demo1 {
/*
* 思路:二分查找的应用
* 时间复杂度要求O(logn)
*
*/
public int[] searchRange(int[] nums, int target) {
int[] result = { -1, -1 };
if (nums == null || nums.length < 1)
return result;
//找到一个target元素的下标,然后两个指针分别向前向后寻找
int index = solve(nums, target, 0, nums.length - 1);
if (index != -1) {
int left = index, right = index;
while (left >= 0 && nums[left] == target)
left--;
while (right < nums.length && nums[right] == target)
right++;
result[0] = left + 1;
result[1] = right - 1;
}
return result;
}
/*
* 二分查找:寻找target
*/
private int solve(int[] nums, int target, int left, int right) {
if (left > right)
return -1;
int mid = left + (right - left) / 2;
if (nums[mid] == target)
return mid;
if (nums[mid] > target)
return solve(nums, target, left, mid - 1);
else
return solve(nums, target, mid + 1, right);
}
}