// https://discuss.leetcode.com/topic/50527/java-10ms-solution-no-priority-queue class Solution { public: vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> buf1(nums1.size(), 0); vector<pair<int, int>> vpair; int minV = INT_MAX; int tmpV = -1; while (vpair.size() < k) { for (int i=0; i<nums1.size(); ++i) { if (buf1[i] < nums2.size() && nums1[i] + nums2[buf1[i]] < minV) { minV = nums1[i] + nums2[buf1[i]]; tmpV = i; } } if (tmpV != -1) { vpair.push_back(make_pair(nums1[tmpV], nums2[buf1[tmpV]])); buf1[tmpV] = buf1[tmpV] + 1; minV = INT_MAX; tmpV = -1; } else { break; } } return vpair; } };
时间: 2024-10-14 17:48:28