-1
class Solution {
public int[] searchRange(int[] nums, int target) 
{
    int first = firstIndex(nums, 0, nums.length, target);
    int last = lastIndex(nums, 0, nums.length, target);

    return new int[] {first, last};
}

public int firstIndex (int[] nums, int left, int right, int target)
{
    while (left <= right)
    {
        int pivot = left + (right - left) / 2;
        if (nums[pivot] == target)
        {

            if (pivot == left || nums[pivot - 1] < nums[pivot]) 
                // it means the search on left side is done or mid is the first occurance in the array
                return pivot;

            else 
                // still go left
                right = pivot - 1;
        }
        else if (nums[pivot] > target)
            right = pivot - 1;
        else
             left = pivot + 1;
    }
    return -1;
}

public int lastIndex (int[] nums, int left, int right, int target)
{
    while (left <= right)
    {
        int pivot = left + (right - left) / 2;
        if (nums[pivot] == target)
        {

            if (pivot == right || nums[pivot] < nums[pivot + 1])
                // it means the search on the right side is done or mid is the last occurance in the array
                return pivot;
            else 
                // still go right
                left = pivot + 1;
        }
        else if (nums[pivot] > target)
            right = pivot - 1;
        else 
            left = pivot + 1;
    }
    return -1;
}

}

这是我使用二进制搜索的解决方案。我运行代码时可以接受但不能提交。if (nums[pivot] == target) 处有一个 ArrayIndexOutOfBoundsException。我不明白为什么会这样。我研究了解决方案。大多数解决方案都采用这种方式。我不知道如何摆脱这个错误。有人可以帮我解释一下吗????非常感谢!!!!

在此处输入图像描述

4

1 回答 1

2

我很确定问题出在你的电话上`

int first = firstIndex(nums, 0, nums.length, target);
int last = lastIndex(nums, 0, nums.length, target);`

由于第三个参数指的是数组最右边的索引,所以 nums.length 太高了,因为数组是从 0 开始的。在寻找比最右边的元素更大的东西时,我用您的代码复制了 jdoodle 上的错误,并将第一行中的 nums.length 更改为 nums.length-1 将错误推到了第二次调用中。在第二次调用中将 nums.length 替换为 nums.length-1 使其完全消失。

单击https://www.geeksforgeeks.org/binary-search/上的 java 选项卡,您可以看到它们使用 n -1。

于 2019-11-17T04:39:47.193 回答