Java 打印2个最大值的索引
我的问题是,如果我在数组中输入两个maxvalue数字,例如100、10、100。如何获得打印两个索引号的输出 指数1和指数3的预期产出为100Java 打印2个最大值的索引,java,arrays,indexing,max,Java,Arrays,Indexing,Max,我的问题是,如果我在数组中输入两个maxvalue数字,例如100、10、100。如何获得打印两个索引号的输出 指数1和指数3的预期产出为100 索引中添加了1,因为我希望索引从1开始,而不是从零开始。将此添加到初始化中 HashSet<Integer> maxIndices = new HashSet<Integer>(); HashSet maxindex=newhashset(); 第二次遍历里程数组,并将任何最大值添加到哈希集 另一个选项是使用HashMap,
索引中添加了1,因为我希望索引从1开始,而不是从零开始。将此添加到初始化中
HashSet<Integer> maxIndices = new HashSet<Integer>();
HashSet maxindex=newhashset();
第二次遍历里程数组,并将任何最大值添加到哈希集
另一个选项是使用HashMap,其中第一个整数是里程数,第二个值是找到的里程数的正整数
因为它只通过一次,所以即使你在计算每一英里数,也可能会更快,而不仅仅是最后的最大里程数。当然,这取决于执行时的数据、编译器和环境条件
对于返回值,您需要一个定制的POJOJavabean,或者可以使用Pair或Tuple。(请参阅。)简单Java使用一系列for循环。下面的方法将返回一个2D int数组,每行由两列、最高数组值及其各自的数组索引号组成
public int[][] getAllMaxValues(int[] allValues) {
int maxVal = 0;
int counter = 0;
// Get the Max value in array...
for (int i = 0; i < allValues.length; i++) {
if (allValues[i] > maxVal) {
maxVal = allValues[i];
}
}
// How many of the same max values are there?
for (int i = 0; i < allValues.length; i++) {
if (allValues[i] == maxVal) {
counter++;
}
}
// Place all the max values and their respective
// indexes into a 2D int array...
int[][] result = new int[counter][2];
counter = 0;
for (int i = 0; i < allValues.length; i++) {
if (allValues[i] == maxVal) {
result[counter][0] = maxVal;
result[counter][1] = i;
counter++;
}
}
// Return the 2D Array.
return result;
}
将索引存储在数据结构中,而不是作为int(只能包含一个值)存储。您希望得到什么样的输出代码>应该是
int index=0代码>和索引=i+1
应该是index=i代码>因为你需要数组中的最大值及其索引。我不完全理解OP对这个代码段的期望,但我认为int index=1;是正确的,因为他正在添加解析为参数的数组的第一个值,所以他可能希望从搜索中忽略它—您的意思是0和2。
int[] allMiles = {100, 10, 100, 60, 20, 100, 34, 66, 74};
int[][] a = getAllMaxValues(allMiles);
for (int i = 0; i < a.length; i++) {
System.out.println("Array max value of " + a[i][0] +
" is located at index: " + a[i][1]);
}
Array max value of 100 is located at index: 0
Array max value of 100 is located at index: 2
Array max value of 100 is located at index: 5