Search for a Range

来源:互联网 发布:java 字符串随机排列 编辑:程序博客网 时间:2024/06/15 19:41

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

 

分析:由于时间复杂度需要O(log n),很容易想到二分法。

一次二分用于找到最左端,一次二分用于找到最右端。

 

代码:

public static int[] searchRange(int[] A, int target) {int[] result = {-1,-1};int left = 0, right = A.length - 1, mid;while(left <= right)// get start index{mid = (left + right) / 2;if(A[mid] < target)left = mid + 1;else if(A[mid] > target)right = mid - 1;else{result[0] = mid;right = mid - 1;}}left = 0;right = A.length - 1;while(left <= right)// get end index{mid = (left + right) / 2;if(A[mid] < target)left = mid + 1;else if(A[mid] > target)right = mid - 1;else{result[1] = mid;left = mid + 1;}}return result;    }


 

0 0
原创粉丝点击