数组查找乘积为指定数的两数时触发ArrayIndexOutOfBoundsException求因
解决数组找乘积配对时的ArrayIndexOutOfBoundsException问题
嘿,我来帮你排查这个数组越界的问题!首先,ArrayIndexOutOfBoundsException几乎都是因为你访问了数组有效索引范围之外的位置——数组的索引是从0开始的,最后一个元素的索引是数组长度-1,如果你的循环条件写错了,就很容易踩这个坑。
先猜一猜你可能写错的代码
大概率你的循环是类似这样的(错误示例):
int[] nums = {1, 3, 5, 9, 10}; int targetProduct = 27; // 错误:循环条件用了<=数组长度,导致索引越界 for (int i = 0; i <= nums.length; i++) { for (int j = i + 1; j <= nums.length; j++) { if (nums[i] * nums[j] == targetProduct) { System.out.println(nums[i] + " 和 " + nums[j]); } } }
这里的问题很明显:nums.length是数组的元素总数(比如上面的数组长度是5),但数组的最大有效索引是4(因为从0开始计数)。当i等于5的时候,访问nums[i]就会直接抛出越界异常。
修正后的双重循环代码
把循环条件改成< nums.length,确保索引始终在有效范围内:
int[] nums = {1, 3, 5, 9, 10}; int targetProduct = 27; boolean found = false; for (int i = 0; i < nums.length; i++) { // j从i+1开始,避免重复检查同一对元素 for (int j = i + 1; j < nums.length; j++) { if (nums[i] * nums[j] == targetProduct) { System.out.println(nums[i] + " 和 " + nums[j]); found = true; break; } } if (found) break; // 找到结果后直接退出循环,提升效率 }
这段代码运行后就能正常输出3 和 9啦。
更高效的优化方案(避免双重循环)
如果数组元素比较多,双重循环的时间复杂度是O(n²),可以用哈希表把时间降到O(n):
import java.util.HashMap; import java.util.Map; public class FindProductPair { public static void main(String[] args) { int[] nums = {1, 3, 5, 9, 10}; int targetProduct = 27; Map<Integer, Integer> numMap = new HashMap<>(); for (int num : nums) { // 先检查当前数的"补数"(target/num)是否在哈希表里 // 注意要先判断target能被当前数整除,不然乘积不可能等于target if (targetProduct % num == 0) { int complement = targetProduct / num; if (numMap.containsKey(complement)) { System.out.println(complement + " 和 " + num); return; } } // 把当前数存入哈希表 numMap.put(num, 1); } System.out.println("未找到符合条件的两个数"); } }
这个方法的思路是:遍历数组时,用哈希表记录已经见过的数,对每个数,计算出能和它乘积为target的补数,如果补数已经在哈希表里,就找到结果了。
内容的提问来源于stack exchange,提问作者RushHour
相关产品推荐
相关产品推荐

