简单
技术面试0 次浏览百度的地图业务需要处理大量的地理坐标数据。请设计一个简单的数据结构来存储地理坐标点,并实现一个函数来计算两个坐标点之间的距离。假设地球是一个完美的球体,半径为 6371 千米。
百度算法工程师
数据结构地理坐标地图业务
答题要点
推荐使用面向对象的设计思路。首先定义一个表示地理坐标点的类,然后在类中实现计算距离的方法。关键要点如下:1. 定义类:创建一个 `Coordinate` 类,包含经度和纬度属性。2. 初始化:在类的构造函数中初始化经度和纬度。3. 距离计算:使用 Haversine 公式计算两个坐标点之间的距离。4. 封装方法:将距离计算逻辑封装在类的方法中。示例话术:可以这样定义类和方法:pythonimport mathclass Coordinate: def __init__(self, lat, lon): self.lat = lat self.lon = lon def distance_to(self, other): dlat = math.radians(other.lat - self.lat) dlon = math.radians(other.lon - self.lon) a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(self.lat)) * math.cos(math.radians(other.lat)) * math.sin(dlon / 2) * math.sin(dlon / 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return 6371 * c