Java 数组中查找两个数之和等于指定值的下标
以下是一个 Java 代码示例,实现了查找数组中两个数之和等于指定值的元素下标。
public class Main {
public static void main(String[] args) {
int[] nums = {2, 4, 6, 8, 10};
int[] result = findTwoNumbers(nums, 10);
if (result != null) {
System.out.println('找到两个数的下标:' + result[0] + ', ' + result[1]);
} else {
System.out.println('没有找到满足条件的两个数');
}
}
public static int[] findTwoNumbers(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return null;
}
}
此示例中,我们定义了一个 findTwoNumbers 方法,它接受一个整型数组 nums 和一个整数 target 作为参数。该方法使用两个嵌套循环遍历数组中的每一个数对,如果找到两个数的和等于 target,则将它们的下标保存在 result 数组中并返回。如果没有找到满足条件的两个数,则返回 null。
在 main 方法中,我们定义了一个示例数组 nums,并调用 findTwoNumbers 方法来查找满足条件的两个数的下标。最后,根据返回的结果输出相应的信息。
原文地址: https://www.cveoy.top/t/topic/peIu 著作权归作者所有。请勿转载和采集!