扑克牌顺子 (排序+计数 JS)
扑克牌顺子
http://www.nowcoder.com/questionTerminal/762836f4d43d43ca9deb273b3de8e1f4
思路:
虽然考的知识点是字符串,不过做的时候就想,输入的是0-13的数组,那我只要记录我的0能不能跟其他牌配合起来成顺子,步骤:
1、输入数组为0 ,返回false
2、将数组进行从小到大排序,查找数组有多少个0
3、从数组尾部开始循环,比较跟旁边的牌的差值,分为以下情况:
① 差值tmp == 0 ,代表两张牌数值相同,多少个0都没用,返回false
② 差值tmp == 1,好朋友,连一块,中间不需要0这个第三者
③tmp>1: 需要0来救场,如果(count代表还有多少个0没用),
count==0代表没有0帮忙补缺的牌
count<tmp-1代表现有的0牌bu'go
count>=tmp-1 代表救场成功,count = count -tmp + 1 记录现在还有几张能救场的0牌
function IsContinuous(numbers)
{
// write code here
if(numbers.length == 0) return false
numbers.sort()
let zero = 0
for(let i=0;i<numbers.length;i++){
if(numbers[i] != 0) break;
zero ++ ;
}
let count =zero
for(let i=numbers.length-1;i>zero;i--){
let tmp = numbers[i]-numbers[i-1]
if(tmp == 0) return false
else if(tmp == 1 ) continue;
else { //tmp > 1
if( count == 0 || count<tmp-1){
return false
}
count = count - tmp + 1
}
}
return true;
}
module.exports = {
IsContinuous : IsContinuous
};
查看3道真题和解析
