java – 最大的5数组的10个数字没有排序
发布时间:2020-05-27 04:59:58 所属栏目:Java 来源:互联网
导读:这是我的代码,找到一个数组的最大数字,但我似乎不明白如何获得前5个数字,并将它们存储在数组中,然后检索它们 以下是代码: public class Max { public static void main (String[] args) { int i; int large[]=new int[5]; int arr
|
这是我的代码,找到一个数组的最大数字,但我似乎不明白如何获得前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. 我得到以下输出:
(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
