34. Search for a Range

来源:互联网 发布:重生之美国仓储淘宝王 编辑:程序博客网 时间:2024/04/29 18:54

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

题意、思路

按要求使用Array、Binary Search:
先根据二分法找出其中一个的位置 然后在第二个 进行两次函数的调用 其实很简单

代码

public class Solution {    public int[] searchRange(int[] nums, int target) {        int start = Solution.shao(nums, target);        if(start == nums.length || nums[start] != target){ //进行判断            return new int[]{-1, -1};        }        return new int[]{start, Solution.shao(nums, target + 1) - 1}; //****注意此处的target + 1    }    public static int shao(int[] nums, int target){ //找出target的位置        int left = 0, right = nums.length;        while(left < right){            int mid = (left + right) / 2;            if(nums[mid] < target){                left = mid + 1;            }            else{                right = mid;            }        }        return left;    }}
0 0
原创粉丝点击