LeetCode Search for a Range(二分法)

来源:互联网 发布:网络语怼人是什么意思 编辑:程序博客网 时间:2024/06/17 14:51

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]

思路:用二分查找法(左开右闭区间形式),可参考stl中的算法实现

代码如下

public class Solution {    public int[] searchRange(int[] nums, int target) {        int[] ans = new int[2];                int left = 0, right = nums.length;        int mid = -1;        int len = right;                while (left < right) {            mid = (left + right) >> 1;            if (nums[mid] < target) {                left = mid + 1;            } else {                right = mid;            }        }                if (left >= len || nums[left] != target) ans[0] = -1;        else ans[0] = left;                left = 0;        right = nums.length;                mid = -1;        while (left < right) {            mid = (left + right) >> 1;            if (nums[mid] <= target) left = mid + 1;            else right = mid;        }                if (left == 0 || nums[left - 1] != target) ans[1] = -1;        else ans[1] = left - 1;                return ans;    }}


0 0
原创粉丝点击