zoukankan      html  css  js  c++  java
  • G面经prepare: Straight Partition of A Deck of Cards

    Define “Straight” as 5 cards with consecutive numbers. Determine if the deck can be fully divided into sets of “Straight”.
    Example: 1, 2, 3, 4, 4, 5, 5, 6, 7, 8 -> True
    You may assume the cards are sorted

    这个是用一个hashtable,key是数字,value是出现次数

    然后遍历原数组,每一个数字都把hash里从自己开始往后5个color数都-1,如果发现缺数则说明不能分割

    很容易错!

    错了好多次,是color往后5个,如果不存在该color或者color数目已经为0,报错

    import java.util.*;
    
    public class Solution {
        public boolean determine(int[] arr) {
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int elem : arr) {
                if (map.containsKey(elem)) {
                    map.put(elem, map.get(elem)+1);
                }
                else map.put(elem, 1);
             }
            
            for (int i=0; i<arr.length; i++) {
                if(map.get(arr[i]) == 0) continue;
                for (int j=arr[i]; j<arr[i]+5; j++) {
                    if (!map.containsKey(j)) return false;
                    if (map.get(j) == 0) return false;
                    else {
                        map.put(j, map.get(j)-1);
                    }
                }
                if (map.get(arr[i]) > 0) i--;
            }
            return true;
        }
        
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Solution sol = new Solution();
            boolean res = sol.determine(new int[]{1,2,3,4,4,5,5,5,6,6,7,7,8,8,9});
            if (res) System.out.println("true");
            else System.out.println("false");
        }
    
    }
    

      

  • 相关阅读:
    a标签跳转新页面
    js或jquery实现页面打印(局部打印)
    js实现点击定位最顶端
    js实现pdf对页面的打印
    js动态创建input
    sha1加密算法
    JsonHelper修改4.0
    List<T>做数据源绑定的问题
    VS2013智能提示
    Newtonsoft.Json(Json.Net)学习笔记
  • 原文地址:https://www.cnblogs.com/apanda009/p/7791286.html
Copyright © 2011-2022 走看看