重看了下, 你的问题好像没说清楚 不过试试用Chained Hash了吗? 1) create the hash table. 2) create a link-list node that stores the position of the value 3) put the values inside the hash table. Preferably, during insertion, you want LIFO 4) loop thru the array again 4.1) get hash[sum-value] 4.2) print if the position of the hash value is greater than current value's position. 4.3) if position > node->position, continue; ============= Yes, it's a hack. why do they test you on procedural stuff when all they teach you in school is OOP?
let me give u an example, 5,5,5,5,5,5; sum=10 there is no way to do it less than O(n^2). This is the worst case. this structure will help you: HashMap>
【在 j**y 的大作中提到】 : 还是没有答案?多谢了
C*g
24 楼
穿裤子的这个伴舞mm出工不出力。 短裙mm很抢眼,把注意力全吸引过去了。
g*s
25 楼
i dont know why Hashmap doesn't work. maybe i mis- understand the question? void findPairs(int[] array, int sum) { HashMap map = new HashMap(); for (int num : array){ if (map.containsKey(sum - num)){ for (int i = 0; i< map.get(sum-num); i++){ System.out.println(num + "," + (sum-num)); } } map.put(num, map.containsKey(num)? map.get(num)+1 : 1); } } the time is O(n+L) L is the pair num of output. if L<