纪念一下我写的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;
	}
    
}

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

猜你喜欢

转载自blog.csdn.net/ailaojie/article/details/85247029