[title] card grouping – lotcode

Time:2021-3-2

Title: card grouping

Given a deck of cards, an integer is written on each card.

At this point, you need to select a number x, so that we can divide the whole deck into one or more groups according to the following rules:

Each group has X cards.
All cards in the group have the same integer written on them.
Returns “true” only if your optional x > = 2.

 

Example 1:

Input: [1,2,3,4,4,3,2,1]
Output: true
Explanation: the feasible groups are [1,1], [2,2], [3,3], [4,4]
Example 2:

Input: [1,1,1,2,2,2,3,3]
Output: false
Explanation: there are no groups that meet the requirements.
Example 3:

Input: [1]
Output: false
Explanation: there are no groups that meet the requirements.
Example 4:

Input: [1,1]
Output: true
Explanation: the feasible grouping is [1,1]
Example 5:

Input: [1,1,2,2,2]
Output: true
Explanation: the feasible groups are [1,1], [2,2], [2,2]

Tips:

1 <= deck.length <= 10000
0 <= deck[i]


 

Thinking:

First of all, according to the conditions of the topic, we are required to divide the cards into one or more groups, and each group of cards is the same.

We can think of, if each group has only one card, then no matter how many cards there are, there are qualified points.

If each group has two cards, then the total number of each kind of same card must be a multiple of 2, in order to meet the conditions of the division.

If there are three cards in each group, then the total number of the same card in each group must be a multiple of 3 in order to meet the conditions.

 

By analogy, the number x we are looking for is:

Let y be a set

  1. The total number of all the same cards is a multiple of the elements in Y, that is, they can divide the elements in Y exactly
  2. X is the largest possible number of Y elements

Obviously, the Y set is the common divisor of all the same number of cards, and X is their greatest common divisor.

 

Code (c) above:

//Finding the greatest common divisor int GCD (int x, int y){
    int tmp;
    while( y != 0 ) {
        tmp = x;
        x = y;
        y = tmp%y;
    }
    return x;
}
bool hasGroupsSizeX(int* deck, int deckSize){
    int count[10005] = {0};
    int x = -1;
    
    for( int i = 0; i < deckSize; i++ ) {
        count[deck[i]]++;
    }
    
    for( int i = 0; i < 10005; i++ ) {
        if( count[i] > 0 ) {
            if( x == -1 ) ans = count[i];
            else x = gcd( ans, count[i] );
        }
    }
   
    if( x >= 2 ) return true;
    return false;
}

 

2020-03-27-19:03:11

 

Recommended Today

Practice analysis of rust built-in trait: partialeq and EQ

Abstract:Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. This article is shared from Huawei cloud community《Analysis of rust built-in trait: partialeq and EQ》Author: debugzhang Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. Some traits can be automatically […]