LeetCode OJ 34. Search for a Range

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

【题目分析】

本题的大意是在一个排序的数组中找到给定值的起始下标和截止下标,如果存在这样的值,则返回这样的下标,如果不存在则返回[-1,-1]。并且要求时间复杂度控制在log(n)。

【思路】

首先我们要在数组中找到给定的值,这是一个数组查找的过程,由于是排序数组,我们很自然地想到了二分查找算法,二分查找的时间复杂度是log(n)。如果找到了目标值,我们再像两边扩散,查找目标值的存在的上下界。这是两个简单的循环遍历过程。然后我们把找到的上下标返回即可。

【java代码】

 1 public class Solution {
 2     public int[] searchRange(int[] nums, int target) {
 3         int[] result = {-1, -1};
 4         if(nums == null || nums.length == 0) return result;
 5         
 6         int left = 0;
 7         int right = nums.length - 1;
 8         
 9         while(left <= right){
10             int mid = (right - left)/2 + left;
11             if(nums[mid] < target) left = mid + 1;
12             else if(nums[mid] > target) right = mid - 1;
13             else{                                       //如果查找到目标值
14                 int leftindex = mid;
15                 int rightindex = mid;
16                 while(rightindex < nums.length && nums[rightindex] == target) rightindex++;//寻找上界
17                 while(leftindex >= 0 && nums[leftindex] == target) leftindex--;            //寻找下界
18                 result[0] = leftindex + 1;
19                 result[1] = rightindex - 1;
20                 return result;
21             }
22         }
23         return result;
24     }
25 }
原文地址:https://www.cnblogs.com/liujinhong/p/5521858.html