[Lucky Algorithm] Minimum Absolute Difference in an Array (50/77)
Minimum Absolute Difference in an Array (Hacker Rank)
Consider an array of integers, . We define the absolute difference between two elements, and (where ), to be the absolute value of .
Given an array of integers, find and print the minimum absolute difference between any two elements in the array.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int minimumAbsoluteDifference(int n, int[] arr) {
Arrays.sort(arr);
int min = -1;
for(int i = 0; i < n-1; i++){
int diff = Math.abs(arr[i] - arr[i+1]);
if(diff < min || min == -1){
min = diff;
}
if(diff == 0){
return 0;
}
}
return min;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int arr_i = 0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
int result = minimumAbsoluteDifference(n, arr);
System.out.println(result);
in.close();
}
}
행운의 77문제 프로젝트
행운의 77문제 프로젝트는 한 달동안 알고리즘 문제 77개를 푸는 프로젝트입니다.
(한달은 이미 많이 지났지만...그래도 77문제는 될 수 있도록!)