扑克牌中的顺子

排序:

class Solution {
    public boolean isStraight(int[] nums) {
        Arrays.sort(nums);
        int zero = 0;
        int needZero = 0;
        if(nums[0] == 0) zero++;
        for(int i=1;i<nums.length;i++){
            if(nums[i] - nums[i-1] > 1&&nums[i-1]>0){
                needZero += (nums[i]-nums[i-1]-1);
            }
            if(nums[i] == nums[i-1] && nums[i]>0){
                return false;
            }
            if(nums[i] == 0) zero++;
        }
        return zero >= needZero;
    }
}

不排序

class Solution {
    public boolean isStraight(int[] nums) {
        int[] hash = new int[14];
        int endIndex = 13,startIndex=1;
        int needZero=0;
        for(int num:nums){
            hash[num]++;
        }
        while(hash[endIndex]==0) endIndex--;//确定顺子的最大下标
        while(hash[startIndex]==0)startIndex++;//确定顺子的最小下标
        for(int i=endIndex;i>=startIndex;i--){//中间少的用零补
            if(hash[i]>1&&i>0) return false;
            if(hash[i]==0&&i>0) needZero++;
        }
        return needZero<=hash[0];
    }
}

不一样的烟火
原文地址:https://www.cnblogs.com/cstdio1/p/13377104.html