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,报错
1 package Straight; 2 import java.util.*; 3 4 public class Solution { 5 public boolean determine(int[] arr) { 6 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 7 for (int elem : arr) { 8 if (map.containsKey(elem)) { 9 map.put(elem, map.get(elem)+1); 10 } 11 else map.put(elem, 1); 12 } 13 14 for (int i=0; i<arr.length; i++) { 15 if(map.get(arr[i]) == 0) continue; 16 for (int j=arr[i]; j<arr[i]+5; j++) { 17 if (!map.containsKey(j)) return false; 18 if (map.get(j) == 0) return false; 19 else { 20 map.put(j, map.get(j)-1); 21 } 22 } 23 if (map.get(arr[i]) > 0) i--; 24 } 25 return true; 26 } 27 28 29 /** 30 * @param args 31 */ 32 public static void main(String[] args) { 33 // TODO Auto-generated method stub 34 Solution sol = new Solution(); 35 boolean res = sol.determine(new int[]{1,2,3,4,4,5,5,5,6,6,7,7,8,8,9}); 36 if (res) System.out.println("true"); 37 else System.out.println("false"); 38 } 39 40 }