[A question daily] 162. The card packet (analog, gcd, conventional solution)

1. Source title

Links: 914. Card grouping
Source: LeetCode

2. Description title

Here Insert Picture Description
Here Insert Picture Description

3. resolve title

Method a: Method conventional analog + gcd +

Simple title, abstract need to understand, simply under the idea:

  • You first need to be repeated the number of statistics, using mapdata structures can be directly statistics, the most convenient and effective. There is also an array using the count can. Of course, sortpost-processing is also possible, high time complexity. Many data processing method, non-key.
  • Count the number of repetitions to get all of the significant digits, then the packet xis any repetition of these non-convention a number 1 , because of this ready-made gcdgreatest common divisor method to be used directly, and with the efficiency of internal division is also removed High. May also seek to enumerate the number of conventions through violence, the time complexity is higher.

See the code below:

// 执行用时 :44 ms, 在所有 C++ 提交中击败了6.40%的用户
// 内存消耗 :16.9 MB, 在所有 C++ 提交中击败了5.71%的用户

class Solution {
public:
    bool hasGroupsSizeX(vector<int>& deck) {
        map<int, int> m;
        for (int i = 0; i < deck.size(); i++)
            m[deck[i]]++;
        int g = m.begin()->second;
        for (auto  i = m.begin(); i != m.end(); i++) 
            g = gcd(g, i->second);
        return g >= 2;
    }
};

// 简约风
class Solution {
public:
    bool hasGroupsSizeX(vector<int>& deck) {
        map<int, int> m;
        for (auto& e : deck) m[e]++;
        int g = m.begin()->second;
        for (auto& e : m) g = gcd(g, e.second);
        return g >= 2;
    }
};
Published 392 original articles · won praise 336 · views 80000 +

Guess you like

Origin blog.csdn.net/yl_puyu/article/details/105153083