Java 查找数组中的元素

标签 java

我有五个数组,用于存储传入的 int 数字,例如:

int array1 = {1,6,..}
int array2 = {2,7,..}
.
.
int array5 = {5,10,..}

现在,我要做的就是在另一个数组中搜索下一个数字。

喜欢,

for(i = 0, i < array1.size ; i++){

int element = array1[0] ;

//here array2, array3, ..., array5 can have different size
search for array2 to find element+1
search for array3 to find element+2
.
.
search for array5 to find element+5
}

我现在正在做的是:

Run for loop for 0 to array2 size, to find element+1 (so for others)

但是,速度相当慢。任何人都可以给我一些想法,如何使其更快(我也可以将数组更改为任何其他数据结构)。

抱歉,我在提问时犯了两个错误,我应该提到的是:

1) Arrays are sorted (incremental elements always).
2) Array elements are very few (2-3) so Binary Search will be expensive.
3) I have to perform the search for thousand times means when channel input pause, I have to perform search, then again channel start and I have to perform search ... so on.

最佳答案

如果数组已排序,请使用二分搜索来查找元素,而不是为每个元素循环遍历。

关于Java 查找数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194441/

相关文章:

java - 统一成本搜索实现

java - 返回最大尺寸的列表<integer>对象

java - springmvc @RequestMapping 下面两个url如何精确匹配?

java - 如何使用 HTTPClient 设置 HTTP 请求 header "authentication"?

java - jboss 上的 Yui 压缩器 StringIndexOutOfBoundsException

java - 掷骰子程序

java - 需要类的实例来重写方法

java - 如何从 SQLite 中的特定列获取具有特定值的行?

java - JAVA中简单的RSA加密和解密消息

java - 使用鼠标调整没有边框的 JFrame 的大小