File tree 1 file changed +27
-25
lines changed
scripts/algorithms/X/X of a Kind in a Deck of Cards
1 file changed +27
-25
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 16 ms (Top 24.87%) | Memory: 17.80 MB (Top 45.38%)
2
+
1
3
class Solution {
2
4
public:
3
- int gcd (int a,int b)
4
- {
5
- while (a>0 && b>0 )
6
- {
7
- if (a>b) a=a%b;
8
- else b=b%a;
9
- }
10
- return (a==0 ? b:a);
11
- }
12
5
bool hasGroupsSizeX (vector<int >& deck) {
13
- unordered_map<int ,int > mp;
14
- vector<int > v;
15
- for (auto i:deck)
16
- {
17
- mp[i]++;
18
- }
19
- for (auto it:mp)
6
+ std::unordered_map<int , int > map;
7
+ for (int i=0 ; i<deck.size (); i++) // store in unordered_map the amount of cards with each number
8
+ map[deck[i]]++;
9
+
10
+ int x = INT_MAX;
11
+ for (std::pair<int , int > num : map) // find minimum
20
12
{
21
- v.push_back (it.second );
13
+ if (num.second < x)
14
+ x = num.second ;
22
15
}
23
- int g=-1 ;
24
- for (int i=0 ;i<v.size ();i++)
16
+ if (x < 2 ) return false ;
17
+
18
+ for (int i=2 ; i<=x;i++) // loop through all numbers smaller than minimum
25
19
{
26
- if (g==-1 )
27
- g=v[i];
28
- else
29
- g=gcd (g,v[i]);
20
+ bool good = true ;
21
+ for (std::pair<int , int > num : map) // if all groups of cards divide by i - flag stays true
22
+ {
23
+ if (num.second % i != 0 )
24
+ {
25
+ good = false ;
26
+ break ;
27
+ }
28
+
29
+ }
30
+ if (good) return true ;
30
31
}
31
- return g>1 ;
32
+
33
+ return false ;
32
34
}
33
- };
35
+ };
You can’t perform that action at this time.
0 commit comments