LeetCode34. Search for a Range

来源:互联网 发布:plc能用c语言编程吗 编辑:程序博客网 时间:2024/06/08 08:28

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

public class Solution {    public int[] searchRange(int[] nums, int target) {        int[] result = new int[2];        int resultStart = -1;        int resultEnd = -1;        int start = 0;         int end = nums.length - 1;        int mid = 0;        while (start <= end) {            mid = start + ((end - start) >>> 1);            //target < nums[mid]肯定往左找            //找下确界,即使相等也要往左找            if (target <= nums[mid]) {                end = mid - 1;            } else {                //target >= nums[mid]                start = mid + 1;            }        }        if (start < nums.length && nums[start] == target) {            resultStart = start;            end = nums.length - 1;            while (start <= end) {                mid = start + ((end - start) >>> 1);                if (target < nums[mid]) {                    end = mid - 1;                } else {                    start = mid + 1;                }            }            resultEnd = end;        }        result[0] = resultStart;        result[1] = resultEnd;        return result;    }}

找下确界时,nums[mid]只要大于等于target就要往左找,end=mid-1的可能性只有大于target,或者等于target。如果大于target的话,自然要往左移。但是如果等于target了,这时,再往左移,其实可能会导致[start, end]区间内的数据都小于target,但是这时start会一直mid+1,直到超越了当前的end,这时start所指的其实就是最小的目标值。因为,end是一步一步往左移的。如:
indx:0 1 2 3 4 5 6
data:1 2 3 3 3 3 3
start,end mid
[0,6] 3 往左
[0,2] 1 往右
[2,2] 2 往左
[2,1] 退出循环
所以,start就是下确界

也有可能,nums[start]不是target,说明,没有target。返回-1.

0 0
原创粉丝点击