题目:
从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。

示例 1:
输入: [1,2,3,4,5]
输出: True

示例 2:
输入: [0,0,1,2,5]
输出: True

C#解法:

public bool IsStraight(int[] nums) {
    int length = nums.Length;
    int zeroCount = 0;
    int minValue = 14;
    int maxValue = 0;
    Dictionary<int, int> dicValue = new Dictionary<int, int>();
    foreach (var item in nums)
    {
        if (item ==0)
            zeroCount++;
        else{
            minValue = Math.Min(minValue, item);
            maxValue = Math.Max(maxValue, item);
            if (dicValue.ContainsKey(item))
                dicValue[item]++;
            else
                dicValue[item]=1;
            if (dicValue[item]>1)
                return false;
        }
    }
    if (zeroCount==0){
        return (maxValue-minValue)==4;
    } else{
        return (maxValue-minValue)<=4;
    }
}

执行结果通过
执行用时 :104 ms, 在所有 C# 提交中击败了77.08%的用户
内存消耗 :24.4 MB, 在所有 C# 提交中击败了100.00%的用户


Jackfruit
4 声望1 粉丝

Code while eating jackfruit


下一篇 »
算法:递归