Counts pairs with given sum
Question
Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’.
Solution
用 HashMap 記錄並小心處理重複的狀況即可
- 如果用 HashMap 記錄,一開始算出的值是要求的兩倍
- 要特別注意兩個數相等的情況 (自己跟自己不能配在一起)
class Test
{
static int arr[] = new int[]{1, 5, 7, -1, 5} ;
// Returns number of pairs in arr[0..n-1] with sum equal
// to 'sum'
static int getPairsCount(int n, int sum)
{
HashMap<Integer, Integer> hm = new HashMap<>();
// Store counts of all elements in map hm
for (int i=0; i<n; i++){
// initializing value to 0, if key not found
if(!hm.containsKey(arr[i]))
hm.put(arr[i],0);
hm.put(arr[i], hm.get(arr[i])+1);
}
int twice_count = 0;
// iterate through each element and increment the
// count (Notice that every pair is counted twice)
for (int i=0; i<n; i++)
{
if(hm.get(sum-arr[i]) != null)
twice_count += hm.get(sum-arr[i]);
// if (arr[i], arr[i]) pair satisfies the condition,
// then we need to ensure that the count is
// decreased by one such that the (arr[i], arr[i])
// pair is not considered
if (sum-arr[i] == arr[i])
twice_count--;
}
// return the half of twice_count
return twice_count/2;
}