4 回答

TA貢獻1906條經驗 獲得超10個贊
下面的代碼沒有創建任何額外的數據結構。對于每個元素,它都會計算之前遇到的重復項的數量,并且只打印第一個重復項。
如果我在現實世界中這樣做,我會使用 aSet但我假設您還沒有了解它們,所以我只使用您已經創建的數組。
import java.util.Scanner;
public class DuplicateArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x = sc.nextInt();
int[] arr = new int[x];
System.out.print("Enter " + x + " values: ");
for (int i = 0; i < x; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Array: ");
for (int i = 0; i < x; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("Duplicate elements:");
for (int i = 0; i < arr.length; i++) {
int numDups = 0;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
numDups++;
}
}
if (numDups == 1) {
System.out.print(" " + arr[i]);
}
}
System.out.println();
}
}

TA貢獻1831條經驗 獲得超9個贊
如果不使用 Hashmap,我認為您最好的選擇是首先對數組進行排序,然后計算重復項。由于數組現在有序,您可以在每次數字切換后打印重復項!
如果這是一項任務,請繼續使用谷歌冒泡排序并將其實現為一種方法。

TA貢獻1828條經驗 獲得超6個贊
System.out.println("Duplicate Elements : ");
for(int i = 0; i<arr.length; i++){
boolean isDuplicate = false;
for(int k=0;k<i;k++){
if(arr[i]== arr[k]){
isDuplicate = true;
break;
}
}
if(isDuplicate){
continue;
}
int count = 0;
for(int j=0; j<arr.length; j++){
if(arr[i] == arr[j]){
count++;
}
if(count >1){
System.out.println(arr[i]);
break;
}
}
}

TA貢獻1802條經驗 獲得超5個贊
一種解決方案是創建一個單獨的列表來存儲找到的任何重復項。
也就是說,除了使用 List 的 .contains() 方法之外,您還可以確保每個 int 只創建一個條目。
public static void main(String[] args) {
// Sample array of ints
int[] ints = {1, 1, 4, 5, 2, 34, 7, 5, 3};
// Create a separate List to hold duplicated values
List<Integer> duplicates = new ArrayList<>();
// Find duplicates
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints.length; j++) {
if (ints[i] == ints[j] && // Are the ints the same value?
i != j && // Ignore if we're looking at the same index
!duplicates.contains(ints[i])) { // Check if our List of duplicates already has this entry
duplicates.add(ints[i]); // Add to list of duplicates
}
}
}
System.out.println("Duplicates: " + duplicates);
}
輸出:
Duplicates: [1, 5]
添加回答
舉報