G面经prepare: Straight Partition of A Deck of Cards - neverlandly - 博客园
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
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 }Read full article from G面经prepare: Straight Partition of A Deck of Cards - neverlandly - 博客园