2012-12-07 25 views
2

我想查找保存最大值的索引/索引ArrayList。我想保留数字的顺序(换句话说,不要排序),因为我想跟踪哪个索引具有什么价值。这些值来自一个随机数发生器,并且有两个(或更多)索引共享相同的最大值的可能性。在ArrayList中查找最大数量(可能有一个以上的最大值)

一个例子ArrayList

12,78,45,78

0,1,2,3 < - 指数

(所以指数,1和3包含我想要保持索引1和3的值为78的事实。我不想只创建一个新的ArrayList,并且索引0和1的新的ArrayList具有值78)

因此,我想找到所有具有最大值的索引,因为如果有多个索引,我将与他们一起“断开”连接。那么,如何找到包含最大值的指数并维持指数与价值的关系呢?

我写了下面的方法:

public static ArrayList<Integer> maxIndices(ArrayList<Integer> numArrayList) { 
// ??? 
    return numArrayList; 
} 

public static void removeElement(ArrayList<Integer> numArrayList, int index) { 
    numArrayList.remove(index); 
} 

public static int getMaxValue(ArrayList<Integer> numArrayList) { 
    int maxValue = Collections.max(numArrayList); 
    return maxValue; 
} 

public static int getIndexOfMaxValue(ArrayList<Integer> numArrayList, int maxVal) { 
    int index = numArrayList.indexOf(maxVal); 
    return index; 
} 
+1

它看起来像你基本上没有编写任何代码执行请求的任务。 [你试过什么?](http://whathaveyoutried.com) –

+0

@Matt Ball这就是我问的原因。我需要帮助如何做到这一点。我已经考虑过散列... –

+0

如果它必须是一个List,那么就不需要声明ArrayList 的习惯,然后将它声明为List。 – BevynQ

回答

3
public static ArrayList<Integer> maxIndices(ArrayList<Integer> list) { 
    List<Integer> indices = new ArrayList<Integer>(); 
    int max = getMaxValue(list); 
    for (int i = 0; i < list.size(); i++) { 
     if(list.get(i) == max) { 
      indices.add(list.get(i)); 
     } 
    } 

    return indices; 
} 
+0

如果我正确理解这一点,它是增加当前索引的值,如果它是最大的?因此,如果我只想要具有最大值的索引本身,那么我只需要:'indices.add(i);'? –

+0

@lord_sneed正确 –

+0

是的,我的坏。它应该是indices.add(i)而不是indices.add(list.get(i)) –

1

O(n)的解决方案:

public static List<Integer> maxIndices(List<Integer> l) { 
     List<Integer> result = new ArrayList<Integer>(); 
     Integer candidate = l.get(0); 
     result.add(0); 

     for (int i = 1; i < l.size(); i++) { 
      if (l.get(i).compareTo(candidate) > 0) { 
       candidate = l.get(i); 
       result.clear(); 
       result.add(i); 
      } else if (l.get(i).compareTo(candidate) == 0) { 
       result.add(i); 
      } 
     } 
     return result; 
    }