Search for a Range

来源:互联网 发布:部落冲突骷髅药水数据 编辑:程序博客网 时间:2024/06/10 19:48

Given a sorted array of n integers, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1].

Have you met this question in a real interview? Yes
Example
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

Challenge
O(log n) time.

两次二分查找!!!条件不一样..找左边界尽量向左,找右边界尽量向右!!!

public class Solution {    public int[] searchRange(int[] A, int target) {        if (A.length == 0) {            return new int[]{-1, -1};        }        int start, end, mid;        int[] bound = new int[2];         bound[0]=-1;        bound[1]=-1;        // search for left bound        start = 0;         end = A.length - 1;        while (start + 1 < end) {            mid = start + (end - start) / 2;            if (A[mid] == target) {                end = mid;            } else if (A[mid] < target) {                start = mid;            } else {                end = mid;            }        }        if (A[start] == target) {            bound[0] = start;        } else if (A[end] == target) {            bound[0] = end;        } else {            return bound;        }        // search for right bound        start = 0;        end = A.length - 1;        while (start + 1 < end) {            mid = start + (end - start) / 2;            if (A[mid] == target) {                start = mid;            } else if (A[mid] < target) {                start = mid;            } else {                end = mid;            }        }        if (A[end] == target) {            bound[1] = end;        } else if (A[start] == target) {            bound[1] = start;        } else {            return bound;        }        return bound;    }}
0 0
原创粉丝点击