[英]Checking whether you have two of the same elements in one integer array
如何檢查(在Java中)整數數組中是否有兩個或多個相同的元素?
例如,如果您想獲取數組的模式,而該數組可能沒有兩個或多個相同的元素,那么就不會有任何模式。 為了知道這一點,您必須檢查該數組中是否有兩個相同的元素。
在Java 8之前的版本中,您可以按@kocko所述使用Set
(對他+1)。 如果您不介意使用java-8 ,則可以使用以下代碼:
public static boolean hasDistinctElements(int[] array) {
return IntStream.of(array).distinct().count() == array.length;
}
您可以使用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");
}
一種方法是使用嵌套循環進行循環。
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
您可以使用以下方法對數組進行排序,然后檢查鄰居是否重復:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.