首页 > 编程语言 > 详细

Java [leetcode 34]Search for a Range

时间:2015-11-12 21:53:39      阅读:369      评论:0      收藏:0      [点我收藏+]

题目描述:

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; } }

 

Java [leetcode 34]Search for a Range

原文:http://www.cnblogs.com/zihaowang/p/4960203.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!