搜索排序列表<龙>对于最近的和小于 [英] Search sorted List<Long> for closest and less than

查看:189
本文介绍了搜索排序列表<龙>对于最近的和小于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一些名为 X 和分类列表<龙> 。什么是最有效的算法来查找列表&LT指数或价值;龙> (我)小于 X (二)最接近 X 上线人数(假设条件(i)已satsified)?

Consider some long called X and a sorted List<Long>. What is the most efficient algorithm to find the index or value in the List<Long> that is (i) less than X, and (ii) The closest to X on the number line (assuming condition (i) has been satsified)?

例如,这可能是一个问题的设置:

For example this could be a problem setup:

long X = 500;
List<Long> foo = new Arraylist<Long>();
foo.add(450L);
foo.add(451L);    
foo.add(499L);
foo.add(501L);
foo.add(550L);

Collections.sort(foo); // It's always sorted.

我想算法要么返回 499 或返回与相关联的指数499 (在这种情况下, I = 2 )。

I would like the algorithm to either return 499 or to return the index associated with 499 (in this case i=2).

推荐答案

鉴于在列表中的值是唯一的,我会建议你使用设置,更特别是一个 TreeSet的 ,因为你是反正排序列表。您可以使用 NavigableSet#楼(E) 方法,它不正是你想要的。

Given that the values in your list are unique, I would suggest you to use a Set, more specifically a TreeSet, as you are anyways sorting your list. You can use the NavigableSet#floor(E) method which does exactly what you want.

返回此的最大元素设为小于或等于给定元素,或如果不存在这样的元素

Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.

因此​​,code看起来像:

So, the code would look like:

long X = 500;
NavigableSet<Long> foo = new TreeSet<Long>();

foo.add(450L);
foo.add(451L);    
foo.add(499L);
foo.add(501L);
foo.add(550L);

System.out.println(foo.floor(X));   // 499

的方法,也将用户定义的对象。只是你必须通过比较&LT; YourClass方式&gt; TreeSet的构造在实例它

这篇关于搜索排序列表&LT;龙&GT;对于最近的和小于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