LeetCode 38: Search for a Range

来源:互联网 发布:现在最火的网络女歌手 编辑:程序博客网 时间:2024/05/22 03:01

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


LL's solution:

Binary search

public class Solution {    public int[] searchRange(int[] A, int target) {        // Start typing your Java solution below        // DO NOT write main() function        int[] res = {-1,-1};        int len = A.length;        if(len<1)            return res;        int start_l = 0,end_l = len-1,middle_l;        int start_r = 0,end_r = len-1,middle_r;        while(start_l<end_l){   // 0011            middle_l = start_l + (int)(end_l-start_l)/2;            if(A[middle_l]>=target)                end_l = middle_l;            else                start_l = middle_l+1;        }        if(A[start_l]!=target)            return res;        else            res[0] = start_l;                while(start_r<end_r){   // 1100            middle_r = start_r + (int)(end_r-start_r+1)/2;            if(A[middle_r]<=target)                start_r = middle_r;            else                end_r = middle_r-1;        }        if(A[end_r]!=target)            return res;        else            res[1] = end_r;                    return res;    }}





原创粉丝点击