zoukankan      html  css  js  c++  java
  • [Swift]LeetCode251.展平二维向量 $ Flatten 2D Vector

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/10215129.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    Implement an iterator to flatten a 2d vector.

    For example,
    Given 2d vector =

    [
      [1,2],
      [3],
      [4,5,6]
    ]

    By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].

    Hint:

    1. How many variables do you need to keep track?
    2. Two variables is all you need. Try with x and y.
    3. Beware of empty rows. It could be the first few rows.
    4. To write correct code, think about the invariant to maintain. What is it?
    5. The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
    6. Not sure? Think about how you would implement hasNext(). Which is more complex?
    7. Common logic in two different places should be refactored into a common method.

    Follow up:
    As an added challenge, try to code it using only iterators in C++ or iterators in Java.


    实现迭代器以展平二维向量。

    例如,

    给定的二维矢量=

    [
      [1,2],
      [3],
      [4,5,6]
    ]

    通过重复调用next直到hasnext返回false,next返回的元素顺序应该是:[1,2,3,4,5,6]。

    提示:

    1. 您需要跟踪多少个变量?
    2. 你只需要两个变量。尝试使用x和y。
    3. 当心空行。可能是前几排。
    4. 要编写正确的代码,请考虑要维护的不变量。这是怎么一回事?
    5. 不变量是x,y必须始终指向二维向量中的有效点。您应该提前保持不变还是在需要时保持不变?
    6. 不确定?考虑如何实现hasNext()。哪个更复杂?
    7. 两个不同地方的公共逻辑应该重构为一个公共方法。

    跟进:

    作为一个额外的挑战,尝试用C++中的迭代器或Java中的迭代器对其进行编码。


     1 class WordDistance {
     2     var x:Int
     3     var y:Int
     4     var v:[[Int]] = [[Int]]()
     5     init(_ vec2d:[[Int]]) {
     6         // perform some initialization here
     7         v = vec2d
     8         x = 0
     9         y = 0
    10     }
    11     
    12     func next() -> Int
    13     {
    14         var num:Int = v[x][y]
    15         y += 1
    16         return num
    17     }
    18     
    19     func hasNext() -> Bool
    20     {
    21         while (x < v.count && y == v[x].count) {
    22             x += 1
    23             y = 0
    24         }
    25         return x < v.count
    26     }
    27 }
  • 相关阅读:
    Linux下分析某个进程CPU占用率高的原因
    Linux下查看某一进程所占用内存的方法
    jbd2导致系统IO使用率高问题
    Linux iotop命令详解
    1.Redis详解(一)------ redis的简介与安装
    Redis详解(十三)------ Redis布隆过滤器
    12.Redis详解(十二)------ 缓存穿透、缓存击穿、缓存雪崩
    面试问题总结
    算法与数据结构基础<二>----排序基础之插入排序法
    CarSim、Adams、Cruise和Simulink四款仿真软件的对比
  • 原文地址:https://www.cnblogs.com/strengthen/p/10215129.html
Copyright © 2011-2022 走看看