Search for a Range -- Share my clean Solution


  • 0
    C
    public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[2];
        res[0] = findBegin(nums, target);
        res[1] = findEnd(nums, target);
        return res;
    }
    public int findBegin(int[] nums, int target) {
        int begin = 0; 
        int end = nums.length - 1;
        while (begin < end - 1) {
            int mid = (begin + end) / 2;
            if (nums[mid] >= target) {
                end = mid;
            } else {
                begin = mid;
            }
        }
        if (nums[begin] == target) {
            return begin;
        }
        if (nums[end] == target) {
            return end;
        }
        return -1;
    }
    
    public int findEnd(int[] nums, int target) {
        int begin = 0; 
        int end = nums.length - 1;
        while (begin < end - 1) {
            int mid = (begin + end) / 2;
            if (nums[mid] > target) {
                end = mid - 1;
            } else {
                begin = mid;
            }
        }
        if (nums[end] == target) {
            return end;
        }
        if (nums[begin] == target) {
            return begin;
        }
        return -1;
    }
    

    }


Log in to reply
 

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