gpt4 book ai didi

java - 找到数组中最小的正数

转载 作者:行者123 更新时间:2023-12-03 03:01:34 24 4
gpt4 key购买 nike

所以...我有:int array[] = {-8,2,0,5,-3,6,0,9};

我想找到最小的正数(上面的列表中是 2)

这就是我正在做的事情:

<小时/>
int array[] = {-8,2,0,5,-3,6,0,9};

int smallest=0;


for(int i=0;i<array.length;i++) // Find the first number in array>0 (as initial
// value for int smallest)
{
if(array[i]>0)
{
smallest=array[i];
break;// Break out of loop, when you find the first number >0
}
}


for(int i=0;i<array.length;i++) // Loop to find the smallest number in array[]
{

if(smallest>array[i]&&array[i]>0)
{
smallest=array[i];

}

}

System.out.println(smallest);

}
<小时/>

我的问题是:

我们可以减少步骤吗?有没有更智能/更短的方法来做到这一点,而无需其他数据结构。

谢谢。

最佳答案

is there any smarter/shorter way of doing it?

如果你想要更短,在 Java 8 中,你可以使用整数流:

int min = Arrays.stream(array).filter(i -> i >= 0).min().orElse(0);

(假设当数组为空时您对最小值 0 感到满意)。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com