LeetCode/Easy
[Java] LeetCode 914 : X of a Kind in a Deck of Cards
새우버거♬
2021. 4. 17. 17:38
LeetCode # 914
Example 1:
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
Note:
- 1 <= deck.length <= 10⁴
- 0 <= deck[i] < 10⁴
Solution #1 (10ms)
class Solution {
public boolean hasGroupsSizeX(int[] deck) {
Map<Integer, Integer> map = new HashMap<>();
for (int i : deck) {
if (map.containsKey(i)) {
int value = map.get(i);
map.put(i, value + 1);
} else {
map.put(i, 1);
}
}
List<Integer> list = new ArrayList<Integer>();
for (Integer value : map.values()) {
list.add(value);
}
int g = list.get(0);
for (int i = 1; i < list.size(); i++) {
g = gcd(g, list.get(i));
}
return g != 1;
}
private int gcd(int x, int y) {
return x == 0 ? y : gcd(y % x, x);
}
}
Result #1
Solution #2 (3ms)
class Solution {
public boolean hasGroupsSizeX(int[] deck) {
if (deck.length >= 2) {
int[] array = new int[10000];
for (int d : deck) {
array[d] = array[d] + 1;
}
int result = 0;
for (int i = 0; i < 10000; i++) {
if (array[i] > 0) result = gcd(result, array[i]);
}
return result != 1;
}
return false;
}
private int gcd(int x, int y) {
return x == 0 ? y : gcd(y % x, x);
}
}
Result #2
More Algorithm!
👇👇
github.com/ggujangi/ggu.leet-code
ggujangi/ggu.leet-code
LeetCode, Java. Contribute to ggujangi/ggu.leet-code development by creating an account on GitHub.
github.com
출처 : LeetCode