정수 배열에 같은 요소가 둘 이상 있는지 어떻게 확인할 수 있습니까?하나의 정수 배열에 두 요소가 같은지 확인
예를 들어 배열의 모드를 가져오고 배열에 동일한 요소가 두 개 이상 없을 수 있으므로 모드가 없을 수 있습니다. 하지만 그 배열에 같은 요소가 두 개 있는지 확인해야합니다.
정수 배열에 같은 요소가 둘 이상 있는지 어떻게 확인할 수 있습니까?하나의 정수 배열에 두 요소가 같은지 확인
예를 들어 배열의 모드를 가져오고 배열에 동일한 요소가 두 개 이상 없을 수 있으므로 모드가 없을 수 있습니다. 하지만 그 배열에 같은 요소가 두 개 있는지 확인해야합니다.
중복을 허용하지 않는 Set
을 사용할 수 있습니다.
Set
에 추가하십시오.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");
}
와우. 번거롭게 여겨지는 무언가에 매우 간단합니다. – AdamMc331
@vefthym'Arrays.asList'는'List
@downvoter, 자신을 설명하십시오. –
한 가지 방법은 중첩 루프를 사용하여 반복하는 것입니다.
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
Pre-java 8, @kocko는 +1 (+1)으로 Set
을 사용할 수 있습니다. 당신이 java-8를 사용 괜찮다면, 여기에 한 줄의 :
public static boolean hasDistinctElements(int[] array) {
return IntStream.of(array).distinct().count() == array.length;
}
Upvote for Java8. 정말 멋진. –
당신은 이웃의 중복 배열 한 후 확인 정렬 다음과 같은 방법을 사용할 수 있습니다 :
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
}
1 정렬 배열 2. 각 요소를 다음 요소와 비교하십시오. – rossum
가능한 복제본 [Java의 배열에서 중복을 제거하는 가장 좋은 방법은 무엇입니까?] (http://stackoverflow.com/questions/357421/what-is-the-best-way-to-remove-duplicates-in -an-array-in-java) – aerokite