My binary search code in Java


  • 0
    J

    The code includes three binary search fragments, which looks tedious. Could someone help to shorten or encapsulate it? Thanks.

    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int[] res = new int[2];
            res[0] = res[1] = -1;
            int start, end, mid;
            if (nums.length == 0)
                return res;
            start = 0;
            end = nums.length - 1;
            while (start <= end) {
                mid = start + (end - start) / 2;
                if (nums[mid] == target) {
                    res[0] = res[1] = mid;
                    int l, r, m;
                    l = start; r = mid;
                    while (l <= r) {
                        m = (l + r) / 2;
                        if (nums[m] == target ) {
                            res[0] = m;
                            r = m - 1;
                        } else {
                            l = m + 1;
                        }
                    }
    
                    l = mid; r = end;
                    while (l <= r) {
                        m = (l + r) / 2;
                        if (nums[m] == target) {
                            res[1] = m;
                            l = m + 1;
                        } else {
                            r = m - 1;
                        }
                    }
                    break;
                } else if (nums[mid] < target)
                    start = mid + 1;
                else
                    end = mid - 1;
            }
            return res;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.