I want to find out the minimum and maximum value in an array of integers.
Which one of the following ways would be the more efficient?
Sort the array and then look at start and end to get the minimum and maximum.
Convert the array into a list using
Arrays.asList()and then use theCollections.min()method.
The code where I want to use this is the following:
// Find missing number from an array of consecutive numbers arranged randomly
import java.util.Arrays;
public class MissingNumber {
public static void main(String[] args) {
int[] consecutiveRandomNos = { 3, 6, 5 };
System.out.println(addNumbers(consecutiveRandomNos));
System.out.println("The missing number is "
+ (returnSum(consecutiveRandomNos) - addNumbers(consecutiveRandomNos)));
}
public static int addNumbers(int... numbers) {
int result = 0;
for (int number : numbers) {
result += number;
}
return result;
}
public static int returnSum(int... nos) {
Arrays.sort(nos);
int max = nos[nos.length - 1];
int min = nos[0];
int total = 0;
for (int i = min; i <= max; i++) {
total += i;
}
return total;
}
}