📌  相关文章
📜  在有序数组中查找元素的第一个和最后一个位置 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:07.350000             🧑  作者: Mango

代码示例2
class Solution {
    public int[] searchRange(int[] nums, int target){
        int[] ans = new int[2];
        ans[0] = searchElementIndex(nums, target, true);
        ans[1] = searchElementIndex(nums, target, false);
        return ans;
    }

    public int searchElementIndex(int[] nums, int target, boolean findFirstIndex){
        int index = -1;
        int start = 0;
        int end = nums.length-1;

        while (start <= end) {
            int mid = start + (end-start) / 2;

            if (findFirstIndex){
                if (nums[mid] >= target) end = mid-1;
                else start = mid+1;
            }else {
                if (nums[mid] <= target) start = mid+1;
                else end = mid-1;
            }
            if (nums[mid]==target) index = mid;
        }
        return index;
    }
}