题解 | #扑克牌顺子#
扑克牌顺子
https://www.nowcoder.com/practice/762836f4d43d43ca9deb273b3de8e1f4
顺子的充分必要条件:
- 最大值 - 最小值 <= 4
- 没有重复值(0除外)
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param numbers int整型一维数组 * @return bool布尔型 */ export function IsContinuous(numbers: number[]): boolean { // write code here let min, max for (let i = 0; i < numbers.length; i++) { if (numbers[i] !== 0) { if (!min || min > numbers[i]) { min = numbers[i] } if (!max || max < numbers[i]) { max = numbers[i] } } } const isValidInterval = max - min <= 4 if (!isValidInterval) return false // Check if duplicated let i = 0 while (i < 5) { if (numbers[i] !== 0 && numbers[i] !== undefined) { const value = numbers[i] if (value !== i) { if (numbers[value] === value) return false // swap numbers[i] = numbers[value] numbers[value] = value continue } } i++ } return true }空间复杂度O(1)
时间复杂度O(n)