识别一组数组中最小数据对应的索引
我相信这是一个微不足道的算法问题,但我似乎无法找到有效而优雅的解决方案。
我们有 3 个 int 数组(Aa、Ab、Ac)和 3 个游标(Ca、Cb、Cc),它们指示相应数组中的索引。我想识别并增加指向最小值的光标。如果该游标已经位于数组的末尾,我将排除它并增加指向第二个最小值的游标。如果只有 1 个游标不在数组末尾,我们将增加该游标。
我能想到的唯一解决方案很复杂和/或不是最佳的。例如,我总是以一个巨大的 if...else... 结束,
有人看到这个问题的巧妙解决方案吗?
我正在使用 C++ 进行编程,但请随意使用伪代码或您喜欢的任何语言进行讨论。
谢谢
This is a trivial algorithmic question, I believe, but I don't seem to be able to find an efficient and elegant solution.
We have 3 arrays of int (Aa, Ab, Ac) and 3 cursors (Ca, Cb, Cc) that indicate an index in the corresponding array. I want to identify and increment the cursor pointing to the smallest value. If this cursor is already at the end of the array, I will exclude it and increment the cursor pointing to the second smallest value. If there is only 1 cursor that is not at the end of the array, we increment this one.
The only solutions I can come up are complicated and/or not optimal. For example, I always end up with a huge if...else...
Does anyone see a neat solution to this problem ?
I am programming in C++ but feel free to discuss it in pseudo-code or any language you like.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
伪java代码:
本质上,它执行以下操作:
用
aa[ca]
、ab[cb]
初始化数组values
和ac[cc]
对
值进行排序
扫描
值
并在可能的情况下递增(即尚未位于数组的末尾)相应值的索引,排序最多是 O(n lg n),但我只对 3 个元素的数组进行排序。
Pseudo-java code:
Essentially, it does the following:
initialize an array
values
withaa[ca]
,ab[cb]
andac[cc]
sort
values
scan
values
and increment if possible (i.e. not already at the end of the array) the index of the corresponding valueI know, sorting is at best O(n lg n), but I'm only sorting an array of 3 elements.
这个解决方案怎么样:
what about this solution:
伪代码:编辑:整理了一下
Pseudo code: EDIT : tidied it up a bit