leetcode846. 一手顺子

这道题有几点,

1、如果数组长度不能整除分组的大小W,则肯定为false,

2、如果能整除的话,需要对数组进行排序,然后判断每组的的数数的差是否为1,那不多说了,排序时间复杂度为o(nlongn), 判断的时间复杂度为o(n),则时间复杂度为o(nlongn)。

class Solution {
public:   
    bool isNStraightHand(vector<int>& hand, int W) {
        long len = hand.size();
        if(len == 1 || W == 1)
            return true;
        if(len % W != 0)
            return false;
        sort(hand.begin(), hand.end());   
        vector<int> visit(len);
        for(int i = 0; i < len; i++){
            if(!visit[i]){
                int cnt = W - 1;
                visit[i] = 1;
                int x = hand[i];
                int j = i;
                while(cnt){
                    if(j < len){ 
                        if(hand[j] != x){
                            if(!visit[j]){
                                if(hand[j] - x == 1){
                                    x = hand[j];
                                    visit[j] = 1;
                                    cnt--;
                                }
                            }        
                        }
                    }
                    else if(j == len + 1)
                        return false;
                    j++;
                }
            }
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/torch_man/article/details/80555314