LeetCode 38.卡牌分组 辗转相除法

题目描述

给定一副牌,每张牌上都写着一个整数。

此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:

每组都有 X 张牌。
组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true。

 

示例 1:

输入:[1,2,3,4,4,3,2,1]
输出:true
解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]


示例 2:

输入:[1,1,1,2,2,2,3,3]
输出:false
解释:没有满足要求的分组。


示例 3:

输入:[1]
输出:false
解释:没有满足要求的分组。


示例 4:

输入:[1,1]
输出:true
解释:可行的分组是 [1,1]


示例 5:

输入:[1,1,2,2,2,2]
输出:true
解释:可行的分组是 [1,1],[2,2],[2,2]

提示:

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

解题思路

先用一个map记录每个数字出现的个数,再判断这些个数是否大于2且存在不等于1的最小公因数,求最小公因数用到了辗转相除法

代码如下

package leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HasGroupsSizeX {
      public boolean hasGroupsSizeX(int[] deck) {
        Map<Integer, Integer> map=new HashMap<Integer, Integer>();
        List<Integer> list=new ArrayList<Integer>();
        for (int i = 0; i < deck.length; i++) {
            if (map.get(deck[i])!=null) {
                map.put(deck[i], map.get(deck[i])+1);
            }else {
                map.put(deck[i], 1);
                list.add(deck[i]);
            }
        }
        int num=map.get(list.get(0));
        boolean flag=true;
        for (int i = 0; i < list.size(); i++) {
            if (gcd(map.get(list.get(i)), num)==1||map.get(list.get(i))<2) {
                flag=false;
            }else {
                num=gcd(map.get(list.get(i)), num);
            }
        }
          return flag;

        }
      
      public static int gcd(int a,int b){

            while(b != 0){
                int temp = a % b;
                a = b;
                b = temp;
            }
            return a;

        }
      
      public static void main(String[] args) {
        System.out.println(gcd(8, 9));
    }
}

 

posted @ 2020-03-27 12:59  Transkai  阅读(169)  评论(0编辑  收藏  举报