/*
* @lc app=leetcode.cn id=870 lang=cpp
*
* [870] 优势洗牌 参考别人写的
*/
// @lc code=start
// nums1升序
// nums2降序
// nums2的最大值,若nums1最大值能胜过就输出,否则输出最小值
class Solution {//大的值在上面 top
struct cmp
{
bool operator()(const pair<int,int>&a,const pair<int,int>& b){
return a.second<b.second;
}
};
public:
vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(),nums1.end());//默认升序
priority_queue< pair<int,int>, vector<pair<int,int>>,cmp>q;
int n=nums2.size();
for(int i=0;i<n;i++){
q.push({i,nums2[i]});
}//nums2排序需要考虑index
int left=0,right=n-1;//双指针
vector<int>res(n);//结果
while (!q.empty())
{
int index=q.top().first;
int max_value = q.top().second;
q.pop();
if(nums1[right]>max_value){
res[index]=nums1[right];
right--;
}
else{
res[index]=nums1[left];
left++;
}
}
return res;
}
};
// @lc code=end
//升序队列
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;
/*
* @lc app=leetcode.cn id=18 lang=cpp
*
* [18] 四数之和
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> nSumTarget(vector<int>&nums,int n,int start,int target){
int sz=nums.size();
vector<vector<int>> res;//记录结果
if(n<2||sz<n) return res;
if(n==2){
//双指针操作
int lo=start,hi=sz-1;
while (lo<hi){
int sum = nums[lo]+nums[hi];
int left = nums[lo],right = nums[hi];
if(sum<target){
while (lo<hi&&nums[lo]==left)lo++;
}
else if(sum>target){
while (lo<hi&&nums[hi]==right)hi--;
}
else{
res.push_back({left,right});
while (lo<hi&&nums[lo]==left)lo++;
while (lo<hi&&nums[hi]==right)hi--;
}
}
}
else{
//n>2时候递归计算(n-1)Sum的结果
for(int i=start;i<sz;i++){
// std::cout << "1" << std::endl;
vector<vector<int>> sub = nSumTarget(nums,n-1,i+1,target-nums[i]);
for(vector<int>&arr :sub){
arr.push_back(nums[i]);
res.push_back(arr);
}
while (i<sz-1&&nums[i]==nums[i+1]){
i++;
}
}
}
return res;
}
// vector<vector<int>> threeSum(vector<int>& nums) {
// sort(nums.begin(),nums.end());
// return nSumTarget(nums,3,0,0);
// }
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
return nSumTarget(nums,4,0,target);
}
};
// @lc code=end