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;}
阅读全文
1 0
- 20170605_unordered_map和unordered_set的具体使用案例
- DBUtils的具体使用案例。
- FluentValidation具体使用案例
- bindingSource具体使用案例
- OleDbDataAdapter 具体使用案例
- unordered_set的find,count效率 和赋值
- dev master—detail 主表和明细的具体使用案例
- Semantic UI 的基本使用(二):具体案例
- C++ set和unordered_set
- 【c++】unordered_set和unordered_map
- 【C++】unordered_map,unordered_set,map和set的用法和区别
- IO流的具体案例
- unordered_set的count函数
- C++的<unordered_set>
- 继承的定义和具体使用-1
- SQL游标如何使用,具体案例
- 简单使用set/unordered_set (备忘)
- Gconf与Gsettings的简介、及gsettings的具体使用案例
- HTML 的语义化理解
- ckplayer播放器设置默认封面时部分浏览器不能正常显示封面图片问题的处理
- json数据转化
- ES6 (十) Set 和 Map
- 系统分析与设计--学习笔记3(用例建模)
- 20170605_unordered_map和unordered_set的具体使用案例
- CSS 动画性能比较问题
- Linux策略路由
- Vue中保存用户登录状态
- 浏览器兼容问题解决方式
- PHP利用cookie保存登录信息
- oracle
- 关于web.xml中的welcome-file-list(欢迎页)
- 利用visio 画思维导图