题解 | #数据分类处理#

数据分类处理

http://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd

#include <bits/stdc++.h>

using namespace std;

bool isExist(string strI, string s){
    return strstr(strI.c_str(), s.c_str()) != nullptr; //在strI中找s第一次出现的位置
}

void process(int sizeI, int sizeR, vector<int> I, vector<int> R){
    sort(R.begin(), R.end()); //排序
    //unique函数:”删除”序列中所有相邻的重复元素(只保留一个)。此处的删除,并不是真的删除,而是指重复元素的位置被不重复的元素给占领了
    //单纯的使用unique函数的话,容器的长度并没有发生变化,只是元素的位置发生了变化
    //返回值是一个迭代器,它指向的是去重后容器中不重复序列的最后一个元素的下一个元素。
    //如1334667——>1346767,指向第2个6的位置;
    //所以要搭配erase使用
    vector<int>::iterator new_end = unique(R.begin(), R.end());//去重 
    R.erase(new_end, R.end());

    unordered_map<string, vector<pair<string, int>>> mp;
    for(int i = 0; i < R.size(); i++){
        //cout << R[i] << " " << endl; //排序去重后的R   
        string tmp_rs = to_string(R[i]);  
        //cout << tmp_rs << endl;
        for(int j = 0; j < I.size(); j++){
            string tmp_is = to_string(I[j]);
            if(isExist(tmp_is, tmp_rs)){
                //cout << j << " ";
                mp[tmp_rs].push_back(make_pair(tmp_is, j));
            }                     
        }
    }

    vector<string> res;
    for(int i = 0; i < R.size(); i++){
        for(auto item = mp.begin(); item != mp.end(); item++){     
            if(item->first == to_string(R[i])){
                res.push_back(item->first);
                int baohanNum = item->second.size();
                res.push_back(to_string(baohanNum));
                for(int idx = 0; idx < baohanNum; idx++){
                    res.push_back(to_string(item->second[idx].second));
                    res.push_back(item->second[idx].first);
                }
            }          
        }     
    }
    
    cout << res.size() << " ";
    for(auto x : res){
        cout << x << " ";
    }
    cout << endl;       
}

int main(){
    int m = 0, n = 0;
    
    cin >> m;
    vector<int> I(m, 0); 
    for(int i = 0; i < m; i++){
        int num = 0;
        cin >> num;
        I[i] = num;
    }
    
    cin >> n;
    vector<int> R(n);   
    for(int i = 0; i < n; i++){
        int num = 0;
        cin >> num;
        R[i] = num;
    }
    
    process(m, n, I, R);
    
    return 0;
}
华为题库题解 文章被收录于专栏

牛客华为题库的题解

全部评论

相关推荐

04-03 12:09
東京大学 C++
求求求求暑期offer:留第一行,剩下的不要
点赞 评论 收藏
分享
05-24 20:52
东南大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务