Created
October 27, 2018 15:50
-
-
Save bmuslih/76790d3135c35467a7b147884e71f9bc to your computer and use it in GitHub Desktop.
Amazon Problem 1 for ClosestXDestinations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Set; | |
import java.util.TreeMap; | |
public class AmazonSolution1 { | |
List<List<Integer>> ClosestXdestinations(int numDestinations, | |
List<List<Integer>> allLocations, | |
int numDeliveries) { | |
Map<Long, List<Integer>> distances = locationsByDistance(allLocations); | |
List<List<Integer>> deliveries = sortLocationsByDistance(distances, numDeliveries); | |
return deliveries; | |
} | |
private Map<Long, List<Integer>> locationsByDistance(List<List<Integer>> locations) { | |
Map<Long, List<Integer>> distances = new TreeMap<Long, List<Integer>>(); | |
for (List<Integer> location : locations) { | |
Integer x = location.get(0); | |
Integer y = location.get(1); | |
List<Integer> value = new ArrayList<>(); | |
value.add(x); | |
value.add(y); | |
distances.put((long) (x * x + y * y), value); | |
} | |
return (distances); | |
} | |
private List<List<Integer>> sortLocationsByDistance(Map<Long, List<Integer>> distances, int numDeliveries) { | |
Set<Long> keys = distances.keySet(); | |
List<List<Integer>> sortedDisances = new ArrayList<>(); | |
for (Long val : keys) { | |
if (sortedDisances.size() < numDeliveries) { | |
sortedDisances.add(distances.get(val)); | |
} else { | |
return sortedDisances; | |
} | |
} | |
return sortedDisances; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment