34.Search for a Range LeetCode Java版代码

Posted 小竹_phper

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了34.Search for a Range LeetCode Java版代码相关的知识,希望对你有一定的参考价值。

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

Tags : Binary Search, Array

题意解析:给定一个排序好的一维数组和一个要查找的目标值target,要求时间复杂度为O(log n).

根据时间复杂度要求,本题需要采用二分查找;

函数的结果是一个长度为2的数组ans, 当给定的数组中不存在target值得时候,返回[-1,-1];反之,返回target在给定数组中的初始下标和终止下标;

eg: 给定数组 [2,2,2,2,2]  要查找的数值为2

结果为[0,4]

下面是在leetcode上AC的代码:

public class Solution 
    public int[] searchRange(int[] nums, int target) 
        int len = nums.length;
		int[] ans = new int[2];
		Arrays.fill(ans, -1);
		if (len == 0)
			return ans;
		int min = 0;
		int max = len - 1;
		int mid = (min + max) / 2;
		while (min <= max) 
			if (target == nums[mid]) 
				ans[0] = mid;
				break;
			
			if (target < nums[mid])
				max = mid - 1;
			else
				min = mid + 1;
			mid = (min + max) / 2;
		
		if (min <= max) 
			int i = mid;
			int j = mid;
			while ((i - 1) >= 0 && nums[i-1] == target) 
				i--;
			
			while ((j + 1) < len && nums[j+1] == target) 
				j++;
			
			ans[0] = i;
			ans[1] = j;
		
		return ans;
    


以上是关于34.Search for a Range LeetCode Java版代码的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 34. Search for a Range

34. Search for a Range

34. Search for a Range

34. Search for a Range

LeetCode - 34. Search for a Range

LeetCode OJ 34Search for a Range