方法一 排序
使用sort
函数,自定义排序类型;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
sort(points.begin(), points.end(), [](const vector<int>& u, const vector<int>& v) {
return u[0] * u[0] + u[1] * u[1] < v[0] * v[0] + v[1] * v[1];//匿名函数,自定义排序方式
});
return {points.begin(), points.begin() + K};
}
};
/**排序函数sort() 头文件: #include<algorithm>, 第三个参数可自定义的比较函数指针默认升序
* bool cmp( const Type1 &a, const Type2 &b)
* 比较a和b,如果想要升序则让 a < b,返回true;
* 如果想要降序则让 a > b,返回true;
* 同样地,可以比较ab的其他参数来确认,例如本题采用a,b代表的点的平方和升序排列;
* 第三个参数采用匿名函数的形式构建(函数语法):
[外部变量访问方式说明符] (参数) mutable noexcept/throw() -> 返回值类型
{
函数体;
};
*/
匿名函数:http://c.biancheng.net/view/7818.html