2012-12-01 7 views
-2

배열에 얼마나 많은 중복 항목이 있는지 계산하려고합니다.자바 배열에서 중복을 찾는 방법은?

예 :

[0, 2, 0] would return 2, [0, 0, 0] would return 3, [0, 1, 2] = 0 

지금까지 내가 모든 세 가지 항목이 동일한 경우 근무해야하지만 무엇이 같은되는 2 개 항목해야 이상의 적은 반환 왜 내가 모르겠어요.

int equal = 0; 

    for(int i = 0; i < recent.length; i++) { 
     for(int j = i; j < recent.length; j++) { 
      if(i != j && recent[i].equals(recent[j])) { 
       equal++; 
      } 
     } 
    } 
+0

문제를 다시 생각해 봐야합니다. – asheeshr

+0

특히, 문제의 * 정의 *를 재고해야합니다. 얼마나 정확하게 * 계산하려고합니까? 중복 된 요소가 몇 개입니까? 아니면 동일한 요소가 몇 쌍입니까? –

+0

[HashMap] (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html)에 대한 문서를 읽으십시오. –

답변

1

귀하의 알고리즘은 다음과 같은 방법으로 결함이 : 당신이 그 요소 후 모든 요소를보고 그들이 동일하게 일어나는 경우에, 당신은 카운터를 증가 배열의 모든 요소에 대해. 그러나 동일한 요소가 3 개있는 경우에는 첫 번째 요소와 두 번째 요소에 대해 내부 루프를 실행할 때 마지막 요소를 두 번 계산합니다. 또한 첫 번째 요소는 절대 세지 않습니다.

따라서 [0, 0, 0]은 우연히 작동하지만 다른 입력에는 사용할 수 없습니다.

1

코드에서 제공하는 코드가 같으므로 요소가 다른 요소와 같을 때마다 코드를 추가합니다.

중복되는 항목의 수는 (길이 - 중복이없는 항목의 수)와 같습니다. 후자의 "uniqueItems"를 호출 할 것입니다.

나는 다음을 추천 :

// set of every item seen 
Set<Integer> allItems = new HashSet<Integer>(); 
// set of items that don't have a duplicate 
Set<Integer> uniqueItems = new HashSet<Integer>(); 

for(int i = 0; i < recent.length; i++) { 
    Integer val = i; 
    if(allItems.contains(val)) { 
     // if we've seen the value before, it is not a "uniqueItem" 
     uniqueItems.remove(val); 
    } else { 
     // assume the value is a "uniqueItem" until we see it again 
     uniqueItems.add(val); 
    } 
    allItems.add(val); 
} 
return recent.length - uniqueItems.size(); 
0

당신은 같은 값을 가지고 인덱스 쌍의 수를 계산한다. 당신이 원하는 것은 둘 이상의 원소를 가진 동등한 요소의 모든 세트의 전체 크기입니다.

지도 또는 이와 유사한 방법을 사용하여 주어진 값의 총 출현 횟수를 계산합니다. 마지막으로, 하나 이상의 모양을 가진 각 키의 모양을 추가하는 키 값을 반복합니다.

1

중첩 루프를 사용하는 것은 상당히 비효율적이라고 생각합니다. 당신은 o (n)보다는 o (n^2)에서 그것을 할 수 있어야합니다.

다음에 대한 당신의 시간 당신 ...

public void run() { 
    int[] array = createRandomArray(2000000, 1000000); 
    System.out.println(countNumDups1(array)); 
} 


private int[] createRandomArray(int numElements, int maxNumExclusive) { 
    int[] array = new int[numElements]; 
    Random random = new Random(); 
    for (int i = 0; i < array.length; i++) { 
     array[i] = random.nextInt(maxNumExclusive); 
    } 
    return array; 
} 

private int countNumDups1(int[] array) { 
    Map<Integer, Integer> numToCountMap = new HashMap<>(); 
    for (int i = 0; i < array.length; i++) { 
     Integer key = array[i]; 
     if (numToCountMap.containsKey(key)) { 
      numToCountMap.put(key, numToCountMap.get(key) + 1); 
     } 
     else { 
      numToCountMap.put(key, 1); 
     } 
    } 
    int numDups = 0; 
    for (int i = 0; i < array.length; i++) { 
     Integer key = array[i]; 
     if (numToCountMap.get(key) > 1) { 
      numDups++; 
     } 
    } 
    return numDups; 
} 

난 당신이 위의 훨씬 더 빨리도 오토 박싱 및 객체 생성의 끔찍한 비 효율성을 고려하고 찾을 수 있습니다 생각한다면

