Search for a Range

来源:互联网 发布:飞思卡尔单片机入门 编辑:程序博客网 时间:2024/06/06 09:08

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[] A, int target) {        // Start typing your Java solution below        // DO NOT write main() function        int[] res = new int[2];        res[0] = lowerbound(A,target);        res[1] = upperbound(A,target);        return res;    }        public static int upperbound(int[] num, int target){//find last 2,int low=0;int high=num.length - 1;int mid = low + (high-low+1)/2;while(low<high){mid = low + (high-low+1)/2;if(num[mid]<=target){low = mid;} else {high = mid - 1;}}        return num[low] == target ? low : -1;}public static int lowerbound(int[] num, int target){//find first 2.int low=0;int high=num.length - 1;int mid = low + (high-low)/2;while(low<high) {mid = low + (high-low)/2;if(num[mid]>=target){high = mid;} else {low = mid + 1;}}return num[high] == target ? high : -1;}}


0 0
原创粉丝点击