search for a range

来源:互联网 发布:js点击按钮执行ctrl c 编辑:程序博客网 时间:2024/06/07 12:25

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[] index = {-1,-1};        if(nums.length == 0 || nums == null){            return index;        }        int start = 0;        int end = nums.length - 1;        int mid = 0;        while(start + 1 < end){            mid = start + (end - start)/2;            if(nums[mid] == target){                //继续向左边找                end = mid;            }else if(nums[mid] < target){                start = mid;            }else{                end = mid;            }        }        //start 在 end 前面,因为找最开始的所以start放前面        if(nums[start] == target){            index[0] = start;        }else if(nums[end] == target){            index[0] = end;        }else{            return index;        }                start = 0;        end = nums.length -1;        while(start + 1 < end){            mid = start + (end - start)/2;            if(nums[mid] == target){                start = mid;            }else if(nums[mid] > target){                end = mid;            }else{                start = mid;            }        }        //start 在 end 前面,因为找最后面的所以end放前面        if(nums[end] == target){            index[1] = end;        }else if(nums[start] == target){            index[1] = start;        }        return index;    }}


0 0
原创粉丝点击