days2
96.时尚圈的衣着稳定性
function solution(n, data) {
// Edit your code here
let clothesArr = data.split('')
// for(let i=0;i<data.ngth)
if (n === 0) return [-1, -1]
if (n === 1) return [1, 1]
// 设置 true 进行 while 循环
let changed = true
// 记录稳定下来的天数
let days = 0
while (changed) {
changed = false
// 如果衣服全部相同,那么一定不可能稳定
const allSame = clothesArr.every(col => col === clothesArr[0])
if (allSame) return [-1, -1]
// 更新明天的衣服穿搭
let nextDay = [...clothesArr]
for (let i = 0; i < n; i++) {
// 第一次写的 if else if else if else
// // 处理边界条件如果是第一个人
// if (i === 0) {
// let isChanged = clothesArr[i] === clothesArr[i + 1] && clothesArr[i] === clothesArr[n - 1]
// if (isChanged) {
// nextDay[i] = clothesArr[i] === '0' ? '1' : '0'
// }
// // 处理边界条件如果是最后一个人
// } else if (i === n - 1) {
// if (clothesArr[i] === clothesArr[i - 1] && clothesArr[i] === clothesArr[0]) {
// nextDay[i] = clothesArr[i] === '0' ? '1' : '0'
// changed = true
// }
// // 其他人
// } else {
// if (clothesArr[i] === clothesArr[i - 1] && clothesArr[i] === clothesArr[i + 1]) {
// // 换衣服
// nextDay[i] = clothesArr[i] === '0' ? '1' : '0'
// changed = true
// }
// }
// }
// 优化
for (let i = 0; i < n; i++) {
const left = (i - 1 + n) % n;
const right = (i + 1) % n;
if (clothesArr[i] === clothesArr[left] && clothesArr[i] === clothesArr[right]) {
nextDay[i] = clothesArr[i] === '0' ? '1' : '0'
changed = true
}
}
clothesArr = nextDay
days++
if (!changed) break
}
// 计算“时尚达人”数量
let fashionistas = 0;
for (let i = 0; i < n; i++) {
const left = (i - 1 + n) % n;
const right = (i + 1) % n;
if (clothesArr[i] !== clothesArr[left] && clothesArr[i] !== clothesArr[right]) {
fashionistas++;
}
}
return [days, fashionistas];
}
function main() {
// Add your test cases here
console.log(solution(4, "0000").toString() === [-1, -1].toString());
console.log(solution(4, "1110").toString() === [2, 4].toString());
console.log(solution(5, "11011").toString() === [2, 3].toString());
}
main();
时间复杂度:
-
while (changed):主循环直到没有学生改变校服颜色。在最坏情况下,每个学生每天都会改变一次校服颜色,直到达到稳定状态。假设达到稳定状态需要 k 天,那么主循环最多会运行 k 次; -
for 循环: 循环遍历数组 clothesArr,遍历所有学生,时间复杂度为 O(n)
因此时间复杂度为: O(k*n)
空间复杂度: 创建用于记录衣服穿搭的 clothesArr ,是一个长度为 n 的数组,空间复杂度为 O(n)