【发布时间】:2018-04-12 07:19:01
【问题描述】:
这是一种桶排序算法,试图从点 (0,0) 获取 K 个最近的位置。这是通过计算这些位置的距离并根据距离对它们进行分桶来完成的。如果两个位置距离相等,则优先考虑具有壁橱 x 和 y 的位置(如果 x 值相同)
以下解决方案的时间复杂度是多少? O(NlogN) 或 O(KNlogN) 或其他任何东西
// 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)
}
}
【问题讨论】:
标签: time-complexity bucket-sort