It's kind of bucket sort algorithm, trying to get K nearest locations from point (0,0). This is being done by calculating distances of these locations and bucketing them based on distance. If two locations are at equal distance then priority given to location with closet x and then y(if x values are same)
What is time complexity of following solution? O(NlogN) or O(KNlogN) or anything else
// java
Input: int k, List<Location>
Output: List<Location>
public class Location {
//constructor x and y
int x;
int y;
//get
//set
//hashcode and equals
}
public class Solution {
public List<Location> returnKNearestLocation(int k, List<Location> locations) {
Map<Float, Set<Location>> map = new TreeMap<>();
for(Location loc: locations) {
float dist = calculateDistance(new Location(0,0), loc);
List<Location> temp = map.getOrDefault(dist, new HashSet());
temp.add(loc);
map.put(temp);
}
List<Location> result = new ArrayList<>();
int size = k;
while(size > 0) {
for(Float key : map.keySet()) {
Set<Location> loc = map.get(key);
Collection.sort(loc, p1, p2 -> {
return p1.x.equals(p2.x)? p1.y.compare(p2.y) : p1.x.compare(p2.x);
});
for(Location currLoc : loc) {
result.add(currLoc);
if(result.size() == k) {
return result;
}
}
size = size - loc.size();
}
}
return result;
}
private float calculateDistance(Location p, Location q) {
// calculate distance Math.sqrt((P.x - Q.x)^2 + (P.y - Q.y)^2)
}
}
I'd say O(N*log(N)).
float dist = calculateDistance(new Location(0,0), loc)
is O(1).put()
and getOrDefault()
in a TreeMap
are O(log(N)). Other implementations offer O(1). I'd take a look at HashMap
.add
in a HashSet
is O(1) (amortized).add
in an ArrayList
is O(1) (amortized)I'd take a look at HashMap
instead of TreeMap
.
So, assuming I'm not wrong: