简体   繁体   English

如何在数组java中找到最大的三个数字?

[英]How to find the biggest three numbers in an array java?

I have an array of numbers and I need the biggest of three number with respective index value. 我有一个数字数组,我需要三个数字中最大数字和各自的索引值。 I have an array like this: 我有一个像这样的数组:

int [] value = new int[5];
value[0] = 8;
value[1] = 3;
value[2] = 5;
value[3] = 2;
value[4] = 7;

How to find the largest numbers and their index values? 如何找到最大的数字及其索引值?

I suspsect this is homework, so I'm going to give some help, but not a full solution. 我怀疑这是家庭作业,因此我将提供一些帮助,但不是完整的解决方案。

You need the biggest three numbers, as well as their index values? 您需要最大的三个数字,以及它们的索引值吗?

Well, walk over the array, keeping track of the highest three numbers you have found so far. 好吧,遍历数组,跟踪到目前为止找到的最高三个数字。 Also keep track of their index numbers. 同时跟踪其索引号。

You could start by doing this for only the biggest number and its index. 您可以从仅对最大数量及其索引进行操作开始。 That should be easy. 那应该很容易。 It takes two variables, eg BiggestNumber and indexOfBiggestNumber . 它需要两个变量,例如BiggestNumberindexOfBiggestNumber Start with finding the biggest number (trivial), then add some code to remember it's index. 首先找到最大的数字(琐碎的),然后添加一些代码以记住它的索引。

Once you have that, you can add some more code to keep track of the second biggest number and it's index as well. 一旦有了它,您就可以添加更多代码来跟踪第二大数字及其索引。

After that, you do the same for the third biggest number. 之后,对第三大数字执行相同的操作。

I have done it for you, and this works. 我已经为您完成了这项工作。

here goes the complete code: 这里是完整的代码:

import java.util.Arrays;

class tester{
    public static void main(String[] args){
        int [] value = new int[5];
        value[0] = 8;
        value[1] = 3;
        value[2] = 5;
        value[3] = 2;
        value[4] = 7;

        int size=value.length;

        int[] temp=(int[])value.clone();

        Arrays.sort(temp);

        for(int i=0;i<3;i++)
        {

           System.out.println("value: "+temp[size-(i+1)]+" index "+getIndex(value,temp[size-(i+1)]));
        }

    }

   static int getIndex(int[] value,int v){

       int temp=0;
        for(int i=0;i<value.length;i++)
        {
            if(value[i]==v)
            {
                temp=i;
                break;
            }
        }

        return temp;

    }

}

No need to traverse through array and keep tracking of so many variables , you can take advantage of already implemented methods like below. 无需遍历数组并跟踪这么多变量,您可以利用下面已经实现的方法。

I would suggest to use a List of Map.Entry<key,value > (where key=index and value=number) and then implement Comparator interface with overridden compare method (to sort on values). 我建议使用Map.Entry<key,value > (where key=index and value=number) ,然后使用覆盖的compare方法实现Comparator接口(以对值进行排序)。 Once you have implemented it just sort the list . 一旦实现,就可以对列表进行排序。

public static void main(String[] args) {

    int [] value={5,3,12,12,7};
    Map <Integer, Integer> map = new HashMap<Integer, Integer>();
    for(int k=0;k<value.length;k++)
        map.put(k, value[k]);

    List<Map.Entry<Integer, Integer>> list =
            new LinkedList<Map.Entry<Integer,Integer>>(map.entrySet());

    Collections.sort(list, new Comparator<Map.Entry<Integer,Integer>>() {
        @Override
        public int compare(
                Entry<Integer, Integer> e1,
                Entry<Integer, Integer> e2) {
            return e2.getValue().compareTo(e1.getValue());
        }
    });

   for(Entry<Integer, Integer> lValue:list)
        System.out.println("value = "+lValue.getValue() +" , Index = "+lValue.getKey());
}

Results: 结果:

 value = 12 , Index = 2
 value = 12 , Index = 3
 value = 7 , Index = 4
 value = 5 , Index = 0
 value = 3 , Index = 1

By this approach you can get top N largest numbers with their index. 通过这种方法,您可以获得带有索引的前N个最大数字。

To get the three biggest, basically, you sort, and pick the last three entries. 要获得最大的三个条目,请进行排序,然后选择最后三个条目。

Getting their indexes takes a little more work, but is definitely doable. 获取它们的索引需要花费更多的工作,但是绝对是可行的。 Simply bundle the number and its index together in a Comparable whose compareTo function only cares about the number. 只需将数字及其索引捆绑到一个Comparable中,其compareTo函数只关心数字。 Sort, get the last three items, and now you have each number and its index. 排序,得到最后三个项目,现在你必须每个数字其指数。

class IntWithIndex implements Comparable<IntWithIndex> {
    public int number, index;
    public IntWithIndex(number, index) { this.number = number; this.index = index; }
    public int compareTo(IntWithIndex other) { return number - other.number; }
}

...
IntWithIndex iwi[] = new IntWithIndex[yourNumbers.length];
for (int i = 0; i < yourNumbers.length; ++i) {
    iwi[i] = new IntWithIndex(yourNumbers[i], i);
}
Arrays.sort(iwi);

int largest      = iwi[iwi.length - 1].number;
int largestIndex = iwi[iwi.length - 1].index;
// and so on

以降序对数组进行排序,并显示前3个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Java中找到数组中最小和最大数量的项目? - How to find the smallest and the biggest number of items in array in Java? 将值添加到Array中并找到Java中最大的值 - Add values into Array and find the biggest one in java java 代码只需 6 个步骤即可找到 5 个(不是从数组中)中的最大和最小数字,每个步骤都需要在 2 个数字之间交换 - java code to find the biggest and smallest numbers out of 5 (not from array) using only 6 steps, each step you need to swap between 2 numbers 如何找到阵列中最大,第二大和第三大的数字,然后显示它们的序列位置? - How to find the biggest, second biggest and third biggest number in an array, then display their sequence location? 如何在Java中查找用户输入的三个数字的XOR - How to find XOR of three numbers taken input from the user in java 如何嵌套 if - else 用 4 个数字来找到最大的数字 - How to do nested if - else with 4 numbers to find biggest number Java数组中的最大数字? - Biggest number in the array for java? 如何找出最小,最大,平均数之和与随机数之和? - How to find out the smallest, biggest, average, sum of the numbers and numbers of numbers that are randomly enetered? Java - 在排序数组中查找总和小于数字的三个数字的所有组合 - Java - find all combinations of three numbers in sorted array that have a sum smaller than a number 如何使用 Java 在给定列表中查找具有重复项的最大数字的索引 - How to find the indexes of the biggest number in a given List with duplicates using Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM