Write an iterator that iterates through a run-length encoded sequence.

The iterator is initialized by RLEIterator(int[] A), where A is a run-length encoding of some sequence.  More specifically, for all even iA[i] tells us the number of times that the non-negative integer value A[i+1] is repeated in the sequence.

The iterator supports one function: next(int n), which exhausts the next n elements (n >= 1) and returns the last element exhausted in this way.  If there is no element left to exhaust, next returns -1instead.

For example, we start with A = [3,8,0,9,2,5], which is a run-length encoding of the sequence [8,8,8,5,5].  This is because the sequence can be read as "three eights, zero nines, two fives".

Example 1:

  1. Input: ["RLEIterator","next","next","next","next"], [[[3,8,0,9,2,5]],[2],[1],[1],[2]]
  2. Output: [null,8,8,5,-1]
  3. Explanation:
  4. RLEIterator is initialized with RLEIterator([3,8,0,9,2,5]).
  5. This maps to the sequence [8,8,8,5,5].
  6. RLEIterator.next is then called 4 times:
  7. .next(2) exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].
  8. .next(1) exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].
  9. .next(1) exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].
  10. .next(2) exhausts 2 terms, returning -1. This is because the first term exhausted was 5,
  11. but the second term did not exist. Since the last term exhausted does not exist, we return -1.

Note:

  1. 0 <= A.length <= 1000
  2. A.length is an even integer.
  3. 0 <= A[i] <= 10^9
  4. There are at most 1000 calls to RLEIterator.next(int n) per test case.
  5. Each call to RLEIterator.next(int n) will have 1 <= n <= 10^9.

这道题给了我们一种 Run-Length Encoded 的数组,就是每两个数字组成一个数字对儿,前一个数字表示后面的一个数字重复出现的次数。然后有一个 next 函数,让我们返回数组的第n个数字,题目中给的例子也很好的说明了题意。那么最暴力的方法肯定是直接还原整个数组,然后直接用坐标n去取数,但是直觉告诉我这种方法会跪,而且估计是 Memory Limit Exceeded 之类的。所以博主最先想到的是将每个数字对儿抽离出来,放到一个新的数组中。这样我们就只要遍历这个只有数字对儿的数组,当出现次数是0的时候,直接跳过当前数字对儿。若出现次数大于等于n,那么现将次数减去n,然后再返回该数字。否则用n减去次数,并将次数赋值为0,继续遍历下一个数字对儿。若循环退出了,直接返回 -1 即可,参见代码如下:


解法一:

  1. class RLEIterator {
  2. public:
  3. RLEIterator(vector<int> A) {
  4. for (int i = 0; i < A.size(); i += 2) {
  5. if (A[i] != 0) seq.push_back({A[i + 1], A[i]});
  6. }
  7. }
  8. int next(int n) {
  9. for (auto &p : seq) {
  10. if (p.second == 0) continue;
  11. if (p.second >= n) {
  12. p.second -= n;
  13. return p.first;
  14. }
  15. n -= p.second;
  16. p.second = 0;
  17. }
  18. return -1;
  19. }
  20. private:
  21. vector<pair<int, int>> seq;
  22. };

其实我们根本不用将数字对儿抽离出来,直接用输入数组的形式就可以,再用一个指针 cur,指向当前数字对儿的次数即可。那么在 next 函数中,我们首先来个 while 循环,判读假如 cur 没有越界,且当n大于当前当次数了,则n减去当前次数,cur 自增2,移动到下一个数字对儿的次数上。当 while 循环结束后,判断若此时 cur 已经越界了,则返回 -1,否则当前次数减去n,并且返回当前数字即可,参见代码如下:


解法二:

  1. class RLEIterator {
  2. public:
  3. RLEIterator(vector<int>& A): nums(A), cur(0) {}
  4. int next(int n) {
  5. while (cur < nums.size() && n > nums[cur]) {
  6. n -= nums[cur];
  7. cur += 2;
  8. }
  9. if (cur >= nums.size()) return -1;
  10. nums[cur] -= n;
  11. return nums[cur + 1];
  12. }
  13. private:
  14. int cur;
  15. vector<int> nums;
  16. };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/900

参考资料:

https://leetcode.com/problems/rle-iterator/

https://leetcode.com/problems/rle-iterator/discuss/168294/Java-Straightforward-Solution-O(n)-time-O(1)-space

