Search This Blog

Wednesday, April 16, 2014

Algorithms - Search- Closest Numbers

Closest Numbers

The following is the solution to Hacker Rank problem Closest Numbers using Java.  For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.

Score:36/36
/**
 *
 */

/**
 *
 */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @author Arun.G
 *
 */
public class Solution{

       /**
        * @param args
        */
       static BufferedReader in = new BufferedReader(new InputStreamReader(
                     System.in));
 
       static ArrayList<Long> numArrayList = new ArrayList<Long>();
       //function to print the array
       static void printArray(ArrayList<Long> list)
       {
              for(int i=0;i<list.size();i++)
              {
              System.out.print(list.get(i)+"\t");
              }
       }
  //function to get the closest numbers
       static void getClosestNumbers(ArrayList<Long> list)
       {
              ArrayList<Long> closestNumbersList = new ArrayList<Long>();
              long min = Long.MAX_VALUE;
              for(int i=0;i<list.size()-1;i++)
              {
                     long numA = list.get(i);
                     long numB = list.get(i+1);
                     long diff = Math.abs(numB-numA);
                     if(diff<min)//if less than min,its a new min so delete old list and add
                     {
                           min = diff;
                           closestNumbersList.clear();
                           closestNumbersList.add(numA);
                           closestNumbersList.add(numB);
                     }
                     else if(diff==min)// this is the known min diff, add numbers to list
                     {
                           closestNumbersList.add(numA);
                           closestNumbersList.add(numB);
                     }
              }
              //sort the list
              Collections.sort(closestNumbersList);
              //print the closest numbers
              printArray(closestNumbersList);
       }
       public static void main(String[] args) throws NumberFormatException, Exception {
              // TODO Auto-generated method stub
              long N = Long.valueOf(in.readLine());
              String[] numbers = in.readLine().split(" ");
              //get the numbers
              for(int i=0;i<numbers.length;i++)
              {
                     long num = Long.valueOf(numbers[i]);
                     numArrayList.add(num);
              }
              //sort the list
              Collections.sort(numArrayList);
              //get the closest numbers
              getClosestNumbers(numArrayList);
             
       }

}

No comments:

Post a Comment

Labels