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
출처 : LeetCode
'LeetCode > Easy' 카테고리의 다른 글
[Java] LeetCode 1518 : Water Bottles (0) | 2021.04.17 |
---|---|
[Java] LeetCode 290 : Word Pattern (0) | 2021.04.17 |
[Java] LeetCode 1486 : XOR Operation in an Array (0) | 2021.04.17 |
[Java] LeetCode 977 : Squares of a Sorted Array (0) | 2021.03.30 |
[Java] LeetCode 1295 : Find Numbers with Even Number of Digits (0) | 2021.03.30 |