编辑代码

// 设置标准输入接口
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
  // 初始化内存数组,长度为100,初始值都为0(表示空闲)
  // 0表示空闲状态,1表示已分配状态
  const memories = Array.from({ length: 100 }, () => 0);

  // 查找连续空闲内存块的辅助函数
  // num: 需要分配的内存大小
  const helper = (num) => {
    // 找到第一个空闲位置
    let left = memories.indexOf(0);
    let right = memories.indexOf(0);

    // 遍历整个内存数组
    while (right < memories.length) {
      left = right; // 记录当前空闲块的起始位置

      // 找到连续的空闲内存块(值为0的连续区域)
      while (memories[right] == 0) {
        right++;
      }

      // 如果找到的连续空闲块大小满足需求,返回起始位置
      if (right - left >= num) {
        return left;
      }
      right++; // 继续寻找下一个空闲块
    }

    // 没有找到足够大的连续空闲块,返回-1
    return -1;
  };

  // 存储所有操作的结果
  let ans = [];

  // 记录已分配的内存块信息
  // 每个元素格式:{startIndex: 起始位置, size: 分配大小}
  let allocated = [];

  // 读取操作次数
  const n = Number(await readline());

  // 处理每个操作
  for (let i = 0; i < n; i++) {
    // 解析命令,格式为:REQUEST=size 或 RELEASE=address
    const [cmd, num] = (await readline()).split("=");

    // 处理内存分配请求
    if (cmd == "REQUEST") {
      // 查找合适的空闲块
      const index = helper(Number(num));

      if (index == -1) {
        // 没有找到足够大的空闲块,返回error
        ans.push("error");
      } else {
        // 找到合适的空闲块,进行分配
        for (let i = index; i < index + Number(num); i++) {
          memories[i] = 1; // 标记为已分配
          // 记录分配信息
          allocated.push({ startIndex: index, size: Number(num) });
        }
        // 返回分配的起始地址
        ans.push(index);
      }
    } else {
      // 处理内存释放请求
      // 查找要释放的内存块
      const target = allocated.filter((item) => item.startIndex == Number(num));

      if (target.length == 0) {
        // 未找到对应的已分配内存块,返回error
        ans.push("error");
      } else {
        // 找到对应的内存块,进行释放
        for (let i = target[0].startIndex; i < target[0].size; i++) {
          memories[i] = 0; // 标记为空闲
        }
      }
    }
  }

  // 输出所有操作的结果
  for (let i = 0; i < ans.length; i++) {
    console.log(ans[i]);
  }
})();