假设有 Element
用position
上课属性(property)。
public class Element {
private float position;
public float getPosition() {
return position;
}
public void setPosition(float position) {
this.position = position;
}
}
此外,还有 ArrayList<Element> elements
持有随机分配的元素 position
值。然后元素按位置值升序排序。
问题:在某个位置区间内获取所有元素的最快方法是什么 <a,b>
,然后简单地遍历元素,像这样:
for (Element element : elements) {
if (element.getPosition() > a && element.getPosition() < b) {
// Do something with an element.
}
}
我假设有一个更快的方法,因为假设列表是排序的。
最佳答案
使用binary search找到范围的起点和终点,然后在它们之间迭代。
关于java - 从排序列表中获取间隔的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20924418/