Given a one-dimensional array of non-negative integers, for example, {1, 3, 8, 45, 21, 14} P must be given the difference P between the two closest values. For a given array, P = 2, since 3-1 = 2. How to do it in Java?
2 answers
- Sort the array.
- Run through the array, calculating the difference of neighboring elements
- When running, remember the current smallest one in the piece and update it with the arrival of a new difference
- At the end of the run output the smallest difference.
- Could you write an example of 2-3 points? - Hev
- @Hev: Well, this is a training task, you yourself should.
for (int i = 0; i < list.size() - 2; i++) { int diff = list[i + 1] - list[i]; if (bestDiff > diff) { /* что делаем тут? */ } }for (int i = 0; i < list.size() - 2; i++) { int diff = list[i + 1] - list[i]; if (bestDiff > diff) { /* что делаем тут? */ } }- VladD - @Hev: It is clear why to
list.size() - 2? - VladD - @VladD but isn't it `list.size () - 1`? - Senior Pomidor
- @SeniorAutomator: ugh, really! Thank! - VladD
|
Option with stream'ами :
Integer[] array = new Integer[]{1, 3, 8, 45, 21, 14}; Arrays .stream(array) .flatMap(element -> Arrays.stream(array).map(otherElement -> otherElement - element)) .filter(e -> e > 0) .min(Comparator.naturalOrder()) .ifPresent(System.out::println); Ps. This code does not take into account duplicates in the array.
- Thank you, but there will be duplicates there - Hev
|