20170605_unordered_map和unordered_set的具体使用案例

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,用来装pair
			for(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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值