34.Search for a Range LeetCode Java版代码

来源:互联网 发布:易华录数据湖 编辑:程序博客网 时间:2024/05/18 00:59

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


0 0