Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[]{-1, -1};
        }
        return new int[]{binarySearch(nums, target, 0), binarySearch(nums, target, 1)};
    }
    
    private int binarySearch(int[] nums, int target, int mode) {
        int l = 0, r = nums.length - 1;
        // check boundary conditions
        if (mode == 0 && nums[l] == target) {
            return l;
        }
        if (mode == 1 && nums[r] == target) {
            return r;
        }

        while (l <= r) {
            int m = l + (r - l) / 2;
            if (nums[m] == target) {
                if (mode == 0) {
                    if (m > 0 && nums[m - 1] < target) {
                        return m;
                    } else {
                        r = m - 1;
                    }
                } else {
                    if (m < nums.length - 1 && nums[m + 1] > target) {
                        return m;
                    } else {
                        l = m + 1;
                    }
                }
            } else if (nums[m] < target) {
                l = m + 1;
            } else {
                r = m - 1;
            }
        }
        return -1;
    }
}