您的位置:首页 > 其它

Leetcode之Search for a Range

2016-08-07 23:33 393 查看

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


题意解释

  题目的意思是从一个已经排序的数组中,给定一个数target,然后从数组中查找是否存在这样的数,如果存在则返回这个数所在的index区间,如果不存在这个数则返回的区间为[-1,-1]


## 解题思路 ##

找到左边界

找到第一个等于target的数的index,做法是找到这个数等于target的index同时并且index-1的这个数刚好小于target,如果找到最后还不存在这样的情况,则根据左边界的定义求得index

找到右边界

找到最后一个等于target的数的index,做法是找到这个数等于target的index同时并且index+1的这个数刚好大于target,如果找到最后还不存在这样的情况,则根据右边界的定义求得index

合并

左右边界合并求得数组

代码

//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].
//
//        Subscribe to see which companies asked this question

/**
* Created by loveqh on 2016/8/7.
*/
public class SearchForARange {
public int[] searchRange(int[] nums, int target) {
int lefeIndex = searchLeft(nums, target, 0, nums.length - 1);
int rightIndex = searchRight(nums, target, 0, nums.length - 1);
return new int[]{lefeIndex, rightIndex};
}

/**
* 求数组中的下界,
*
* @param nums
* @param target
* @return
*/
public int searchLeft(int[] nums, int target, int first, int last) {
int mid;
while (first + 1 < last) {
mid = first + (last - first) / 2;
if (nums[mid] < target) {
first = mid + 1;
} else if (nums[mid] > target) {
last = mid - 1;
//else 的情况为相等
} else {
if (nums[mid - 1] < target) {
return mid;
} else {
last = mid;
}
}
}
if (nums[first] == target) return first;
else if (nums[last] == target) return last;
else return -1;
}

/**
* 求数组中的上界
*
* @param nums
* @param target
* @return
*/
public int searchRight(int[] nums, int target, int first, int last) {
int mid;
while (first + 1 < last) {
mid = first + (last - first) / 2;
if (nums[mid] < target) {
first = mid + 1;
} else if (nums[mid] > target) {
last = mid - 1;
//else 的情况为相等
} else {
if (nums[mid + 1] > target) {
return mid;
} else {
first = mid;
}
}
}
if (nums[last] == target) return last;
if (nums[first] == target) return first;
return -1;
}
@Test
public static void main(String[] args) {
int[] a = {2, 2};
int[] result = new SearchForARange().searchRange(a, 2);
for (int value : result) {
System.out.println(value + "   ");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法