实现一个函数:最长顺子

XX公司综合机试题第三题,以前有人讨论过,这里列出不同的算法

3.请实现一个函数:最长顺子;输入很多个整数(1<=数值<=13),返回其中可能组成的最长的一个顺子(顺子中数的个数代表顺的长度); 其中数字1也可以代表14; 顺子包括单顺\双顺\3顺;单顺的定义是连续5个及以上连续的数,比如1,2,3,4,5、3,4,5,6,7,8和10,11,12,13,1等;双顺的定义是连续3个及以上连续的对(对:两个相同的数被称为对),比如1,1,2,2,3,3、4,4,5,5,6,6,7,7和11,11,12,12,13,13,1,1等;3顺的定义是连续2个及以上连续的3张(3张:3个相同的数被称为3张),比如1,1,1,2,2,2、3,3,3,4,4,4,5,5,5,6,6,6和13,13,13,1,1,1等等;
比如:输入数组[1,5,2,3,4,4,5,9,6,7,2,3,3,4], 输出数组[2,2,3,3,4,4,5,5]


public static Integer[] doTest(Integer[] array) {
int[] count = new int[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] < 1 || array[i] >= array.length)
return null;
++count[array[i]];
}
TreeMap<Integer, Map<Integer, Integer>> allList = new TreeMap<Integer, Map<Integer, Integer>>();
Map<Integer, Integer> map = null;
for (int k = 0; k < 3; k++) {
map = getList(count, k);
if (null != map) {
if (0 == k)
allList.put(map.size(), map);
else if (1 == k)
allList.put(2 * map.size(), map);
else
allList.put(3 * map.size(), map);
}
}
if (allList.size() > 0) {
Map<Integer, Integer> maxList = allList.get(allList.lastKey());
List<Integer> resultList = new LinkedList<Integer>();
Collection<Integer> coll = maxList.values();
int min = Collections.min(coll);
for (Integer k : maxList.keySet()) {
for (int j = 0; j < min; j++) {
resultList.add(k);
}
}
Integer[] result = new Integer[resultList.size()];
resultList.toArray(result);
return result;
} else
return null;
}

private static Map<Integer, Integer> getList(int[] count, int k) {
TreeMap<Integer, Map<Integer, Integer>> list = new TreeMap<Integer, Map<Integer, Integer>>();
Map<Integer, Integer> map = null;
int flag = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > k && flag == 0) {
flag = 1;
map = new LinkedHashMap<Integer, Integer>();
map.put(i, count[i]);
} else if (count[i] > k && flag == 1) {
map.put(i, count[i]);
if (13 == i) {
if (count[14 - i] > k) {
map.put(14 - i, count[14 - i]);
putList(k, list, map);
} else {
flag = 0;
putList(k, list, map);
}
}
} else if (count[i] <= k && flag == 1) {
flag = 0;
putList(k, list, map);
map = null;
}
}
if (list.size() > 0)
return list.get(list.lastKey());
else
return null;
}

private static void putList(int k, TreeMap<Integer, Map<Integer, Integer>> list, Map<Integer, Integer> map) {
if (0 == k && map.size() >= 5) {
list.put(map.size(), map);
}
if (1 == k && map.size() >= 3) {
list.put(2 * map.size(), map);
}
if (2 == k && map.size() >= 2) {
list.put(3 * map.size(), map);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值