20170605_unordered_map和unordered_set的具体使用案例

来源:互联网 发布:淘宝联盟推广首页 编辑:程序博客网 时间:2024/06/01 09:03

20170605_unordered_map和unordered_set的具体使用案例


//leet532_找出给定数组中差值为k的对儿数.//Example 1://Input: [3, 1, 4, 1, 5], k = 2//Output: 2//Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).//Although we have two 1s in the input, we should only return the number of unique pairs.////Example 2://Input:[1, 2, 3, 4, 5], k = 1//Output: 4//Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).#include<iostream>#include<vector>#include<string>#include<algorithm>#include<map>#include<set>#include<unordered_map>#include<unordered_set>#include<utility>using namespace std;class Solution{public://双重循环,时间复杂度是O(n^2)int findPairs(vector<int> &nums, int k){int sz=nums.size();if(sz<2 || k<0)return 0;else{int i=0,j=0;int diff=0;unordered_map<int,int> intmap;//定义一个map,用来装pairfor(i=0; i<sz; ++i){for(j=i+1; j<sz; ++j){diff=abs(nums[i]-nums[j]);if(diff==k){if(nums[i]<=nums[j]){auto m=make_pair(nums[i],nums[j]);intmap.insert(m);}else{auto m=make_pair(nums[j],nums[i]);intmap.insert(m);}//here is a good place for you to save the two integers that the diff of them is k.}}}//for(auto mem:intmap)//cout<<mem.first<<"--"<<mem.second<<endl;return intmap.size();}    }    /**     * for every number in the array:     *  - if there was a number previously k-diff with it, save the smaller to a set;     *  - and save the value-index to a map;     */    int findPairs2(vector<int> &nums, int k){        if(k<0)            return 0;        unordered_set<int> starters;//关键字集合,无序        unordered_map<int,int> indices;//关键字-值集合,无序        for(int i=0; i<nums.size(); i++){            if(indices.count(nums[i]-k))                starters.insert(nums[i]-k);            if(indices.count(nums[i]+k))                starters.insert(nums[i]);            indices[nums[i]]+=1;        }for(auto mem:starters)cout<<mem<<" ";cout<<endl;for(auto m:indices)cout<<m.first<<"_"<<m.second<<" ";cout<<endl;        return starters.size();    }};int main(void){int nums[]={3,1,4,1,5};//int nums[]={1,3,1,5,4};vector<int> ivec(begin(nums),end(nums));Solution object;int k=2;int res=object.findPairs2(ivec,k);cout<<res<<endl;system("pause");return 0;}