.

+0

mfb의 솔루션이 내 것보다 낫습니다. 둘 다 o (n)이지만 그의 상상력은 몇 배 더 빨라질 것입니다. – kelceyp

+0

+1 pk, 여전히 좋은 해결책입니다! :디 – billz

0
int intArray[] = {5, 1, 2, 3, 4, 5, 3, 2}; 

String val = ""; 

int c = 1; 

Map<Integer, Integer> nwmap = new HashMap<Integer, Integer>(); 

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

    Integer key = intArray[i]; 

     if(nwmap.get(key) != null && nwmap.containsKey(key)){ 

     val += " Duplicate: " +String.valueOf(key)+"\n"; 

    }else{ 

     nwmap.put(key, c); 

      c++; 

    } 

} 

LOG.debug("duplicate value:::"+val); 
1

아래의 코드는 중복

을 찾기 위해 완벽하게 작동
int array[] = {1,2,3,4,5,2,3,4,5,3,4,5,4,5,5}; 

    HashMap<Integer,Integer> duplicates = new HashMap<Integer,Integer>(); 
    for(int i=0; i<array.length; i++) 
    { 
     if(duplicates.containsKey(array[i])) 
     { 
      int numberOfOccurances = duplicates.get(array[i]); 
      duplicates.put(array[i], (numberOfOccurances + 1)); 
     }else{ 
      duplicates.put(array[i], 1); 
     } 
    } 
    Iterator<Integer> keys = duplicates.keySet().iterator(); 
    System.out.print("Duplicates : "); 
    while(keys.hasNext()) 
    { 
     int k = keys.next(); 
     if(duplicates.get(k) > 1) 
     { 
      System.out.print(" "+k); 
     } 
    } 
0
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.LinkedHashMap; 
import java.util.Map; 


public class ArrayDuplicateCount { 

    /** 
    * @author:raviteja katari 
    */ 
    public static void main(String[] args) { 
     int intArray[] = {5, 1,4,4,4,5,1,2,1,2,5,5}; 


     //for counting duplicate items 
     int c = 0; 

     //creating map collection to hold integers as keys and Cont as value 
     Map<Integer, Integer> nwmap = new LinkedHashMap<Integer, Integer>(); 

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

      //Assigning array element to key 
      Integer key = intArray[i]; 

       //this code checks for elemnt if present updates count value else 
       //put the new Array elemnt into map and increment count 

       if(nwmap.containsKey(key)){ 

        //updating key value by 1 
        nwmap.put(key, nwmap.get(key) + 1); 

      }else{ 

       //Adding new array element to map and increasing count by 1 
        nwmap.put(key, c+1); 


        } 

          } 
      //printing map 
     System.out.println(nwmap); 
    } 

} 

출력 : {5 = 4 = 3 (1) = 3, 2, 4 = 2}

0
public void TotalduplicateNumbers { 
    int a[] = {2,8,2,4,4,6,7,6,8,4,5}; 
    Map<Integer,Integer> m = new HashMap<Integer,Integer>(); 
    for(int i=0;i<a.length;i++){    

      if(!m.containsKey(a[i])) 
      { 
       m.put(a[i], 1); 
      } 
      else 
      { 
       m.put(a[i], (m.get(a[i])+1)); 
      } 

    } 

    for(Integer i:m.keySet()){ 
     System.out.println("Number "+i+" "+"Occours "+m.get(i)+" time,"); 
    } 
} 

우리는 11 개의 숫자를 포함하는 배열을 가지고 있습니다. 논리는이 번호를 사용하여지도를 만드는 것입니다. 지도의 KEYS는 사용자가 입력해야하는 실제 번호이고 아니오입니다. 그 실제 번호의 occurnce. 그 열쇠의 가치가 될 것입니다. 여기서 containsKey() 메소드는 맵에 키가 이미 있는지 검사하고 적용된 부울 값 true 또는 false를 반환합니다.그것이 포함되어 있지 않으면 해당 키를 맵에 추가하고 해당 값은 1이어야합니다. 그렇지 않으면 키가 이미 맵에 포함되어 있으므로 get()을 사용하여 해당 키 값을 가져 와서 1 씩 증가시킵니다. 마지막으로 맵을 인쇄합니다.

OUTPUT -

수 2 Occours 2 시간, 4 Occours 번호 3 번, 5 번 Occours 1 번, 6 번 Occours 2 시간 번호 7 Occours 1 시간 번호 8 Occours 2 시간,

관련 문제