In a deck of cards, each card has an integer written on it.
Return true
if and only if you can choose X >= 2
such that it is possible to split the entire deck into 1 or more groups of cards, where:
- Each group has exactly
X
cards. - All the cards in each group have the same integer.
Example 1:
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Approach
Java
import java.util.HashMap;public class XKindDeckCards {public static void main(String[] args) {int[] deck = { 1, 2, 3, 4, 4, 3, 2, 1 };System.out.println(hasGroupsSizeX(deck));}static boolean hasGroupsSizeX(int[] deck) {HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();for (int i : deck)mp.put(i, mp.getOrDefault(i, 0) + 1);int min = Integer.MAX_VALUE;for (int i : mp.keySet()) {if (mp.get(i) > 0) {if (mp.get(i) < min)min = mp.get(i);}}int flag = 0, k = min;if (min == 1)return false;else {for (int i1 : mp.keySet()) {if (mp.get(i1) > 0) {for (int j = min; j >= 2; j--) {if (mp.get(i1) % j == 0 && mp.get(i1) != min) {k = j;if (min % k == 0)break;}}}}for (int i2 : mp.keySet()) {if (mp.get(i2) > 0) {if (mp.get(i2) % k != 0) {flag = 1;break;}}}if (flag == 0 && deck.length > 1)return true;elsereturn false;}}}
C++
#include <bits/stdc++.h>using namespace std;bool hasGroupsSizeX(vector<int> &deck){int hash[10001] = {0};for (int i = 0; i < deck.size(); i++)hash[deck[i]]++;int min = INT_MAX;for (int i = 0; i < 10001; i++)if (hash[i] > 0){if (hash[i] < min)min = hash[i];}int flag = 0, k = min;if (min == 1)return false;else{for (int i = 0; i < 10001; i++){if (hash[i] > 0){for (int j = min; j >= 2; j--){if (hash[i] % j == 0 && hash[i] != min){k = j;if (min % k == 0)break;}}}}for (int i = 0; i < 10001; i++){if (hash[i] > 0){if (hash[i] % k != 0){flag = 1;break;}}}if (flag == 0 && deck.size() > 1)return true;elsereturn false;}}int main(){vector<int> deck = {1, 2, 3, 4, 4, 3, 2, 1};if (hasGroupsSizeX(deck))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment