2012-12-07 3 views
2

ArrayList의 최대 값을 갖는 인덱스/인덱스를 찾고 싶습니다. 인덱스에 어떤 가치가 있는지 추적하고 싶기 때문에 숫자가있는 순서 (즉, 정렬 없음)를 유지하려고합니다. 값은 난수 생성기에서 가져온 값이며 두 개 (또는 그 이상)의 인덱스가 동일한 최대 값을 공유 할 가능성이 있습니다.ArrayList의 최대 수 찾기 (복수의 최대 값 가능성 있음)

ArrayList :

12

, 78, 45, 78

0,1,2,3 < - 인덱스

(인덱스 그래서,도 1 및 3을 포함 값은 최대 값을 가지고 있습니다. 인덱스 1과 3의 값이 78이라는 사실을 유지하고 싶습니다. 새로운 ArrayList을 만들고 인덱스 0과 1을 가지고 싶지 않습니다. ArrayList의 값은 7830입니다.

따라서 인덱스가 두 개 이상인 경우 넥타이를 "끊으려고"할 것이므로 최대 값을 가진 모든 인덱스를 찾고 싶습니다. 그러면 최대 값을 포함하고 인덱스와 값의 관계를 유지하는 인덱스를 어떻게 찾을 수 있습니까? 나는 다음과 같은 방법을 쓴

:

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

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

이것을 정확하게 이해하면 현재 색인의 값이 최대 값에 추가됩니까? 그래서 인덱스 값 자체가 최대 값을 갖기를 원하면'index.add (i);'? –

+0

@lord_seed 정확히 –

+0

예, 좋았습니다. indices.add (list.get (i)) 대신에 indices.add (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; 
    }