We have a list of points
on the plane. Find the K
closest points to the origin (0, 0)
.
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
在点的集合中找出距离原点最近的k个点,显然要依据点距原点的远近对这些点进行排序,需要自己设置结构体存储各点到原点的距离,以及自定义比较函数,用sort进行排序。
class Solution {
public:
struct Point {//定义点结构体,index表示该点在vector数组中的索引,distance代表该点到原点的距离。
int index;
int distance;
};
vector point2;//存储点的集合,以便于排序
static bool comp(const Point &p1,const Point& p2) {//定义比较函数,一定要注意是static类型,不然会报错。
return p1.distance < p2.distance;
}
int cal(vector points) {//计算距离
return points[0] * points[0] + points[1]* points[1];
}
vector> kClosest(vector>& points, int K) {
vector> result;
for (int i = 0; i < points.size(); i++)
{
Point p;
p.index = i;
p.distance = cal(points[i]);
point2.push_back(p);
}
sort(point2.begin(), point2.end(), comp);//排序
for (int i = 0; i < K; i++) {
int index = point2[i].index;
result.push_back(points[index]);
}
return result;
}
};
在这里注意自定义sort函数的比较函数时,static和const的应用:
1、自定义的比较函数一定要是静态成员函数或是全局函数。因为非静态函数的调用依赖于具体的对象,但std::sort()函数是全局函数,无法调用一个非静态成员函数。
静态成员函数和全局函数不依赖具体对象,无须创建任何实例就可以访问。
2、const除了修饰常量之外,还可以修饰函数的“引用传递”,这样可以避免指针在函数体内部受到修改,在比较函数中返回的只是一个布尔值,不希望对传入的两个对象指针有什么变动。
另外传入参数是非内部数据结构时,如void fun(A a),执行时方法会复制一个a实例,并在方法体内对a实例进行操作,在这个过程中对象的构造、复制和析构都是要花费时间的。我们可以传入一个引用,但又不希望在这个过程中对a有更改,我们可以用const修饰参数,即 void fun( const A &a)。
从上面的例子中我们可以看到把非内部数据结构参数的“值传递”变为“const + 引用传递”,效果相同但是提高了效率。
当传入参数是内部数据结构(如int)时,不需要大费周章将void fun(int i)改为 void fun(const int &i)因为内部数据结构不存在对象的复制、析构等过程,两个的效率都很高。