程序,从C ++中的不同列表中查找所选择元素之间的最小差异
假设我们有一个列表列表,我们必须找到一个最小的差异,该差异可以通过从每个列表中选取一个值,并取所选取元素的最大数量与最小数量之间的差来形成。
因此,如果输入类似于列表=[[30,50,90],[85],[35,70]],则输出将为20,因为我们可以采用90、85、70和90-70=20
在线示例
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
struct Cmp {
bool operator()(vector<int>& a, vector<int>& b) {
return !(a[0] < b[0]);
}
};
class Solution {
public:
int solve(vector<vector<int>>& lists) {
int maxVal = INT_MIN;
int ret = INT_MAX;
priority_queue<vector<int>, vector<vector<int>>, Cmp> pq;
int n = lists.size();
for (int i = 0; i < n; i++) {
sort(lists[i].begin(), lists[i].end());
pq.push({lists[i][0], i, 0});
maxVal = max(lists[i][0], maxVal);
}
while (pq.size() == n) {
vector<int> temp = pq.top();
pq.pop();
ret = min(ret, maxVal - temp[0]);
temp.back()++;
if (temp.back() < lists[temp[1]].size()) {
maxVal = max(maxVal, lists[temp[1]][temp.back()]);
temp[0] = lists[temp[1]][temp.back()];
pq.push(temp);
}
}
return ret;
}
};
int solve(vector<vector<int>>& lists) {
return (new Solution())->solve(lists);
}
int main(){
vector<vector<int>> v = {{30, 50, 90},{85},{35, 70}};
cout << solve(v);
}输入值
{{30, 50, 90},{85},{35, 70}}输出结果20