在十万个数字里筛选出出现两次以上的数字,如1,2,3,4,5,6,7,7,8,8,8,9,9,9......,则打印出7,8,9.
我是觉得可以用java的map集合,我需要具体实现的源代码,希望能够给出解题思路和源代码,尤其是使用Java语言map集合方法。
import java.util.*;
public class DuplicateElements {
public static void main(String args[]) {
int count, i;
int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Count frequency of elements in array
for (Integer val : intArray) {
if (map.containsKey(val)) {
// Increment counter
map.put(val, map.get(val) + 1);
} else {
map.put(val, 1);
}
}
// Check for duplicate element
System.out.println("Duplicate Elements\n");
Set<Integer> keys = map.keySet();
for (Integer key : keys) {
if (map.get(key) > 1) {
System.out.print(key + " ");
}
}
}
}
可以吗.
public class DuplicatesArray {
public static void main(String[] args) {
int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9 };
System.out.println("Given array elements are: ");
for (int i = 0; i < intArray.length - 1; i++) {
System.out.print(intArray[i] + " ");
}
System.out.println("\n========================");
for (int i = 0; i < intArray.length - 1; i++) {
for (int j = i + 1; j < intArray.length; j++) {
if ((intArray[i] == (intArray[j])) && (i != j)) {
System.out.println("\nDuplicate Element is : " + intArray[j]);
}
}
}
}
}
Given array elements are:
1 2 3 4 5 6 7 7 8 8 8 9 9
========================
Duplicate Element is : 7
Duplicate Element is : 8
Duplicate Element is : 8
Duplicate Element is : 8
Duplicate Element is : 9
Duplicate Element is : 9
Duplicate Element is : 9
Duplicate Elements
7 8 9