★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-vgoicgmw-ky.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given two 1d vectors, implement an iterator to return their elements alternately.git
For example, given two 1d vectors:github
v1 = [1, 2] v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false
, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]
.微信
Follow up: What if you are given k
1d vectors? How well can your code be extended to such cases?app
Clarification for the follow up question - Update (2015-09-18):
The "Zigzag" order is not clearly defined and is ambiguous for k > 2
cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input:測試
[1,2,3] [4,5,6,7] [8,9]
It should return [1,4,8,2,5,9,3,6,7]
.spa
給定兩個一維向量,實現迭代器交替返回元素。code
例如,給定兩個一維向量:htm
v1 = [1, 2] v2 = [3, 4, 5, 6]
經過反覆調用next直到hasNext返回false,next返回的元素順序應該是:[1,3,2,4,5,6]。blog
後續:若是你獲得k 1d向量怎麼辦?您的代碼在這種狀況下能夠擴展到什麼程度?
後續問題澄清-更新(2015-09-18):
「之字形」順序沒有明肯定義,對於k>2的狀況不明確。若是「之字形」看起來不正確,請用「循環」替換「之字形」。例如,給定如下輸入:
[1,2,3] [4,5,6,7] [8,9]
它應該返回[1,4,8,2,5,9,3,6,7]。
Solution:
1 class ZigzagIterator { 2 var v:[Int] = [Int]() 3 var i:Int = 0 4 init(_ v1:[Int],_ v2:[Int]) 5 { 6 var n1:Int = v1.count 7 var n2:Int = v2.count 8 let n:Int = max(n1, n2) 9 for i in 0..<n 10 { 11 if i < n1 {v.append(v1[i])} 12 if i < n2 {v.append(v2[i])} 13 } 14 } 15 16 func next() -> Int 17 { 18 let num:Int = v[i] 19 i += 1 20 return num 21 } 22 23 func hasNext() -> Bool 24 { 25 return i < v.count 26 } 27 }
點擊:Playground測試
1 var zigzag = ZigzagIterator([1, 2],[3, 4, 5, 6]) 2 while(zigzag.hasNext()) 3 { 4 print(zigzag.next()) 5 } 6 //Print 7 /* 8 1 9 3 10 2 11 4 12 5 13 6 14 */