zoukankan      html  css  js  c++  java
  • 870. Advantage Shuffle

    问题:

    给定两个size相同的数组A,B

    对A进行排列,使得同位 i 上对数,A[i]>B[i],求使得满足这样条件元素最多的A的排列。

    Example 1:
    Input: A = [2,7,11,15], B = [1,10,4,11]
    Output: [2,11,7,15]
    
    Example 2:
    Input: A = [12,24,8,32], B = [13,25,32,11]
    Output: [24,32,8,12]
     
    
    Note:
    1 <= A.length = B.length <= 10000
    0 <= A[i] <= 10^9
    0 <= B[i] <= 10^9
    

      

    解法:贪婪算法

    思想:对A进行从小到大排序,

    遍历B,对B的每一个元素b,在A中从小到大找A[i]>b最小的A[i],

    若不存在这样的A[i],则用当前A中最小的A[0]去对应b。

    代码参考:

     1 class Solution {
     2 public:
     3     vector<int> advantageCount(vector<int>& A, vector<int>& B) {
     4         vector<int> res;
     5         int i=0;
     6         sort(A.begin(), A.end());
     7         for(int b:B){
     8             int size=A.size();
     9             for(i=0; i<A.size(); i++){
    10                 if(A[i]>b){
    11                     res.push_back(A[i]);
    12                     A.erase(A.begin()+i);
    13                     break;
    14                 }
    15             }
    16             if(A.size()>0 && i==size){
    17                 res.push_back(A[0]);
    18                 A.erase(A.begin());
    19             }
    20         }
    21         return res;
    22     }
    23 };

    ♻️优化,使用C++的multiset,(保存排序A)

    使用upper_bound(b)二分查找来找到第一个大于b的数值。

    代码参考:

     1 static auto x = []() {
     2     ios_base::sync_with_stdio(false);
     3     cin.tie(NULL);
     4     return NULL;
     5 }();
     6 
     7 class Solution {
     8 public:
     9     vector<int> advantageCount(vector<int>& A, vector<int>& B) {
    10         multiset<int> s(A.begin(), A.end());
    11         vector<int> res;
    12         for(int b:B){
    13             auto p=s.upper_bound(b);
    14             if(p==s.end()) p=s.begin();
    15             res.push_back(*p);
    16             s.erase(p);
    17         }
    18         return res;
    19     }
    20 };
  • 相关阅读:
    SQL优化
    Mybatis
    Spring MVC(总结二)
    ES多机集群配置
    ES索引,分片,一致性
    ElasticSearch关于索引库的命令操作
    试题01(一)
    Linux安装配置elastic search
    Windows安装配置elastic search
    SpringBoot(二)
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12889815.html
Copyright © 2011-2022 走看看