leetcode打卡-846. 一手顺子

216 阅读1分钟

846. 一手顺子

思路:

罗列一次groupSize所有的情况:

  1. 如果是第一个数则记录没有上一个的数字,把当前数字设置为上一个数,用以比较是否是递增,进入下次
  2. 如果当前数和上一个数相同,则进行忽略;因为数字相同,则说明这个数可能是下一次循环的第一个数,因此要进行判断:下次起始位置等于起始位置,本次遍历长度和过滤空白长度之和,则说明这个相同数是下次起始位置,并将过滤空白长度加一,进入下次
  3. 如果当前数是上一个数字加一,则将当前数置空,进入下次
  4. 以上都不满足则说明不符合条件,返回false
/**
 * @param {number[]} hand
 * @param {number} groupSize
 * @return {boolean}
 */
var isNStraightHand = function(hand, groupSize) {
    const len = hand.length;
    if (len % groupSize !== 0) return false;
    hand.sort((i, i2) => i - i2);
    let start = 0;
    while (start < len) {
        let pre = null;
        let nextStart = start + groupSize;
        for(let i = start, j = 0; i < start + groupSize + j; i++) {
            if (hand[i] === null) {
                 if (nextStart === start + groupSize + j) {
                    nextStart ++;
                }
                j++
                continue;
            }
            if (start === i) {
                pre = hand[i];
                hand[i] = null;
            } else if (pre === hand[i]){
                if (nextStart === start + groupSize + j) {
                    nextStart = i;
                }
                j++;
            } else if (pre + 1 === hand[i]) {
                pre = hand[i];
                hand[i] = null;
            } else {
                return false
            }
        }
        start = nextStart;
    }
    return true;
};