共計 694 個字符,預計需要花費 2 分鐘才能閱讀完成。
可以使用 HashMap 來統計數組中重復元素的個數。首先遍歷數組,將數組中的元素作為鍵,出現的次數作為值存儲在 HashMap 中。然后再遍歷 HashMap,輸出重復元素及其出現的次數。
以下是示例代碼:
import java.util.HashMap;
import java.util.Map;
public class CountDuplicates {public static void main(String[] args) {int[] array = {1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1};
// 使用 HashMap 來統計重復元素的個數
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : array) {if (countMap.containsKey(num)) {countMap.put(num, countMap.get(num) + 1);
} else {countMap.put(num, 1);
}
}
// 輸出重復元素及其出現的次數
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {int num = entry.getKey();
int count = entry.getValue();
if (count > 1) {System.out.println(" 重復元素:" + num + ",出現次數:" + count);
}
}
}
}
以上代碼輸出的結果為:
重復元素:1,出現次數:3
重復元素:2,出現次數:2
重復元素:3,出現次數:2
重復元素:4,出現次數:2
重復元素:5,出現次數:2
丸趣 TV 網 – 提供最優質的資源集合!
正文完