[Swift]LeetCode251.展平二維向量 $ Flatten 2D Vector

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-xtzbilfx-mb.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Implement an iterator to flatten a 2d vector.java

For example,
Given 2d vector =git

[
  [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].github

Hint:api

  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.微信


實現迭代器以展平二維向量。oracle

例如,編碼

給定的二維矢量=spa

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

經過重複調用next直到hasnext返回false,next返回的元素順序應該是:[1,2,3,4,5,6]。code

提示:

  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 }
相關文章
相關標籤/搜索