2014-12-15 3 views
0

정수 배열에 같은 요소가 둘 이상 있는지 어떻게 확인할 수 있습니까?하나의 정수 배열에 두 요소가 같은지 확인

예를 들어 배열의 모드를 가져오고 배열에 동일한 요소가 두 개 이상 없을 수 있으므로 모드가 없을 수 있습니다. 하지만 그 배열에 같은 요소가 두 개 있는지 확인해야합니다.

+4

1 정렬 배열 2. 각 요소를 다음 요소와 비교하십시오. – rossum

+1

가능한 복제본 [Java의 배열에서 중복을 제거하는 가장 좋은 방법은 무엇입니까?] (http://stackoverflow.com/questions/357421/what-is-the-best-way-to-remove-duplicates-in -an-array-in-java) – aerokite

답변

3

중복을 허용하지 않는 Set을 사용할 수 있습니다.

  1. 배열의 모든 요소를 ​​Set에 추가하십시오.
  2. Set의 크기와 배열의 크기를 비교하십시오.
    • 동일하면 중복이 없습니다.
    • 그렇지 않으면 중복됩니다. 예를 들어

:

int[] array = ... 
Set<Integer> set = new HashSet<Integer>(); 
for (int i : array) { 
    set.add(i); 
} 
if (set.size() == array.length) { 
    System.out.println("There are no duplicates"); 
} else { 
    System.out.println("There are duplicates"); 
} 
+0

와우. 번거롭게 여겨지는 무언가에 매우 간단합니다. – AdamMc331

+1

@vefthym'Arrays.asList'는'List '을 만들 것이므로 작동하지 않을 것입니다. –

+1

@downvoter, 자신을 설명하십시오. –

1

한 가지 방법은 중첩 루프를 사용하여 반복하는 것입니다.

for(int i=0; i<arr.length ; i++) 
    for(int j=i; j<arr.length ; j++) 
     if(arr[i] == arr[j]) 
      //two same elements detected 
5

Pre-java 8, @kocko는 +1 (+1)으로 Set을 사용할 수 있습니다. 당신이 를 사용 괜찮다면, 여기에 한 줄의 :

public static boolean hasDistinctElements(int[] array) { 
    return IntStream.of(array).distinct().count() == array.length; 
} 
+1

Upvote for Java8. 정말 멋진. –

1

당신은 이웃의 중복 배열 한 후 확인 정렬 다음과 같은 방법을 사용할 수 있습니다 :

private boolean checkDuplicates(int[] array) { 
    Arrays.sort(array);      //sort the array in ascending order 
    int prevElem = array[0]; 
    for (int i = 1; i < array.length; ++i) { 
     if (array[i] == prevElem) { //if duplicates exist, they will be neighbors, since the array is sorted 
      return true; //no need to examine the rest of the array elements, if a duplicate is found 
     } 
     prevElem = array[i]; 
    } 
    return false; //if no duplicates are found, return true 
} 
관련 문제