友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

900. RLE 迭代器

我们可以使用游程编码(即 RLE *)来编码一个整数序列。在偶数长度 encoding ( *从 0 开始 )的游程编码数组中,对于所有偶数 iencoding[i] 告诉我们非负整数 encoding[i + 1] 在序列中重复的次数。

  • 例如,序列 arr = [8,8,8,5,5] 可以被编码为 encoding =[3,8,2,5]encoding =[3,8,0,9,2,5]encoding =[2,8,1,8,2,5] 也是 arr 有效的 RLE

给定一个游程长度的编码数组,设计一个迭代器来遍历它。

实现 RLEIterator 类:

  • RLEIterator(int[] encoded) 用编码后的数组初始化对象。

  • int next(int n) 以这种方式耗尽后 n`个元素并返回最后一个耗尽的元素。如果没有剩余的元素要耗尽,则返回 `-1

示例 1:

输入:
["RLEIterator","next","next","next","next"]
[[[3,8,0,9,2,5]],[2],[1],[1],[2]]
输出:
[null,8,8,5,-1]
解释:
RLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // 这映射到序列 [8,8,8,5,5]。
rLEIterator.next(2); // 耗去序列的 2 个项,返回 8。现在剩下的序列是 [8, 5, 5]。
rLEIterator.next(1); // 耗去序列的 1 个项,返回 8。现在剩下的序列是 [5, 5]。
rLEIterator.next(1); // 耗去序列的 1 个项,返回 5。现在剩下的序列是 [5]。
rLEIterator.next(2); // 耗去序列的 2 个项,返回 -1。 这是由于第一个被耗去的项是 5,
但第二个项并不存在。由于最后一个要耗去的项不存在,我们返回 -1。

提示:

  • 2 <= encoding.length <= 1000

  • encoding.length 为偶

  • 0 <= encoding[i] <= 109

  • 1 <= n <= 109

  • 每个测试用例调用 next 不高于 1000

思路分析

使用属性 index 记录 next 操作走到那个字符了。然后,检查 encoding[index] 的值是否大于参数 n,如果大于等于,从 encoding[index] 中减去 n,返回 encoding[index+1];如果小于,则从 n 中减去 encoding[index]index += 2,继续循环判断,直达超过 encoding 数组长度。

  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2025-05-29 22:19:19
 */
class RLEIterator {

  private int[] encoding;
  private int index;

  public RLEIterator(int[] encoding) {
    this.encoding = encoding;
    this.index = 0;
  }

  public int next(int n) {
    while (index < encoding.length) {
      if (encoding[index] >= n) {
        encoding[index] -= n;
        return encoding[index + 1];
      }
      n -= encoding[index];
      index += 2;
    }
    return -1;
  }
}

参考资料