[leetcode]34. Search for a Range(Java实现)

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.

Java code:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值