java 在数组中找到最小的正数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25500199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
find smallest positive number in an array
提问by Navchetan
So ... I have : int array[] = {-8,2,0,5,-3,6,0,9};
所以......我有: int array[] = {-8,2,0,5,-3,6,0,9};
I want to find the smallest positive number ( which in the list above is 2 )
我想找到最小的正数(在上面的列表中是 2 )
This is what i am doing :
这就是我正在做的:
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);
}
My question is :
我的问题是:
Can we reduce the number of steps ? Is there any smarter/shorter way of doing it, with no other data structure.
我们可以减少步数吗?有没有更聪明/更短的方法来做到这一点,没有其他数据结构。
Thanks.
谢谢。
采纳答案by NoobEditor
You do not need to have smallest=array[i]
, just initialize a variable with INTEGER.MAX_VALUE
or array[0]
and iterate over the array comparing the value with this variable.
您不需要有smallest=array[i]
,只需使用INTEGER.MAX_VALUE
or初始化变量array[0]
并迭代数组,将值与此变量进行比较。
This is achieved in O(n) timeand O(1) spaceand thats the best you can get! :)
这是在O(n) 时间和O(1) 空间内实现的,这是您能得到的最好的结果!:)
a simpler way would be
一个更简单的方法是
int[] array ={-1, 2, 1};
boolean max_val_present = false;
int min = Integer.MAX_VALUE;
for(int i=0;i<array.length;i++) // Loop to find the smallest number in array[]
{
if(min > array[i] && array[i] > 0)
min=array[i];
//Edge Case, if all numbers are negative and a MAX value is present
if(array[i] == Integer.MAX_VALUE)
max_val_present = true;
}
if(min == Integer.MAX_VALUE && !max_val_present)
//no positive value found and Integer.MAX_VALUE
//is also not present, return -1 as indicator
return -1;
return min; //return min positive if -1 is not returned
回答by assylias
is there any smarter/shorter way of doing it?
有没有更聪明/更短的方法来做到这一点?
If you want shorter, with Java 8, you can use a stream of ints:
如果你想要更短,在 Java 8 中,你可以使用整数流:
int min = Arrays.stream(array).filter(i -> i >= 0).min().orElse(0);
(assuming you are happy with a min of 0 when the array is empty).
(假设当数组为空时您对 min 为 0 感到满意)。
回答by amit
Without any prioe knowledge there is no way to avoid iterating the entire array.
如果没有任何 prioe 知识,就无法避免迭代整个数组。
You can however make sure you iterate it only once by removing the first loop, and instead just assign smallest = Integer.MAX_VALUE
. You can also add a boolean that indicates the array was changed to distinguish between cases where there is no positive integer, and cases where the only positive integer is Integer.MAX_VALUE
但是,您可以通过删除第一个循环来确保只迭代一次,而只是分配smallest = Integer.MAX_VALUE
. 您还可以添加一个布尔值,指示数组已更改,以区分没有正整数的情况和唯一正整数的情况Integer.MAX_VALUE
回答by Seyfülislam ?zdemir
You don't need two loops for this purpose.
为此,您不需要两个循环。
int smallest = Integer.MAX_VALUE;
for(int i=0;i<array.length;i++) {
if(array[i] > 0 && smallest > array[i])
{
smallest = array[i];
}
}
The only problem with this code is that after the loop you can't know that whether all elements are non-positive or at least one of them is Integer.MAX_INT and remaining is non-positive. You should add controls if you think that such a case is possible.
这段代码的唯一问题是,在循环之后,您无法知道是否所有元素都是非正数,或者其中至少一个是 Integer.MAX_INT 并且剩余元素是非正数。如果您认为可能出现这种情况,则应添加控件。
回答by Laurence Geng
A sample for you:
给你一个样本:
int array[] = {-8,2,0,5,-3,6,0,9};
int minPosNum = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
if(array[i] > 0 && array[i] < minPosNum){
minPosNum = array[i];
}
}
System.out.println(minPosNum);
回答by Michael Kleimann
int array[] = {-8,2,0,5,-3,6,0,9};
int minPos = Integer.MAX_VALUE;
for (int number : array) {
if (number > 0)
minPos = Math.min(number, minPos);
}
回答by qbit
You can try this to do it with 1 loop:
您可以尝试使用 1 个循环来执行此操作:
int array[] = {8,2,0,5,-3,6,0,9};
int smallestPositive = array[0];
for(int i = 1; i < array.length; i++){
if(smallestPositive > 0){
if(array[i] < smallestPositive && array[i] > 0)
smallestPositive = array[i];
}else
smallestPositive = array[i];
}
System.out.println(smallestPositive);
will print 2
System.out.println(smallestPositive);
将打印 2
回答by Aditya
You can try the following code
你可以试试下面的代码
import java.util.*;
public class SmallItem
{
public static void main(String args[])
{
int array[] = {-8,2,0,5,-3,6,0,9};
int number = Integer.MAX_VALUE;
ArrayList al = new ArrayList();
//Here we add all positive items into a ArrayList al
for(int i=1;i<array.length;i++){
if(array[i]>0){
al.add(new Integer(array[i]));
}
}
Iterator it = al.iterator();
while(it.hasNext()){
int n = ((Integer)it.next()).intValue();
if(n<number){
number = n;
}
}
System.out.println("Smallest number : " + number);
}
}
回答by bhavya
For C++
对于 C++
int smallest (int array[]){
int a;
for(int i=0;i<n;i++){
if(array[i]>0){
a=array[i];
break;
}
}
for (int i=0; i<n; i++){
if(array[i]<=a && array[i]>0){
a=array[i];
}
}
return a;
}
回答by Vic Key
In JavaScript
在 JavaScript 中
var inputArray = [-1,2,1,5,-20];
var arrayWithOnlyPositiveValue = [];
for(var i=0;i<inputArray.length;i++){
if(inputArray[i]>=0){
arrayWithOnlyPositiveValue.push(inputArray[i])
}
}
var min_of_array = Math.min.apply(Math, arrayWithOnlyPositiveValue);
console.log('---smallestPositiveValue----',min_of_array);