G面经prepare: Straight Partition of A Deck of Cards
2016-01-15 08:05
417 查看
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"); } }
相关文章推荐
- rails分段查询
- 身体的智能
- Ibatis中的动态SQL:isNotNull,isPropertyAvailable,isNotEmpty用法
- RAID的原理和区别
- main函数参数
- LeetCode_Climbing Stairs--爬楼梯
- [leetCode]70. Climbing Stairs
- codeforces 616E Sum of Remainders(数学公式转化 较难)
- 写的小案例中问题总结--baidumap
- svn cleanup failed–previous operation has not finished; run cleanup if it was interrupted
- USACO天梯--Barn Repair
- Climbing Stairs_爬楼梯_递归
- 无法安装vmware tools的解决方PLEASE WAIT! VMware Tools is currently being installed on your system. Dependin
- haartraing 准备(将图像统一修改尺寸)
- VS2010 error: LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
- (Mac)Rails项目使用七牛上传及下载文件
- Studio team goals and pain points
- AIDL的使用
- AjaxControlToolKit--TabContainer控件的介绍收藏[摘录]
- Shallow Size、Retained Size、Heap Size和Allocated