寻找Java数组中最长的向下序列
给定这个数组,
int [] myArray = {5,-11,2,3,14,5,-14,2};
我必须能够返回 3,因为最长的向下序列是 14,5,-14。 最快的方法是什么?
PS:下降序列是一系列不递增的数字。
Given this array
int [] myArray = {5,-11,2,3,14,5,-14,2};
I must be able to return 3 because the longest down sequence is 14,5,-14.
What's the fastest way to do this?
PS: Down sequence is a series of non-increasing numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
python 中的另一个实现:
another implementation in python:
只需浏览一下数字列表即可。伪代码:
注意:如果您不关心知道子序列发生的位置,则可以放弃包含 bestIndex 或 curIndex 的任何行,如 Gary 的实现中所示。
Just make one pass through the list of numbers. Pseudocode:
Note: You can ditch any line containing bestIndex or curIndex if you don't care about knowing where that subsequence occurs, as seen in Gary's implementation.
在java中:
由于您要求最快或更好的性能,因此仅在重置计数器之前检查最长的下降序列。永远不会在每次迭代中。但是,您必须在循环后再次检查,以防最长的序列位于数组的末尾。
In java:
Since you're asking for fastest or better performance, only check for the longest down sequence just before you reset the counter. Never on each iteration. However, you have to check again after the loop in case the longest sequence is at the end of the array.
Java中的另一种解决方案:
Another solution in Java:
正如比尔上面所说,这本质上是最长的递增子序列。请参阅维基百科条目以获取最佳解决方案。这是从那里引用的,进行了一些小的更改,以适用于非递减的情况,
请参阅上面我的评论中其他提议的解决方案的反例。
As Bill above said, this is essentially longest increasing subsequence. See the wikipedia entry for the optimal solution. This is quoted from there with small changes to work for the nondecreasing case
See counterexample to other proposed solution in my comment above.
最快的方法可能取决于环境:计算机和问题大小。
对于非常大的列表(或数组),并行化作业可能很有用,可以实现:
The fastest way might depend on the environment: computer and problemsize.
For a very large List (or array) it might be useful to parallelize the job, which could be implemented: