Sorting is useful as the first step in many different tasks. The most common task is to make finding things easier, but there are other uses as well. In this case, it will make it easier to determine which pair or pairs of elements have the smallest absolute difference between them.
For example, if you've got the list , sort it as  to see that several pairs have the minimum difference of . The return array would be .
Given a list of unsorted integers, , find the pair of elements that have the smallest absolute difference between them. If there are multiple pairs, find them all.



Question from hackerrank.


Solution in C# - 


class Solution {

    static int[] closestNumbers(int[] arr) {
        List<int> newarr = new List<int>();
        Array.Sort(arr);
        long min = int.MaxValue;
        for(int i=0; i<arr.Length-1; i++)
        {
            long x = Math.Abs(arr[i]-arr[i+1]);
            if(x < min)
            min = x;
        }
       
        for(int i=0; i<arr.Length-1; i++)
        {
            long x = Math.Abs(arr[i]-arr[i+1]);
            if(x == min)
            {
                newarr.Add(arr[i]);
                newarr.Add(arr[i+1]);
            }
        }
        return newarr.ToArray();
    }

    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int n = Convert.ToInt32(Console.ReadLine());

        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
        int[] result = closestNumbers(arr);

        textWriter.WriteLine(string.Join(" ", result));

        textWriter.Flush();
        textWriter.Close();
    }

}

Post a Comment

Previous Post Next Post