算法 —— Count pairs with given sum ——dictionary的妙用,高,实在是高!!!

原文:https://www.geeksforgeeks.org/count-pairs-with-given-sum/

 

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’.

Examples:  

Input  :  arr[] = {1, 5, 7, -1}, 
          sum = 6
Output :  2
Pairs with sum 6 are (1, 5) and (7, -1)

Input  :  arr[] = {1, 5, 7, -1, 5}, 
          sum = 6
Output :  3
Pairs with sum 6 are (1, 5), (7, -1) &
                     (1, 5)         

Input  :  arr[] = {1, 1, 1, 1}, 
          sum = 2
Output :  6
There are 3! pairs with sum 2.

Input  :  arr[] = {10, 12, 10, 15, -1, 7, 6, 
                   5, 4, 2, 1, 1, 1}, 
          sum = 11
Output :  9

Expected time complexity O(n)
 

Naive Solution – A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum. 
 

 
 
// C# implementation of simple
// method to find count of
// pairs with given sum.
using System;
 
class GFG {
    public static void getPairsCount(int[] arr, int sum)
    {
 
        int count = 0; // Initialize result
 
        // Consider all possible pairs
        // and check their sums
        for (int i = 0; i < arr.Length; i++)
            for (int j = i + 1; j < arr.Length; j++)
                if ((arr[i] + arr[j]) == sum)
                    count++;
 
        Console.WriteLine("Count of pairs is " + count);
    }
 
    // Driver Code
    static public void Main()
    {
        int[] arr = { 1, 5, 7, -1, 5 };
        int sum = 6;
        getPairsCount(arr, sum);
    }
}
 
// This code is contributed
// by Sach_Code
Output
 
 

Count of pairs is 3

Time Complexity: O(n2
Auxiliary Space: O(1)
  

Efficient solution – 
A better solution is possible in O(n) time. Below is the Algorithm – 

  1. Create a map to store frequency of each number in the array. (Single traversal is required)
  2. In the next traversal, for every element check if it can be combined with any other element (other than itself!) to give the desired sum. Increment the counter accordingly.
  3. After completion of second traversal, we’d have twice the required value stored in counter because every pair is counted two times. Hence divide count by 2 and return.

Below is the implementation of above idea : 
 

 
 
// C# implementation of simple method to
// find count of pairs with given sum
using System;
using System.Collections.Generic;
 
class GFG {
    public static int[] arr = new int[] { 1, 5, 7, -1, 5 };
 
    // Returns number of pairs in arr[0..n-1]
    // with sum equal to 'sum'
    public static int getPairsCount(int n, int sum)
    {
        Dictionary<int, int> hm
            = new Dictionary<int, int>();
 
        // 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[arr[i]] = 0;
            }
 
            hm[arr[i]] = hm[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[sum - arr[i]] != 0) {
                twice_count += hm[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;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int sum = 6;
        Console.WriteLine("Count of pairs is "
                          + getPairsCount(arr.Length, sum));
    }
}
 
// This code is contributed by Shrikant13
Output
Count of pairs is 3

This article is contributed by Ashutosh Kumar

 

修改错误code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
[Theory]
[InlineData(new int[] { 6, 1, 3, 46 }, 47)]
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
public static int getPairsCount2(int[] arr, int sum)
{
    int n = arr.Length;
    Dictionary<int, int> hm
        = new Dictionary<int, int>();
 
    // 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[arr[i]] = 0;
        }
 
        hm[arr[i]] = hm[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.ContainsKey(sum - arr[i]) && hm[sum - arr[i]] != 0)
        {
            twice_count += hm[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;
}

  

 

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

posted @   PanPan003  阅读(57)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
历史上的今天:
2018-07-11 Docker网络配置概述
2018-07-11 Docker Engine SDKs and API 的开发2
2018-07-11 Docker Engine SDKs and API 的开发1
2018-07-11 Dockerize PostgreSQL
2018-07-11 Dockerize a .NET Core application
2018-07-11 Images之管理image
点击右上角即可分享
微信分享提示