Sorting to the rescue, another HackerRank problem
This is the problem: https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array:
Consider an array of integers, . We define the absolute difference between two elements, and (where ), to be the absolute value of .
One way that I found to solve the problem was in NLogN-time (I think there is a linear solution to this problem too): (quick)sort the input array, assume the best solution to be a[1]-a[0], and check all others a[i+1]-a[i]. Code is below, cheers, Marcelo.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp, Int32.Parse);
Array.Sort(a);
long solution = a[1] - a[0];
for (int i = 1; i < n - 1; i++)
{
long candidate = a[i + 1] - a[i];
if (candidate < solution) solution = candidate;
}
Console.WriteLine(solution);
}
}
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.
Input Format
The first line contains a single integer denoting (the number of integers).
The second line contains space-separated integers describing the respective values of .
The second line contains space-separated integers describing the respective values of .
Constraints
Output Format
Print the minimum absolute difference between any two elements in the array.
Sample Input 0
3
3 -7 0
Sample Output 0
3
One way that I found to solve the problem was in NLogN-time (I think there is a linear solution to this problem too): (quick)sort the input array, assume the best solution to be a[1]-a[0], and check all others a[i+1]-a[i]. Code is below, cheers, Marcelo.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp, Int32.Parse);
Array.Sort(a);
long solution = a[1] - a[0];
for (int i = 1; i < n - 1; i++)
{
long candidate = a[i + 1] - a[i];
if (candidate < solution) solution = candidate;
}
Console.WriteLine(solution);
}
}
Comments
Post a Comment