寻找hash值——把int array看成是一个整数

本文介绍了一个名为DominoChecker的类的设计实现,该类包含一个addBox方法,用于检查并添加一组多米诺骨牌到集合中。每组骨牌由10个整数表示,若已存在相同的组合则返回false。

QUESTION:

Write a class DominoChecker that has a method called addBox(int[]) that takes a box of five dominoes, described as a list of 10 integers (explained after), adds it to a collection, and returns true if a box with the same dominoes was already in the collection and false otherwise. A box of dominoes is encoded as a list of 10 integers from 0 to 9, where a pair of numbers represent a domino. For example: 0,2,9,1,3,3,7,4,5,6 represents a box containing dominoes: (0,2); (9,1); (3,3); (7,4); (5,6). 
SOLUTION:
typedef pair< int,int > Domino;

class DominoChecker {
   unordered_set< long long > hash;
   vector< vector< Domino > > boxes;

  public:
    bool addBox(const vector< int >& box) {
        vector< Domino > v;
        for (int i = 0; i < 5; i++) {
            Domino d(box[2*i], box[2*i+1]);
            if (d.first > d.second)
                swap(d.first, d.second); // order does not matter
            v.push_back(d);
        }
        sort(v.begin(), v.end());  // order does not matter here as well.
        long long hash_value = 0;
        for (int i = 0 ; i < 5; i++)
             hash_value = hash_value * 100 + v[i].first*10 + v[i].second; //把int  array看成是一个整数
        if (hash.find(hash_value) != hash.end())
            return false;
        hash.insert(hash_value);
        boxes.push_back(v); // i suppose we want to store them
        return true;
    }
};

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/4830399.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值