敢教日月换新天。为有牺牲多壮志,

[Swift]LeetCode281. 之字形迭代器 $ Zigzag Iterator

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

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given two 1d vectors, implement an iterator to return their elements alternately.

For example, given two 1d vectors:

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?

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


给定两个一维向量,实现迭代器交替返回元素。

例如,给定两个一维向量:

v1 = [1, 2]
v2 = [3, 4, 5, 6]

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

后续:如果你得到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 */
复制代码

 

posted @   为敢技术  阅读(260)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
哥伦布
09:09发布
哥伦布
09:09发布
3°
多云
东南风
3级
空气质量
相对湿度
47%
今天
中雨
3°/15°
周三
中雨
3°/13°
周四
小雪
-1°/6°