题目:输入一个3行4列的数组,找出该数组中绝对值最大的元素、输出该元素的绝对值及其两个下标值。如有多个输出行号最小的,还有多个的话输出列号最小的。
这个问题可以分为以下几个步骤来解决:
- 遍历整个数组,找到绝对值最大的元素,同时记录其绝对值、行号和列号。
- 如果有多个绝对值最大的元素,选择行号最小的,如果行号相同,则选择列号最小的。
接下来,我将分别展示三种不同的方法来实现这个任务,并列出它们的解题思路、实现代码以及各自的优缺点。
方法一:嵌套循环法
解题思路:
使用两层循环遍历整个数组,计算每个元素的绝对值,然后比较找到最大的元素。在比较时,如果找到的元素的绝对值大于当前最大元素,或者绝对值相同但行号小于当前最大元素,或者绝对值相同但行号相同且列号小于当前最大元素,则更新最大元素。
实现代码:
public class Main {
public static void main(String[] args) {
int[][] array = new int[][] {
{1, -2, 3, 4},
{5, -6, 7, 8},
{-9, 10, 11, 12}
};
int maxAbsValue = 0;
int maxRow = 0;
int maxCol = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
int absValue = Math.abs(array[i][j]);
if (absValue > maxAbsValue || (absValue == maxAbsValue && (i < maxRow || (i == maxRow && j < maxCol)))) {
maxAbsValue = absValue;
maxRow = i;
maxCol = j;
}
}
}
System.out.println("绝对值最大的元素:" + maxAbsValue);
System.out.println("行号:" + maxRow);
System.out.println("列号:" + maxCol);
}
}
优点:
- 简单易懂,容易实现。
- 时间复杂度为O(12),因为需要遍历所有元素。
缺点:
- 需要两层嵌套循环,可能在大型数组上效率较低。
方法二:一次遍历法
解题思路:
使用一次遍历来查找绝对值最大的元素,同时记录行号和列号。这种方法更高效。
实现代码:
public class Main {
public static void main(String[] args) {
int[][] array = new int[][] {
{1, -2, 3, 4},
{5, -6, 7, 8},
{-9, 10, 11, 12}
};
int maxAbsValue = 0;
int maxRow = 0;
int maxCol = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
int absValue = Math.abs(array[i][j]);
if (absValue > maxAbsValue) {
maxAbsValue = absValue;
maxRow = i;
maxCol = j;
}
}
}
System.out.println("绝对值最大的元素:" + maxAbsValue);
System.out.println("行号:" + maxRow);
System.out.println("列号:" + maxCol);
}
}
优点:
- 只需要一次遍历,因此在大型数组上更高效。
- 简单易懂。
缺点:
- 如果需要记录多个最大元素,此方法不适用。
方法三:多次遍历法
解题思路:
分两次遍历,第一次找到绝对值最大的元素,第二次遍历用于确定是否有多个相同最大值。
实现代码:
public class Main {
public static void main(String[] args) {
int[][] array = new int[][] {
{1, -2, 3, 4},
{5, -6, 7, 8},
{-9, 10, 11, 12}
};
int maxAbsValue = 0;
int maxRow = 0;
int maxCol = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
int absValue = Math.abs(array[i][j]);
if (absValue > maxAbsValue) {
maxAbsValue = absValue;
maxRow = i;
maxCol = j;
}
}
}
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
int absValue = Math.abs(array[i][j]);
if (absValue == maxAbsValue) {
count++;
}
}
}
System.out.println("绝对值最大的元素:" + maxAbsValue);
System.out.println("行号:" + maxRow);
System.out.println("列号:" + maxCol);
}
}
优点:
- 能够处理多个相同最大值的情况。
缺点:
- 需要两次遍历,可能在大型数组上效率较低。
总结与推荐:
从上面的三种方法中,方法二(一次遍历法)是最简单和高效的,因为它只需要一次遍历即可找到答案。方法一(嵌套循环法)虽然简单,但在大型数组上性能可能较低。方法三(多次遍历法)能够处理多个相同最大值的情况,但需要两次遍历,因此在大型数组上效率较低。
综合考虑,方法二是最好的选择,因为它简单、高效,并且满足了问题的基本要