加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 最大的5数组的10个数字没有排序

发布时间:2020-12-14 16:31:55 所属栏目:Java 来源:网络整理
导读:这是我的代码,找到一个数组的最大数字,但我似乎不明白如何获得前5个数字,并将它们存储在数组中,然后检索它们 以下是代码: public class Max { public static void main (String[] args) { int i; int large[]=new int[5]; int array[] = {33,55,13,46,87,42
这是我的代码,找到一个数组的最大数字,但我似乎不明白如何获得前5个数字,并将它们存储在数组中,然后检索它们

以下是代码:

public class Max {


    public static void main (String[] args) 
    {
        int i;
        int large[]=new int[5];     
        int array[] = {33,55,13,46,87,42,10,34,43,56};
        int max = array[0]; // Assume array[0] to be the max for time-being

        //Looping n-1 times,O(n)
        for(  i = 1; i < array.length; i++) // Iterate through the First Index and compare with max
        {
            // O(1)
            if( max < array[i])
            {
                // O(1)
                max = array[i];// Change max if condition is True
                large[i] = max;
            }
        }
        for (int j = 0; j<5; j++)
        {
            System.out.println("Largest 5 : "+large[j]);
        }
        System.out.println("Largest is: "+ max);
        // Time complexity being: O(n) * [O(1) + O(1)] = O(n)
    }

}

我正在使用一个数组来存储5个数字,但是当我运行它时,它不是我想要的.
任何人都可以帮我吗?

解决方法

看下面的代码:
public static void main(String args[]) {
    int i;
    int large[] = new int[5];
    int array[] = { 33,56 };
    int max = 0,index;
    for (int j = 0; j < 5; j++) {
        max = array[0];
        index = 0;
        for (i = 1; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
                index = i;
            }
        }
        large[j] = max;
        array[index] = Integer.MIN_VALUE;

        System.out.println("Largest " + j +  " : " + large[j]);
    }
}

注意:如果您不想更改输入的数组,请复制它并对复制的数组执行相同的操作.

看看Integer.MIN_VALUE.

我得到以下输出:

Largest 0 : 87

Largest 1 : 56

Largest 2 : 55

Largest 3 : 46

Largest 4 : 43

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读