I am trying to find next adjacent bigger number for an input number from given list of numbers.
Please help me with Java code or algorithm to implement below.
Given list of numbers = [50, 20, 40, 30, 10]
Input number = 15
Output = 20 (next adjacent bigger number of 15)
CodePudding user response:
You could iterate through the array and find out which is the one that you want.
//Add the imports BEFORE the "class{"
import java.util.Arrays;
import java.util.List;
private static int check_bigger_adjacent(final int input_number){
final int[] list_of_numbers={50, 20, 40, 30, 10};
//Sort the array.
final List<int> sorted_list=Arrays.asList(list_of_numbers);
sorted_list.sort();
final int[] new_sorted_list_of_numbers=sorted_list.toArray();
for(int i:new_sorted_list_of_numbers){
if(i>input_number)
return i;
}
// If the number is way too big for your included array.
return -1;
}
CodePudding user response:
The simplest approach is like filtering all the greatest numbers and then finding the smallest among them.
import java.util.*;
public class Main{
public static void main(String[] args) {
int[] numbers = {50, 20, 40, 30, 10};
int target = 9;
System.out.println("Adjacent Greatest number of " target " is " findAdjacentGreatest(numbers,target));
}
// METHOD TO FIND THE ADJACENT GREATEST NUMBER
public static int findAdjacentGreatest(int[] numbers, int target) {
// USED ARRAY LIST BECAUSE WE DONT KNOW THE CORRECT SIZE OF THE ARRAY TO INITIALISE THE ARRAY
ArrayList<Integer> greaterNumbers = new ArrayList<Integer>();
for (int i=0; i<numbers.length;i ) {
if(numbers[i] > target) {
greaterNumbers.add(numbers[i]);
}
}
// RETURN THE MINIMUM OF THE GREATEST NUMBERS
return Collections.min(greaterNumbers);
}
}
CodePudding user response:
THIS SHOWS THE CORE IDEA BUT DOES NOT ANSWER THE QUESTION CORRECTLY/FULLY
The best thing to do in this case would be to create a test case called isBiggest
or even just a small loop wherever this is going.
int biggest = /*the first number*/
int test = /*the next number*/
if (test > biggest)
/*then this is the new biggest number*/
Keep that loop going till the end and you should find it :D
EDIT for correction
This will find the biggest number and NOT the second-biggest number.