您的位置:首页 > 编程语言 > Java开发

Java [leetcode 34]Search for a Range

2015-11-12 20:30 555 查看
题目描述:

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]
.

结题思路:

采用二分法查找,如果找到再从这个位置向两边扩散,直到到达目标值的两边边界。

代码如下:

public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = { -1, -1 };
int left = 0;
int right = nums.length - 1;
int mid, low, high;

if (target > nums[right] || target < nums[left])
return result;

while (left <= right) {
mid = (left + right) / 2;
if (nums[mid] == target) {
low = mid;
high = mid;
while (low >= 0 && nums[low] == target)
low--;
result[0] = low + 1;
while (high < nums.length && nums[high] == target)
high++;
result[1] = high - 1;

return result;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: