查找数组中的第二个最小整数 [英] Finding the second smallest integer in array

查看:76
本文介绍了查找数组中的第二个最小整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要在作业中递归地找到一个数组中的第二个最小整数.但是,为了更好地理解该主题,我想先通过本网站迭代地进行迭代,然后自己进行递归.

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iteratively first (with the help of this website) and recursively on my own.

不幸的是,迭代地进行操作非常令人困惑.我知道解决方案很简单,但是我无法解决.

Unfortunately, doing it iteratively is quite confusing. I understand that the solution is simple but i can't wrap my head around it.

到目前为止,以下是我的代码:

Below is my code, so far:

public static void main(String[] args) 
{
    int[] elements  = {0 , 2 , 10 , 3, -3 }; 
    int smallest = 0; 
    int secondSmallest = 0; 

    for (int i = 0; i < elements.length; i++)
    {
        for (int j = 0; j < elements.length; j++)
        {
            if (elements[i] < smallest)
            {
                smallest = elements[i];

                if (elements[j] < secondSmallest)
                {
                    secondSmallest = elements[j];
                }
            }
        }

    }

    System.out.println("The smallest element is: " + smallest + "\n"+  "The second smallest element is: " + secondSmallest);
}

这适用于一些数字,但不是全部.数字会变化,因为内部if条件的效率不如外部if条件.

This works for a few numbers, but not all. The numbers change around because the inner if condition isn't as efficient as the outer if condition.

禁止数组重排.

推荐答案

尝试一下.最小的数字是第一个条件时,第二个条件用于捕获事件

Try this one. Second condition is used to catch an event when the smallest number is the first

    int[] elements = {-5, -4, 0, 2, 10, 3, -3};
    int smallest = Integer.MAX_VALUE;
    int secondSmallest = Integer.MAX_VALUE;
    for (int i = 0; i < elements.length; i++) {
        if(elements[i]==smallest){
          secondSmallest=smallest;
        } else if (elements[i] < smallest) {
            secondSmallest = smallest;
            smallest = elements[i];
        } else if (elements[i] < secondSmallest) {
            secondSmallest = elements[i];
        }

    }

@Axel的

UPD

int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
    if (elements[i] < smallest) {
        secondSmallest = smallest;
        smallest = elements[i];
    } else if (elements[i] < secondSmallest) {
        secondSmallest = elements[i];
    }
}

这篇关于查找数组中的第二个最小整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