我试图在不使用数组的情况下找到集合中的两个最小数字。这是代码:

Scanner in = new Scanner(System.in);

int N = in.nextInt();
int min = in.nextInt();


for(int i = 1; i < N; i++){
    int a = in.nextInt();

    if(a < min){
        min = a;
    }
}

System.out.println(min);


它找到最小的数字,但第二个最小的数字什么也没有。

我怎么做?

请注意,我是Java的完整入门者,因此非常容易进行解释和提供帮助)

最佳答案

这是您必须添加的一种条件:

Scanner in = new Scanner(System.in);

int N = in.nextInt();
int min = Integer.MAX_VALUE;
int secondMin = Integer.MAX_VALUE;

for(int i = 0; i < N; i++){
    int a = in.nextInt();

    if(a < min){
        secondMin = min; // the current minimum must be the second smallest
        min = a; // allocates the new minimum
    }

    else if (a < secondMin) {
        secondMin = a; // if we did not get a new minimum, it may still be the second smallest number
    }
}

System.out.println(min);
System.out.println(secondMin);

关于java - 一组中的两个最小数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24223577/

10-10 01:02