当列表中不存在X时,从列表中查找大于X的值 [英] Find greater than X from list when X doesn't exist in list
问题描述
我正在尝试从列表中查找大于某个值(在我的情况下为已知)的值.
I am trying to find values from a list that are greater than certain value (known in my case).
示例:
给出
list = [1, 2, 5, 10, 15]; //list is sorted
查找大于X
的值(在这种情况下为=7
).
Find values greater than X
(=7
in this case).
所需结果=返回值= [10, 15]
Desired result = Return a list with values = [10, 15]
我尝试使用Java二进制搜索,例如
I tried using java binary search, like
int index = Collections.binarySearch(list, X);
我的计划是找到索引(X
),然后返回索引之后的所有元素.
My plan was to find index (of X
) and then return all the elements after index.
但是索引返回负值,据我了解,因为7
不在列表中.
But index return negative, that I understand because 7
is not in the list.
还有其他方法吗?有人建议.
Is there any other way ? Someone please suggest.
推荐答案
If your list is sorted than Collection#binarySearch will return the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). You can calculate begin index of insertion_point like below:
index= -(insertion_point) - 1
-(insertion_point)= index+1
insertion_point=-(index+1)
After got the begin index of List
than you can apply subList method to got the resulted list greater than X.
Integer[] values = {1, 2, 5, 10, 15};
List<Integer> list = new ArrayList<>(Arrays.asList(values));
int X = 7;
int index = Collections.binarySearch(list, X);
int insertion_point = -(index+1); // As calculated above.
List<Integer> res = list.subList(insertion_point, list.size());
System.out.println(res);
输出:[10,15]
这篇关于当列表中不存在X时,从列表中查找大于X的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!