简体   繁体   English

有没有一种更快的方法来检查列表中的某个项目是否大于,小于或等于某个数字?

[英]Is there a faster way to check if an item in a list if it is greater than, less than, equal to a certain number?

Is there a faster way to check if an item in a list is greater than, less than, equal to a certain number? 有没有一种更快的方法来检查列表中的项目是否大于,小于或等于某个数字?

Or you just have to loop through it? 还是只需要遍历它? Im just curious if there are pre-built functions for this. 我只是好奇是否有预建的功能。

Example: 例:

List contains 5, 5, 10, 15, 15, 20. 清单包含5、5、10、15、15、20。

I want to check if how many items are actually >= 5. So the answer is 6. If I want to check >= 15, the answer would be 3. 我想检查实际上是否有多少个项目> =5。所以答案是6。如果我想检查> = 15,则答案应该是3。

step 1 : sort the list
step 2 : find the index for desired element
step 3 : print length-index

I don't see any such methods in the documentation , so I would say NO . 在文档中没有看到任何这样的方法,所以我要说 You have to iterate through the List. 您必须遍历列表。 If it is sorted, you can do binary search for faster results. 如果已排序,则可以执行二进制搜索以获得更快的结果。

您需要循环检查每个元素的条件。

Are you trying to sort? 您要排序吗? If you are dealing with arrays you can use Arrays.sort() else if you are dealing with collections you can use Collections.sort() 如果要处理数组,则可以使用Arrays.sort()如果要处理集合,则可以使用Collections.sort()

No there is no pre-built function afaik. 没有预构建的功能afaik。 If your list items are not order critical(ie you are not making any priority list or LIFO/FIFO), you can improve the searching through sorting list before finding the element. 如果您的列表项不是顺序关键的(即,您没有创建任何优先级列表或LIFO / FIFO),则可以在查找元素之前改善对排序列表的搜索。

您可以对列表进行排序,然后只需将其第一个和最后一个元素与数字进行比较。

That is why I am asking a question if there is such method that currently exists within the Collection. 这就是为什么我要问一个问题,即当前Collection中是否存在这种方法。

There is no such method in the standard collection APIs. 标准集合API中没有这种方法。

Write a loop. 写一个循环。 It should be quicker code and test a 5 line method to do this than scouring the internet for a 3rd party library. 它比在Internet上搜索第三方库要更快,并且测试5行方法可以做到这一点。 And your code will most likely be faster ... and certainly no slower. 而且您的代码很可能会更快……当然也不会慢。

Just do it. 去做就对了。 (I'd write the code for you myself, but it sounds like you need the practice ...) (我会亲自为您编写代码,但这听起来像您需要练习...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM