viernes, 31 de agosto de 2018

3. Find two numbers within an array that their sum be K - java 8

3. Find two numbers within an array that their sum be K - java 8

 

Tools:

-JDK 8
-CoderPad/Sanbox

Solution:

import java.io.*;
 import java.util.*;
 import java.util.Map;
 import java.util.stream.Collectors;

 class Solution
 {
   public static void main(String[] args)
   {
     //Init array
     ArrayList<Integer> array = new ArrayList<Integer>();
     array.add(10);
     array.add(15);
     array.add(3);
     array.add(7);
     int k=17;
     List<Integer> result=getNumbers(k,array);
     /*Verify result. If result size is higher than 2 then the method found the       numbers */
     if(result.size()==2)
       System.out.println(result.get(0)+" + "+result.get(1)+" = "+ k);
     else
       System.out.println("No numbers found");

   }
   //Method which seach two numbers that get K by adding each other

   public static List<Integer> getNumbers(int k, List<Integer>array)
   {
     /*Get a sorted map of the array. This help to find numbers faster than prove one by one*/
     Map<Integer,Integer> map = array
                               .stream()
                               .sorted()
                               .collect(Collectors
                                         .toMap(Integer::intValue,Integer::intValue));
    
     List <Integer> result= new ArrayList<Integer>();
     //check the results
     for (Map.Entry<Integer, Integer> entry : map.entrySet())
     {
       //get the resudue between key and k
       int reo = k - entry.getKey();
      /*If resudue is equal to itself and resudue is higher than k then it is impossible to get k by adding other number in array*/
       if((reo == entry.getKey() && reo + entry.getKey()> k) )
       {
         break;
       }
       /*if resudue is lower than key + 1 then it is impossible to get k by adding */
       else if(reo < (1+entry.getKey()))
       {
         break;
       }
       /*search resudue in map if the residue is found then the solution is gotten*/
       else
       {
         if(map.containsKey(reo))
         {
           result.add(reo);
           result.add(entry.getKey());
           break;
         }
       }
     }
     return result;
   }
 }

Comment: Leave a comment if you have a doubt or you have a better solution, also if you have any suggestion

No hay comentarios:

Publicar un comentario