Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f613d9b

Browse files
committedNov 28, 2021
solves x of a kind in a deck of cards
1 parent 8997f68 commit f613d9b

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed
 

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@
246246
| 897 | [Increasing Order Search Tree](https://leetcode.com/problems/increasing-order-search-tree) | [![Java](assets/java.png)](src/IncreasingOrderSearchTree.java) |
247247
| 905 | [Sort Array by Parity](https://leetcode.com/problems/sort-array-by-parity) | |
248248
| 908 | [Smallest Range I](https://leetcode.com/problems/smallest-range-i) | [![Java](assets/java.png)](src/SmallestRangeI.java) |
249-
| 914 | [X of a kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards) | |
249+
| 914 | [X of a kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards) | [![Java](assets/java.png)](src/XOfAKindInADeckOfCards.java) |
250250
| 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters) | |
251251
| 922 | [Sort Array by Parity II](https://leetcode.com/problems/sort-array-by-parity-ii) | |
252252
| 925 | [Long Pressed Name](https://leetcode.com/problems/long-pressed-name) | |

‎src/XOfAKindInADeckOfCards.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import java.util.Collection;
2+
import java.util.HashMap;
3+
import java.util.HashSet;
4+
import java.util.Map;
5+
import java.util.Set;
6+
7+
public class XOfAKindInADeckOfCards {
8+
public boolean hasGroupsSizeX(int[] deck) {
9+
if (deck.length == 1) return false;
10+
Map<Integer, Integer> cards = getFrequencies(deck);
11+
Set<Integer> frequencies = new HashSet<>(cards.values());
12+
if (frequencies.size() == 1 && cards.get(deck[0]) >= 2) return true;
13+
return gcd(frequencies) > 1;
14+
}
15+
16+
private int gcd(Collection<Integer> collection) {
17+
int gcd = 0;
18+
boolean firstTime = true;
19+
for (int value : collection) {
20+
gcd = firstTime ? value : gcd(gcd, value);
21+
firstTime = false;
22+
}
23+
return gcd;
24+
}
25+
26+
private int gcd(int a, int b) {
27+
return b == 0 ? a : gcd(b, a % b);
28+
}
29+
30+
private Map<Integer, Integer> getFrequencies(int[] array) {
31+
Map<Integer, Integer> result = new HashMap<>();
32+
for (int val : array) {
33+
result.put(val, result.getOrDefault(val, 0) + 1);
34+
}
35+
return result;
36+
}
37+
}

0 commit comments

Comments
 (0)
Please sign in to comment.