patternjavaModerate
Find the 2 distinct highest values in an array
Viewed 0 times
distinctfindthearrayhighestvalues
Problem
I want to know if there is a way to improve my code. It finds the two highest values in an array, and these numbers need to be distinct.
I don't want to sort the values; I just want to find them.
My idea is to create a new array if the length is even and compare the pair of values to find the minimum and maximum values.
So, later, I find the second highest value.
I don't want to sort the values; I just want to find them.
My idea is to create a new array if the length is even and compare the pair of values to find the minimum and maximum values.
So, later, I find the second highest value.
package doze;
public class Elementos {
public int maxValue(int array[], int arrayLength) {
arrayLength = array.length;
if ((arrayLength % 2) > 0) {
arrayLength++;
int aux[] = array;
array = new int[arrayLength];
for (int i = 0; i array[i + 1]) {
if (array[i] > maxValue) {
maxValue = array[i];
}
if (array[i + 1] maxValue) {
maxValue = array[i + 1];
}
if (array[i] minValue) && (array[i] < maxValue)) {
minValue = array[i];
secondMaxValue = minValue;
}
i += 1;
}
return maxValue;
}
}Solution
Here's a simple implementation which will return the max (first index in return array) and second distinct max (second index in return array) value as an array. If the list is size zero or there is no distinct max value, then Integer.MIN_VALUE is returned.
/**
* @param integer array
* @return an array comprising the highest distinct value (index 0) and second highest distinct
* value (index 1), or Integer.MIN_VALUE if there is no value.
*/
public int[] findTwoHighestDistinctValues(int[] array)
{
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int value:array)
{
if (value > max)
{
secondMax = max;
max = value;
}
else if (value > secondMax && value < max)
{
secondMax = value;
}
}
return new int[] { max, secondMax };
}Code Snippets
/**
* @param integer array
* @return an array comprising the highest distinct value (index 0) and second highest distinct
* value (index 1), or Integer.MIN_VALUE if there is no value.
*/
public int[] findTwoHighestDistinctValues(int[] array)
{
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int value:array)
{
if (value > max)
{
secondMax = max;
max = value;
}
else if (value > secondMax && value < max)
{
secondMax = value;
}
}
return new int[] { max, secondMax };
}Context
StackExchange Code Review Q#23045, answer score: 11
Revisions (0)
No revisions yet.