简体   繁体   English

找到数组中最小的正数

[英]find smallest positive number in an array

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. 谢谢。

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流:

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). (假设你对数组为空时的最小值为0感到满意)。

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 . 但是,您可以确保通过删除第一个循环仅迭代一次,而只是分配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 您还可以添加一个布尔值,指示数组已更改以区分没有正整数的情况,以及唯一正整数为Integer.MAX_VALUE

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_VALUEarray[0]初始化变量,并迭代数组,将值与此变量进行比较。

This is achieved in O(n) time and O(1) space and 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

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. 此代码的唯一问题是在循环之后,您无法知道所有元素是否为非正数或至少其中一个是Integer.MAX_INT且剩余是非正数。 You should add controls if you think that such a case is possible. 如果您认为可能出现这种情况,则应添加控件。

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);
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);
}

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 将打印2

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);
    }
}

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;
}

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);
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { -1, 2, 1, -2, 11, 23, 44 };
            int min = MinArray(array);
            Console.WriteLine(min.ToString() + " is the minimum number!");
            Console.ReadKey();
        }
        public static int MinArray(int[] array)
        {
            int minimumNumber = Int32.MaxValue;
            foreach (int i in array)
            {
                if (i < minimumNumber && i > 0)
                {
                    minimumNumber = i;
                }

            }

            return minimumNumber;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM