[英]Search for the smallest element in a list after some value
Consider a list of integers <1,5,10>
(assume sorted in ascending fashion). 考虑整数<1,5,10>
的列表(假定以升序排序)。
Given an integer, say, key = 6
, is there a utility method that returns the smallest element after key
(in this case it would be 10)? 给定一个整数,例如key = 6
,是否有一种实用程序方法返回key
之后的最小元素(在这种情况下为10)?
NB: Looping through the elements in the list and comparing it with key
is an obvious way to do it, but I'm just wondering if there exist a utility method to do the same thing :) 注意:遍历列表中的元素并将其与key
进行比较是一种显而易见的方法,但是我只是想知道是否存在实用工具来执行相同的操作:)
Have you considered Binary Search ? 您是否考虑过二进制搜索 ? Collections has a binarySearch method which you could use. 集合具有您可以使用的binarySearch方法。
From the Collections binarySearch documentation: 从Collections binarySearch文档中:
Returns: 返回值:
index of the search key, if it is contained in the list; 搜索关键字的索引(如果包含在列表中); otherwise, (-(insertion point) - 1). 否则为(-(插入点)-1)。 The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. 插入点定义为将关键字插入列表的点:如果列表中的所有元素均小于指定的关键字,则第一个元素的索引大于关键字,或者为list.size()。 Note that this guarantees that the return value will be >= 0 if and only if the key is found. 请注意,这保证了当且仅当找到键时,返回值才> = 0。
I will let you figure out how you can use the return value of Collections.binarySearch to get the answer you need. 我将让您弄清楚如何使用Collections.binarySearch的返回值来获取所需的答案。
Binary search works, but if in fact you have a sorted set of values, then instead of a List
, a SortedSet
(or even better a NavigableSet
), is the most natural data structure of choice. 二进制搜索有效,但是如果实际上您拥有一组排序的值,那么最自然的选择是使用SortedSet
(甚至更好的NavigableSet
)代替List
,而不是List
。
Here's an example usage: 这是一个示例用法:
NavigableSet<Integer> nums = new TreeSet<Integer>(
Arrays.asList(9,1,5,7,3)
);
System.out.println(nums); // "[1, 3, 5, 7, 9]"
System.out.println(nums.first()); // "1"
System.out.println(nums.last()); // "9"
System.out.println(nums.higher(3)); // "5"
System.out.println(nums.lower(8)); // "7"
System.out.println(nums.subSet(2,8)); // "[3, 5, 7]"
System.out.println(nums.subSet(1, true, 5, true)); // "[1, 3, 5]"
There's also NavigableMap
counterpart that can be even more useful in some scenarios. 还有NavigableMap
对应项,在某些情况下可能会更加有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.