矩阵行中较大的值
如何获得矩阵行中两个较大的数字?
如果矩阵中其他行的数字较大,则无法显示。
例如,假设我有以下矩阵,
int mat[][] ={{1,2,3}{4,5,6}{7,8,9}};
如果我从第 0 行搜索 2 个较大的数字,它应该返回索引 1 和 2(值 2 和 3)。
How can I get the 2 biggers numbers of a matrix row?
If the matrix have a bigger number in other row, it can't be shown.
For example, let's suppose I have the following matrix
int mat[][] ={{1,2,3}{4,5,6}{7,8,9}};
if I search the 2 biggers numbers from the row 0, it should return me the indexes 1 and 2 (values 2 and 3).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于“矩阵”在 Java 中存储为数组数组的方式,问题简化为简单地在
int[]
中查找最高 2 个元素(可能具有相等值)的索引。因此,解决方案非常简单:
使用数组的 1 遍
O(N)
线性扫描。Integer.MIN_VALUE
和>=
比较的组合使其一切正常。high1i
是第一个最高元素的索引,high2v
是第二个最高元素的值,依此类推。Due to the way your "matrix" is stored in Java as an array of arrays, the problem is reduced to simply finding the indices of the highest 2 elements (possibly of equal values) in an
int[]
.The solution therefore is quite simple:
This uses a 1-pass
O(N)
linear scan of the array. The combination ofInteger.MIN_VALUE
and>=
comparison make it all work nicely.high1i
is the index of the first highest element,high2v
is the value of the second highest element, etc.更新以返回索引。另外,我认为在此过程中更改原始矩阵是不可取的,因此我编写了一个测试来确认我的原始实现确实更改了矩阵,然后修改了代码,使其不再更改。
Updated to return the indexes. Also, I imagine it's undesirable to change the original matrix in the course of this, so I wrote a test that confirmed my original implementation did change the matrix, then modified the code so it doesn't, anymore.
我对 @Carl 代码进行了改编,我得到了这个,
我们可以在我评论的地方放置一个 break 指令,但我不知道它是否会提高算法的性能。
I made an adaption fro @Carl code, and I got this
we can put a break instruction where I commented, but I don't know if it will improve the performance of the algorithm.