Answer the question
In order to leave comments, you need to log in
Java, this task is solved only through a set of if?
I need to remove from the array all numbers that are greater than neighboring ones.
For example
5 3 8 1 becomes 3 ( 5 is greater than 3 ) 1 ( 8 is greater than 3 and 1 ).
18, 1, 3, 6, 7, -5 becomes 1, 3, 6, -5, etc.
But faced with such difficulty, when index > 0 and < array.length-1, then we compare the previous number and the next one with the current one.
When index 0 is only next
when index array.length-1 is only previous.
It turns out that a big if with three conditions is the only way to complete the task?
Or is there a more elegant approach?
public static int[] removeMax(int[] array) {
int[] localMax = new int[array.length];
int s = -1;
for (int i = 0; i < array.length; i++) {
if ((i == 0 && array[i] > array[i + 1]) ||
(i != 0 && i != array.length - 1 && array[i] > array[i + 1] && array[i] > array[i - 1]) ||
(i == array.length-1 && array[i-1] < array[i])) {
continue;
}
localMax[++s] = array[i];
}
return Arrays.copyOf(localMax, s+1);
}
Answer the question
In order to leave comments, you need to log in
for (int i = 0; i < array.length; i++) {
double previous = i == 0 ? Double.POSITIVE_INFINITY : array[i - 1];
double next = i < array.length ? array[i + 1] : Double.POSITIVE_INFINITY;
int current = array[i];
if (current > previous || current > next)
continue;
localMax[++s] = current;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question