纪念一下我写的leetcode题解 以后每天都会写的!!

定个小目标

leetcode题解等完成上传之后阅读量大于1000

leetcode914. X of a Kind in a Deck of Cards

class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        //键值对,key(数字)--value(出现次数)
	    Map<Integer, Integer> map = new HashMap<>();
	    for (int i = 0; i < deck.length; i++) {
			if (!map.containsKey(deck[i])) {
				map.put(deck[i], 1);
			}else {
				map.put(deck[i], map.get(deck[i])+1);
			}
		}
	    
	    java.util.Collection<Integer> value = map.values();
	    System.out.println("次数长度:"+value.size());
	    int[] values = new int[value.size()];
	    Iterator<Integer> iterator = value.iterator();
	    int i = 0;
	    while (iterator.hasNext()) {
			values[i] = iterator.next();
			System.out.println("出现次数 :"+values[i]);
			i++;
		}
	    
	    System.out.println(getMaxCommonDivisor(values));
	    
	    //辗转相除法求最大公约数
	    if (getMaxCommonDivisor(values) >= 2) {
			return true;
		}else {
			return false;
		}
    }
    
    /**   
	 * @Title: getMaxCommonDivisor   
	 * @Description: 辗转相除法求解最大公约数.   
	 * @param: @param values 求解数组.
	 * @return: int 最大公约数.      
	 * @throws   
	 */
	private static int getMaxCommonDivisor(int[] values) {
		// TODO Auto-generated method stub
        if(values.length < 1)
            return 0;
        if(values.length < 2)
            return values[0];
		int k = getTwoDivisor(values[0],values[1]);
		for (int i = 2; i < values.length; i++) {
			int j = values[i];
			k = getTwoDivisor(j, k);
			System.out.println("k = "+k);
		}
		return k;
	}
	/**   
	 * @Title: getTwoDivisor   
	 * @Description: 得到两个数的最大公约数.
	 * @param: @param a 数组1.
	 * @param: @param b 数字2.
	 * @param: @return 
	 * @return: int    数字1和数字2的最大公约数.  
	 * @throws   
	 */
	private static int getTwoDivisor(int a,int b) {
		if (a == b) {
			return a;
		}
		int c = (a < b) ? a : b;
		int d = (a < b) ? b : a;
		while (c != 0) {
			int r = d % c;
			d = c;
			c = r;
		}
		return d;
	}
    
}

效率是差了点,但是思路清晰,注释规范

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值