classSolution { public: vector<vector<int>> kClosest(vector<vector<int>>& points, int K) { map<int, vector<vector<int>>> distance; for (constauto point: points) { distance[point[0]*point[0] + point[1]*point[1]].push_back(point); } vector<vector<int>> results; int i = 0; for (constauto d: distance) { for (constauto point: d.second) { results.push_back(point); i++; if (i >= K) { return results; } } } return results; } };
976. Largest Perimeter Triangle
只用找最大的3个可以组成三角形的数就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intlargestPerimeter(vector<int>& A){ int result = 0; sort(A.begin(), A.end()); for (int i = A.size() - 3; i >= 0; i--) { if (A[i] + A[i+1] > A[i+2]) { result = A[i] + A[i+1] + A[i+2]; break; } } return result; } };
974. Subarray Sums Divisible by K
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intsubarraysDivByK(vector<int>& A, int K){ unordered_map<int, int> prefix_sum; int sum = 0; int result = 0; prefix_sum[0] = 1; for (int i = 0; i < A.size(); i++) { sum = (sum + A[i] % K + K) % K; result += prefix_sum[sum]; prefix_sum[sum]++; } return result; } };