我有五个数组,用于存储传入的 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/