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");
        }
    
    }
    

      

  • 相关阅读:
    格式刷的一小步,原型工具的一大步
    精益设计,敏捷开发,一个都不能少
    慢工出细活,Facebook点赞按钮设计中的门道
    5个范例告诉你什么是自适应网页设计
    用户体验设计5大目标
    poj1251Jungle Roads(最小生成树)
    hdu2222Keywords Search
    hdu2328Corporate Identity
    hdu1238Substrings
    hdu4763Theme Section
  • 原文地址:https://www.cnblogs.com/apanda009/p/7791286.html
Copyright © 2011-2022 走看看