zoukankan      html  css  js  c++  java
  • C++ pair用法

    刷leecode有这么一道题:

    给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 A[i] > B[i] 的索引 i 的数目来描述。

    返回 A 的任意排列,使其相对于 B 的优势最大化。

    我第一次想的是枚举法,然后超时了。

    class Solution {
    public:
        vector<int> advantageCount(vector<int>& A, vector<int>& B) {
            int max = 0;
            vector<int> maxVector;
            maxVector.insert(maxVector.begin(), A.begin(), A.end());
            sort(A.begin(), A.end());
            do
            {
                int count = 0;
                for(int i = 0; i < A.size(); i ++)
                {
                    if(A[i] > B[i] ) count++;
                }
                if(count > max)
                {
                    max = count;
                    maxVector.clear();
                    maxVector.insert(maxVector.begin(), A.begin(), A.end());            
                }
            } while(next_permutation(A.begin(), A.end()));
            return maxVector;
        }
    };

     后来想了想。换了一种方法做。通过用例了。

    1.首先两个数组进行排序,如果数组A[i] > B[j];,用pair存储B数组未排序的索引 可以认为B[j]之前的索引数组都是小于等于A[i].

    2. 则对数组A遍历,找到满足A[i]>B[j]的值,取代结果数组B中原先索引值。

    代码如下:

    class Solution {
    public:
        vector<int> advantageCount(vector<int>& A, vector<int>& B) {
            vector<pair<int, int> > b_matrix;
            vector<int> result;  //存储结果索引值
            result.resize(B.size());
            int flag = -1;
            for(int i = 0; i < B.size(); i++)
            {
                b_matrix.push_back(make_pair(B[i],i));
            }
            sort(A.begin(), A.end());
            sort(b_matrix.begin(), b_matrix.end());
            int j = A.size()-1;
            int k = A.size()-1;
            int i = 0;
            while(j>=0)
            {
                if(A[k] > b_matrix[j].first) {
                    result[b_matrix[j].second] = A[k];
                    k--;
                    j--;
                } else {
                    result[b_matrix[j].second] = A[i];
                    i++;
                    j--;
                }
                
            }
             
            return result;
        }
    };
    /*********example ******
    
    A[k]:          1 2  2 4 6
    b_matrix[j]:0 2 2 4 5
    6取代5原先的索引,  
    4取代2原先的索引,
    2取代0原来的索引值。
    其他位置则随意
    ****************/
    The Safest Way to Get what you Want is to Try and Deserve What you Want.
  • 相关阅读:
    winform+c#之窗体之间的传值 Virus
    ASP.NET 2.0 利用 checkbox获得选中行的行号, 在footer中显示 Virus
    .NET中的winform的listview控件 Virus
    我的书橱
    Expert .NET 2.0 IL Assembler·译者序一 写在一稿完成之即
    Verbal Description of Custom Attribute Value
    AddressOfCallBacks in TLS
    下一阶段Schedule
    2008 Oct MVP OpenDay 第二天 博客园聚会
    2008 Oct MVP OpenDay 第二天 颁奖·讲座·晚会
  • 原文地址:https://www.cnblogs.com/Shinered/p/9313954.html
Copyright © 2011-2022 走看看