get indexes of n smallest elements in an array

前端 未结 6 1611
醉酒成梦
醉酒成梦 2020-12-17 08:15

I have an int array int[] myArray = new int[100]; and want to get indexes of smallest 10 (any n) elements. How can I do this?

6条回答
  •  心在旅途
    2020-12-17 08:56

    If you are looking for a practical answer (versus the actual sorting alg., etc.), then just use a HashMap or PriorityQueue. If speed isn't a concern try this easy alg. It is easier than a PriorityQueue since you don't need a custom object:

    HashMap> indexMap = new HashMap>();

    Fill indexMap so we can get the indices for any given number in array

    for (int index = 0; index <= array.size; index++) {
       if (indexMap.get(array[index]) == null) { // Prime it with an ArrayList
          indexMap.put(array[index], new ArrayList());
       }
    
       indexMap.get(array[index]).add(index);
    }
    

    For the smallest n numbers in array, print out their index.

    Arrays.sort(array);
    for (int index = 0; index <= n; index++) {
       System.out.println(indexMap.get(array[index]).remove(0));
    }
    

提交回复
热议问题