34. Search for a Range

来源:互联网 发布:中影人 知乎 编辑:程序博客网 时间:2024/06/08 21:12

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(log n),因此采用二分查找的方法。该题目需要找出一个范围,数组元素可以相等,那就可以通过二分查找分别找出左边界和右边界,返回边界值即可。

程序如下所示:

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



原创粉丝点击