码迷,mamicode.com
首页 > 其他好文 > 详细

34. Search for a Range

时间:2017-10-16 09:41:05      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:cti   pre   algo   att   must   div   turn   run   selector   

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

给定一个整型已排序数组,找到一个给定值在其中的起点与终点。 你的算法复杂度必须低于O(logn)。 如果目标在数组中不会被发现,返回[-1, -1]。 例如,给定[5, 7, 7, 8, 8, 10],目标值为8,返回[3, 4]。

 1     public int[] searchRange(int[] nums, int target) {
 2         int[] result = {-1,-1};
 3         if (nums.length == 0) return result;
 4         int low = 0, high = nums.length - 1;
 5         while (low < high) {
 6             int mid = (low + high) / 2;
 7             if (nums[mid] < target) low = mid + 1;
 8             else  high = mid;
 9         }
10         if (nums[low]!=target) return result;
11         else result[0]=low;
12 
13         high = nums.length-1;  // We don‘t have to set i to 0 the second time.
14         while (low < high)
15         {
16             int mid = (low + high) /2 + 1;    // Make mid biased to the right
17             if (nums[mid] > target) high = mid - 1;
18             else low = mid;                // So that this won‘t make the search range stuck.
19         }
20         result[1] = high;
21         return result;       
22     }

 

34. Search for a Range

标签:cti   pre   algo   att   must   div   turn   run   selector   

原文地址:http://www.cnblogs.com/wzj4858/p/7675400.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!