关于java:如何在int数组中查找元素的索引?

How to find the index of an element in an int array?

如何在类型int的Java数组中找到某个值的索引?

我尝试在未排序的数组上使用Arrays.binarySearch,它有时只能给出正确的答案。


1
2
3
Integer[] array = {1,2,3,4,5,6};

Arrays.asList(array).indexOf(4);

请注意,此解决方案是线程安全的,因为它创建了类型为List的新对象。

另外,您也不想循环或类似地调用它,因为每次都会创建一个新对象


如果您使用的是番石榴集合,则另一个选择是Ints.indexOf

1
2
3
4
5
6
// Perfect storm:
final int needle = 42;
final int[] haystack = [1, 2, 3, 42];

// Spoiler alert: index == 3
final int index = Ints.indexOf(haystack, needle);

当空间,时间和代码重用非常宝贵时,这是一个很好的选择。这也很简洁。


看一下API,它说您必须先对数组进行排序

所以:

1
2
Arrays.sort(array);
Arrays.binarySearch(array, value);

如果您不想对数组进行排序:

1
2
3
4
5
public int find(double[] array, double value) {
    for(int i=0; i<array.length; i++)
         if(array[i] == value)
             return i;
}


将此方法复制到您的班级中

1
2
3
4
5
6
7
8
9
10
11
12
 public int getArrayIndex(int[] arr,int value) {

        int k=0;
        for(int i=0;i<arr.length;i++){

            if(arr[i]==value){
                k=i;
                break;
            }
        }
    return k;
}

通过传递两个性能参数Array和value来调用此方法,并将其返回值存储在整数变量中。

1
int indexNum = getArrayIndex(array,value);

谢谢


您可以将其转换为列表,然后使用indexOf方法:

1
Array.asList(array).indexOf(1);

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#asList(T ...)
http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html#indexOf(java.lang.Object)


使用二进制搜索之前,需要对值进行排序。否则,手动方法是尝试选项卡中的所有整数。

1
2
3
4
5
6
7
8
public int getIndexOf( int toSearch, int[] tab )
{
  for( int i=0; i< tab.length ; i ++ )
    if( tab[ i ] == toSearch)
     return i;

  return -1;
}//met

一种替代方法是将每个索引的所有索引映射到映射中。

1
2
3
tab[ index ] = value;
if( map.get( value) == null || map.get( value) > index )
    map.put( value, index );

然后map.get(value)获取索引。

问候,
斯特凡

@pst,感谢您的评论。您可以发布其他替代方法吗?


1
2
3
    Integer[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
    List<Integer> arrlst = Arrays.asList(arr);
    System.out.println(arrlst.lastIndexOf(1));

您可以使用现代Java解决此问题。请使用以下代码:

1
2
3
static int findIndexOf(int V, int[] arr) {
        return IntStream.range(1, arr.length).filter(i->arr[i]==V).findFirst().getAsInt();
    }

简单:

1
2
3
4
5
public int getArrayIndex(int[] arr,int value) {
    for(int i=0;i<arr.length;i++)
        if(arr[i]==value) return i;
    return -1;
}

1
2
3
ArrayUtils.indexOf(array, value);
Ints.indexOf(array, value);
Arrays.asList(array).indexOf(value);


在使用for循环的主要方法中:
-在我的示例中,第三个for循环就是该问题的答案。
-在我的示例中,我制作了一个由20个随机整数组成的数组,为变量分配了最小的数字,并在计算循环数的同时当数组的位置达到最小值时停止了循环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Random;
public class scratch {
    public static void main(String[] args){
        Random rnd = new Random();
        int randomIntegers[] = new int[20];
        double smallest = randomIntegers[0];
        int location = 0;

        for(int i = 0; i < randomIntegers.length; i++){             // fills array with random integers
            randomIntegers[i] = rnd.nextInt(99) + 1;
            System.out.println(" --" + i +"--" + randomIntegers[i]);
        }

        for (int i = 0; i < randomIntegers.length; i++){            // get the location of smallest number in the array
            if(randomIntegers[i] < smallest){
                smallest = randomIntegers[i];                
            }
        }

        for (int i = 0; i < randomIntegers.length; i++){                
            if(randomIntegers[i] == smallest){                      //break the loop when array location value == <smallest>
                break;
            }
            location ++;
        }
        System.out.println("location:" + location +"
smallest:"
+ smallest);
    }
}

代码输出所有数字及其位置,以及最小数字的位置和最小数字的位置。


您可以这样做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 public class Test {

public static int Tab[]  = {33,44,55,66,7,88,44,11,23,45,32,12,95};
public static int search = 23;

public static void main(String[] args) {
    long stop = 0;
    long time = 0;
    long start = 0;
    start = System.nanoTime();
    int index = getIndexOf(search,Tab);
    stop = System.nanoTime();
    time = stop - start;
    System.out.println("equal to took in nano seconds ="+time);
    System.out.println("Index  of searched value is:"+index);
    System.out.println("De value of Tab with searched index is:"+Tab[index]);
    System.out.println("==========================================================");
    start = System.nanoTime();
    int Bindex = bitSearch(search,Tab);
    stop = System.nanoTime();
    time = stop - start;
    System.out.println("Binary search took nano seconds ="+time);
    System.out.println("Index  of searched value is:"+Bindex);
    System.out.println("De value of Tab with searched index is:"+Tab[Bindex]);
}



public static int getIndexOf( int toSearch, int[] tab ){
     int i = 0;
     while(!(tab[i] == toSearch) )
     {  i++; }
       return i; // or return tab[i];
   }
public static int bitSearch(int toSearch, int[] tab){
    int i = 0;
    for(;(toSearch^tab[i])!=0;i++){
    }
    return i;

}

}

添加了XOR :)


如果有人还在寻找答案,

  • 您可以使用[Apache Commons Library] [1]中的ArrayUtils.indexOf()。

  • 如果您使用的是Java 8,则还可以使用Strean API:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public static int indexOf(int[] array, int valueToFind) {
        if (array == null) {
            return -1;
        }
        return IntStream.range(0, array.length)
                .filter(i -> valueToFind == array[i])
                .findFirst()
                .orElse(-1);
    }

    [1]:https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#indexOf(int[],%20int)


  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    static int[] getIndex(int[] data, int number) {
        int[] positions = new int[data.length];
        if (data.length > 0) {
            int counter = 0;
            for(int i =0; i < data.length; i++) {
                if(data[i] == number){
                    positions[counter] = i;
                    counter++;
                }
            }
        }
        return positions;
    }

    二进制搜索:二进制搜索还可用于查找数组中数组元素的索引。但是二进制搜索只能在数组排序后使用。 Java为我们提供了一个内置函数,可以在Java的Arrays库中找到该函数,如果存在元素,它将返回索引,否则返回-1。复杂度将为O(log n)。
    下面是二进制搜索的实现。

    1
    2
    3
    4
    public static int findIndex(int arr[], int t) {
       int index = Arrays.binarySearch(arr, t);
       return (index < 0) ? -1 : index;
    }

    您可以遍历数组直到找到所需的索引,或者使用List。请注意,您可以使用asList()将数组转换为列表。


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    /**
         * Method to get the index of the given item from the list
         * @param stringArray
         * @param name
         * @return index of the item if item exists else return -1
         */

        public static int getIndexOfItemInArray(String[] stringArray, String name) {
            if (stringArray != null && stringArray.length > 0) {
                ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
                int index = list.indexOf(name);
                list.clear();
                return index;
            }
            return -1;
        }


    1
    2
    3
    4
    5
    6
    7
    8
    Integer[] array = {1, 2, 3, 4, 5, 6};

    for (int i = 0; i < array.length; i++) {
        if (array[i] == 4) {
            system.out.println(i);
            break;
        }
    }