【发布时间】:2014-12-22 12:19:45
【问题描述】:
试图返回哈希表中出现奇数次的所有数字,我已经注释了坏行。
基本上,我希望代码通过 int 数组并将其分配给哈希表的键,如果它再次出现(偶数次),则将布尔值设为 false,如果出现奇数次则布尔值为真。然后我需要遍历哈希表的键并返回布尔值为 true 的键。
package practice;
import java.util.*;
/*
You are given an integer array, where all numbers except for TWO numbers appear even number of times.
Q: Find out the two numbers which appear odd number of times.
*/
public class hashTable{
public static void main(String[] args){
int[] test = {2, 2, 5, 7, 4, 4};
List<Integer> solution = new ArrayList<Integer>();
Hashtable<Integer, Boolean> ht = new Hashtable<Integer, Boolean>();
Boolean check = true;
for (int item : test){
if (!ht.containsKey(item)){
check = true;
} else{
check = false;
ht.put(item, check);
}
}
for (int item : ht.keySet()){
if (ht.get(item) == true){
solution.add(item);
}
}
System.out.println("the result is");
System.out.println(solution);
}
}
【问题讨论】:
-
作为旁注,Hashtable 已过时,在这种情况下,您应该改用 HashMap。