Find all pairs of integers that sum to given value

Design an algorithm to find all pairs of integers within an array which sum to a specified
value.

Solution: say the array is X[], given value is M, the solution I know is to create a map containing pairs <M-X[i], count>, when traversing X[], if we find the key exist, that means there is a pair. I think there are two tricky things that people always ignore. One is to handle situation of repeated elements. e.g. {1, 2, 1, 2} and given value is 3. Another is if required to return all these pairs, what data structure will you use ? If you use HashMap, remember all of the keys form a set, you can't store <1, 2> twice.

public class PairSum {

public static Map<Integer, Integer> getPairSumToN(int[] array, int sum) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Map<Integer, Integer> result = new IdentityHashMap<Integer, Integer>();
for (int i : array) {
if (map.containsKey(i)) {
result.put(new Integer(i), sum-i);
int count = map.get(i);
if (count == 1) {
map.remove(i);
} else {
map.put(i, --count);
}
} else {
if (map.containsKey(sum-i)) {
int count = map.get(sum-i);
map.put(sum-i, ++count);
} else {
map.put(sum-i, 1);
}
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
int[] array = {3, 3, 2, 4, 1, 4, 5, 6, 3, 9, 2, 2};
System.out.println(getPairSumToN(array, 7));
System.out.println(getPairSumToN(array, 6));
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值