So ... I have : 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 )
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:
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).
Without any prioe knowledge there is no way to avoid iterating the entire array.
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
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.
This is achieved in O(n) time and O(1) space and thats the best you can get! :)
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. 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:
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
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++
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
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;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.