The absolute difference is the positive difference between two values a and b, is written |a-b| or |b-a| and they are equal. If a=3 and b=2, |3-2| = |2-3| = 1. Given an array of integers, find the minimum absolute difference between any two elements in the array.
Example.
arr = [-2,2,4]
There are 3 pairs of numbers:[-2,-2], [-2,4] and [2,4]. The absolute differences for these pairs are |(-2) - 2| = 4, |(-2) - 4| = 6 and . |2 - 4| = 2. The minimum absolute difference is 2.
Function Description
Complete the minimumAbsoluteDifference function in the editor below. It should return an integer that represents the minimum absolute difference between any pair of elements.
minimumAbsoluteDifference has the following parameter(s):
Returns
Input Format
The first line contains a single integer n, the size of arr.
The second line contains n space-separated integers, arr[i].
간단한 문제이다. 자바에서 절대값을 구할때는 Math.abs()를 사용하면 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
private static int minimumAbsoluteDifference(int[] arr) {
int min = 2000000000;
Arrays.sort(arr);
for (int i = 0; i < arr.length-1; i++) {
min = Math.min(min, Math.abs(arr[i] - arr[i+1]));
}
return min;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
System.out.println(minimumAbsoluteDifference(arr));
br.close();
}
}