例如: 输入 [0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 9, 9, 9] 输出 [9, 4, 3, 1, 0]
public static List<Integer> countArrayListNumberAriseIsOdd(List<Integer> arr){
Map<Integer, Integer> numAndCount = new HashMap<Integer, Integer>();
//统计每个元素出现的次数
for (int i = 0; i < arr.size(); i++) {
if (numAndCount.get(arr.get(i)) == null){
numAndCount.put(arr.get(i), 1);
}else {
numAndCount.put(arr.get(i), numAndCount.get(arr.get(i)) + 1);
}
}
arr.clear();
//统计出现次数为奇数的元素
for (int key : numAndCount.keySet()){
if (numAndCount.get(key) % 2 != 0){
arr.add(key);
}
}
Collections.sort(arr, Collections.<Integer>reverseOrder());
return arr;
}
测试:
public class CountArrayListNumberAriseIsOdd {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Collections.addAll(arr,0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 9, 9, 9);
System.out.println("输入:" + arr);
System.out.println("输出:" + countArrayListNumberAriseIsOdd(arr));
}
}
输出结果: