如何在java数组中多次查找元素的索引

时间:2015-08-31 12:55:21

标签: java

如何在java数组中找到多个同一元素的多个索引。例如,这个数组= {2,3,54,67,9,9,13,9}应该得到结果{4,5,7}。代码也应该很短。请提前帮助我。

2 个答案:

答案 0 :(得分:3)

使用HashMap<Integer, Integer>,例如

int[] array = ...

HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>();

for (int i = 0; i < array.length; ++i)
  if (hs.keySet().contains(array[i])) {
    // collision found
    System.out.print("array[");
    System.out.print(hs.get(array[i]));
    System.out.print("[ == array[");
    System.out.print(i);
    System.out.print("]");
  }
  else
    hs.put(array[i], i);

在您的情况下,输出可以简化:

   for (int i = 0; i < array.length; ++i) 
     if (hs.keySet().contains(array[i])) {
       // you don't have to print out all the indexes here,
       // you can, for instance, store indexes in ArrayList etc. 
       if (i >= 0)
         System.out.print(i);

       System.out.print(", "); 
       System.out.print(array[i]);

       array[i] = -1;
     }
     else
       hs.put(array[i], i);  

答案 1 :(得分:0)

仅使用通用int[]ArrayList<int>来解决您的问题:

int[] array = {2,3,54,67,9,9,13,9};
List<int> indexes = new ArrayList<int>();

for (int i = 0; i < array.length; i++)
{
    if (array[i] == <value>)
        indexes.add(array[i]);
}