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,报错

 package Straight;
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");
} }
上一篇:Python——递归函数


下一篇:SAP abap 语句、命令 语法查询备用