Java Leetcode 34。使用ArrayIndexOutOfBoundsException查找排序数组中元素的第一个和最后一个位置 类解决方案{ 公共int[]搜索范围(int[]nums,int目标) { int first=firstIndex(nums,0,nums.length,target); int last=lastIndex(nums,0,nums.length,target); 返回新的int[]{first,last}; } 公共int firstIndex(int[]nums,int left,int right,int target) { while(左目标) 右=枢轴-1; 其他的 左=枢轴+1; } 返回-1; } 公共int lastIndex(int[]nums,int left,int right,int target) { while(左目标) 右=枢轴-1; 其他的 左=枢轴+1; } 返回-1; }
} 这是我使用二进制搜索的解决方案。当我运行代码时可以接受,但不能提交。 if(nums[pivot]==target)处存在ArrayIndexOutOfBoundsException。我不明白为什么会这样。我研究了解决方案。大多数解决方案都使用这种方式。我不知道如何消除这个错误。 有人能帮我解释一下吗????非常感谢你Java Leetcode 34。使用ArrayIndexOutOfBoundsException查找排序数组中元素的第一个和最后一个位置 类解决方案{ 公共int[]搜索范围(int[]nums,int目标) { int first=firstIndex(nums,0,nums.length,target); int last=lastIndex(nums,0,nums.length,target); 返回新的int[]{first,last}; } 公共int firstIndex(int[]nums,int left,int right,int target) { while(左目标) 右=枢轴-1; 其他的 左=枢轴+1; } 返回-1; } 公共int lastIndex(int[]nums,int left,int right,int target) { while(左目标) 右=枢轴-1; 其他的 左=枢轴+1; } 返回-1; },java,indexoutofboundsexception,java.lang.class,java.lang,Java,Indexoutofboundsexception,Java.lang.class,Java.lang,} 这是我使用二进制搜索的解决方案。当我运行代码时可以接受,但不能提交。 if(nums[pivot]==target)处存在ArrayIndexOutOfBoundsException。我不明白为什么会这样。我研究了解决方案。大多数解决方案都使用这种方式。我不知道如何消除这个错误。 有人能帮我解释一下吗????非常感谢你 我敢肯定问题出在你的电话上` class Solution { public int[] searchRange(int[] nums, int target) {
我敢肯定问题出在你的电话上`
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;
}
由于第三个参数引用数组最右边的索引,nums.length太高,因为数组是基于0的。在查找大于最右边元素的内容时,我用代码复制了jdoodle上的错误,并在第一行中将nums.length更改为nums.length-1,将错误推到了第二个调用中。在第二次调用中将nums.length替换为nums.length-1使其完全消失
单击网站上的java选项卡,您可以看到他们使用了n-1。非常感谢。你的回答帮助很大。我应该一直小心射程。通过使用nums.length-1,代码被接受。非常感谢!!
int first = firstIndex(nums, 0, nums.length, target);
int last = lastIndex(nums, 0, nums.length, target);`