[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

[LeetCode] 900. RLE Iterator RLE迭代器的更多相关文章

  1. LC 900. RLE Iterator

    Write an iterator that iterates through a run-length encoded sequence. The iterator is initialized b ...

  2. Java之集合初探(二)Iterator(迭代器),collections,打包/解包(装箱拆箱),泛型(Generic),comparable接口

    Iterator(迭代器) 所有实现了Collection接口的容器都有一个iterator方法, 用来返回一个实现了Iterator接口的对象 Iterator对象称作迭代器, 用来方便的实现对容器 ...

  3. Iterator接口(迭代器)

    目录 前言 原理 方法 异常 Iterator接口(迭代器) 前言 一般遍历数组都是采用for循环或者增强for,这两个方法也可以用在集合框架,但是还有一种方法是采用迭代器遍历集合框架,它是一个对象, ...

  4. STL源码分析-iterator(迭代器)

    1. GOF 迭代器设计模式 前面一篇文章有写到stl_list的实现,也实现了一下相应的iterator,但是后面觉得,实现具体容器之前有必要介绍一下iterator(迭代器) .那么迭代器是什么呢 ...

  5. Set,Multiset,Iterator(迭代器)详解

    Set,Multiset,Iterator(迭代器) Iterator:迭代器 我们可以发现所谓一些数据结构比如说数组和链表,它们都有一些相似的性质.我们看下面两个例子: 数组:定义数组\(int~a ...

  6. Iterator接口(迭代器)的使用

    Iterator接口(迭代器) 前言 在程序开发中,经常需要遍历集合中的所有元素.针对这种需求,JDK专门提供了一个接口java.util.Iterator.Iterator接口也是Java集合中的一 ...

  7. 【LeetCode】900. RLE Iterator 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/rle-itera ...

  8. leetcode 900. RLE Iterator

    Write an iterator that iterates through a run-length encoded sequence. The iterator is initialized b ...

  9. 【leetcode】900. RLE Iterator

    题目如下: 解题思路:非常简单的题目,直接递归就行了. 代码如下: class RLEIterator(object): def __init__(self, A): ""&quo ...

随机推荐

  1. PM学习笔记(一):解构产品经理

    1.产品定义:什么是产品 来自百度百科(链接)的解释:        产品是指能够供给市场 [1]  ,被人们使用和消费,并能满足人们某种需求的任何东西,包括有形的物品.无形的服务.组织.观念或它们的 ...

  2. linux不同服务器SSH连接与数据传送

    linux不同服务器通过SSH连接 SCP 命令进行数据传送 1. 安装scp yum install -y openssh-client 2.命令 复制文件(本地>>远程):scp /h ...

  3. 转:对softmax讲解比较清楚的博客

    https://blog.csdn.net/wgj99991111/article/details/83586508

  4. LeetCode 1290. Convert Binary Number in a Linked List to Integer

    题目 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListN ...

  5. springboot拦截器拦了静态资源css,js,png,jpeg,svg等等静态资源

    1.在SpringBoot中自己写的拦截器,居然把静态资源也拦截了,导致了页面加载失败. package com.bie.config; import com.bie.component.MyLoca ...

  6. HashHelper

    在C#中,数据的Hash以MD5或SHA-1的方式实现,MD5与SHA1都是Hash算法,MD5输出是128位的,SHA1输出是160位的,MD5比SHA1快,SHA1比MD5强度高. MD5与SHA ...

  7. 你不知道的Go unsafe.Pointer uintptr原理和玩法

    unsafe.Pointer 这个类型比较重要,它是实现定位和读写的内存的基础,Go runtime大量使用它.官方文档对该类型有四个重要描述: (1)任何类型的指针都可以被转化为Pointer (2 ...

  8. C 补充

    a++与++a的区别 #include <stdio.h> void main(){ int a=5,b=5; int i=0; for(i=0;i<2;i++){ printf(& ...

  9. vue.js环境在window和linux安装

    一.windows环境下安装vue 1.node.js安装:在node.js的官网上下载node的安装包 https://nodejs.org/en/download/ 安装完毕之后,在命令行下验证是 ...

  10. rabbitmq 实现多个消费队列

    1.将消费程序复制重新生成一个. 2.channel.BasicQos(0, 1, false); 空闲的先消费