【Lintcode】1728. X of a Kind in a Deck of Cards
題目地址:
https://www.lintcode.com/problem/x-of-a-kind-in-a-deck-of-cards/description
給定一個陣列 A A A,將其分組成若干組(可以重排 A A A),使得每組的數字都相等,每組數字的個數相等,並且每組數字個數都至少是 2 2 2。返回這個每組數字個數。
先用雜湊表統計每個數出現次數,答案其實就是所有出現次數的最大公約數。如果最大公約數是 1 1 1,則返回false,否則最後返回true。程式碼如下:
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
/**
* @param deck: a integer array
* @return: return a value of bool
*/
public boolean hasGroupsSizeX(List<Integer> deck) {
// write your code here
Map<Integer, Integer> map = new HashMap<>();
for (int d : deck) {
map.put(d, map.getOrDefault(d, 0) + 1);
}
// 求最少出現次數
int x = deck.size();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
x = Math.min(x, entry.getValue());
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
// 求最大公約數,如果最大公約數是1,則返回false
x = gcd(x, entry.getValue());
if (x == 1) {
return false;
}
}
return true;
}
private int gcd(int x, int y) {
while (y != 0) {
int tmp = x % y;
x = y;
y = tmp;
}
return x;
}
}
時間複雜度 O ( l A log l A ) O(l_A\log l_A) O(lAloglA)( log l A \log l_A loglA的部分來自於求最大公約數,但實際時間要比這個小得多),空間 O ( l A ) O(l_A) O(lA)。
相關文章
- X of a Kind in a Deck of Cards 卡牌分組
- 【Lintcode】141. Sqrt(x)
- 使用kind搭建kubernetes
- DataTransferItem.kind 屬性
- POJ 1511-Invitation Cards(SPFA)
- Kubernetes容器化工具Kind實踐部署Kubernetes v1.18.x 版本, 釋出WordPress和MySQLMySql
- 使用 kind 快速搭建 kubernetes 環境
- LeetCode之Reveal Cards In Increasing Order(Kotlin)LeetCodeKotlin
- CF1392H ZS Shuffles Cards
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- 使用 Kind 搭建你的本地 Kubernetes 叢集
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- Throwing cards away I(queue迴圈佇列)佇列
- CARDS主題 & 導航欄樣式修改
- Jayson Tatum is a fascinating player who has a sort of in-between kind
- P1446-[HNOI2008]Cards【Burnside引理,dp】IDE
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP
- 【Lintcode】572. Music PairsAI