Search for a range

两次二分

array的题 每次写循环的时候都要注意有没有index out of bound的可能!!

public class Solution {
    public int[] searchRange(int[] A, int target) {
        int[] res = new int[2];
        res[0] = -1;
        res[1] = -1;
        
        int beg = 0;
        int end = A.length - 1;
        int s = -1;
        
        while (beg <= end) {
            s = (beg + end)/2;
            if (A[s] > target) {
                end = s - 1;
            } else if (A[s] < target) {
                beg = s + 1;
            } else {
                 //save the result
        int temp = s;
        res[0] = s;
        res[1] = s;
                
        //search towards right
        int rbeg = temp + 1;
        while ( rbeg <= end) {
            s = (rbeg + end)/2;
            if (A[s] == target && (s == end || A[s+1] > target)){
                res[1] = s;
                break;
            }
            if (A[s] == target) {
                rbeg = s + 1;
            } else {
                end = s - 1;
                }
            }
                
        // search towards left
        int lend = temp -1;
        while (beg <= lend){
            s = (beg + lend)/2;
            if (A[s] == target && (s == beg || A[s-1] < target)){
                res[0] = s;
                break;
            }
            if (A[s] == target) {
                lend = s - 1;
            } else {
                beg = s + 1;
                }
            }
            break;
        }
    }
    
     return res;
    }
}


你可能感兴趣的:(Leetcode,Array,二分Binary,Search)