LeetCode-973. 最接近原点的 K 个点

版权声明:孔庆鑫 https://blog.csdn.net/kongqingxin12/article/details/86417440

973. 最接近原点的 K 个点

class Solution {
public:
	vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
		//将所有坐标点分类
		map<int, vector<vector<int>>>coordinate_from_the_origin;
		for (int i = 0; i < points.size(); ++i) {
			int length = pow(points[i][0], 2) + pow(points[i][1], 2);
			coordinate_from_the_origin[length].push_back(points[i]);
		}
		//处理并得到结果
		vector<vector<int>>ans;
		int sum = 0;
		for (auto j = coordinate_from_the_origin.begin(); j != coordinate_from_the_origin.end(); ++j) {
			pair<int, vector<vector<int>>>tmp = *j;
			sum += tmp.second.size();
			ans.insert(ans.end(), tmp.second.begin(), tmp.second.end());
			if (sum == K)
				break;
		}
		return ans;
	}
};
import operator
class Solution:
    def kClosest(self, points, K):
        """
        :type points: List[List[int]]
        :type K: int
        :rtype: List[List[int]]
        """
        coordinate_from_the_origin = {}
        for i in points:
            length = pow(i[0], 2) + pow(i[1], 2)
            coordinate_from_the_origin.setdefault(length,[]).append(i)
        coordinate_from_the_origin=dict(sorted(coordinate_from_the_origin.items(),key=operator.itemgetter(0)))
        ans = []
        sum = 0
        for i in coordinate_from_the_origin:
            sum += len(coordinate_from_the_origin[i])
            ans.extend(coordinate_from_the_origin[i])
            if sum == K:
                break
        return ans

猜你喜欢

转载自blog.csdn.net/kongqingxin12/article/details/86417440