【二分查找】Search for a Range

来源:互联网 发布:倩女手游 mac 编辑:程序博客网 时间:2024/05/02 01:42

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

解法:特殊的二分,在找到首个val后要进行判断它的前面是否还有符合的值;同理找最后一个

public class Solution {    public int searchFirst(int []num, int val){        int low = 0;        int high = num.length-1;        while(low <= high){            int mid = (low + high) / 2;            if(num[mid] == val){                if(mid-1 >= 0 && num[mid-1] == val ) high = mid-1;                else return mid;            }            else if(num[mid] > val) high = mid - 1;            else low = mid + 1;        }        return -1;    }        public int searchLast(int [] num, int val){        int low = 0;        int high = num.length-1;        while(low <= high){            int mid = (low + high) / 2;            if(num[mid] == val){                if(mid+1 < num.length && num[mid+1] == val ) low = mid+1;                else return mid;            }            else if(num[mid] > val) high = mid - 1;            else low = mid + 1;        }        return -1;    }        public int[] searchRange(int[] A, int target) {        int first = searchFirst(A, target);        int last = searchLast(A, target);        int b[] = new int[2];        b[0] = first;        b[1] = last;        return b;    }}


0 0
原创粉丝点击