简体   繁体   English

在数组中查找目标总和的对

[英]Find pairs for a target sum in an array

First there seems to lot of questions about this kind of problem but I couldn't find one that helps me.首先,关于这类问题似乎有很多问题,但我找不到对我有帮助的问题。

I am trying find pairs of target with O(n) or linear time complexity.我正在尝试找到具有O(n)或线性时间复杂度的目标对。

int[] input = {1, 6, 3, 2, 5, 5, 7, 8, 4, 8, 2, 5, 9, 9, 1};
int target = 10;

Expected output (in any order):预期输出(按任何顺序):

(1,9)(1,9)(6,4)(3,7)(2,8)(2,8)(5,5)(5,5)(5,5)(8,2)(8,2)(9,1)(9,1)

I have tried bruteforce approach with two for loops and it gives me right output but O(n*n) .我已经尝试了两个 for 循环的蛮力方法,它给了我正确的输出,但O(n*n)

for (int i = 0; i < input.length; i++) {
    for (int j = i + 1; j < input.length; j++) {
        if (input[i] + input[j] == target) {
            System.out.println("(" + input[i] + "," + input[j] + ")");
        }
    }
}

Then I have tried the hashing which does not give all pairs.然后我尝试了没有给出所有对的散列。 Two pairs are missing缺少两对

Set<Integer> set = new HashSet<>();
for (int num : input) {
    set.add(num);
    if (set.contains(target - num)) {
        System.out.println("(" + (target - num) + "," + num + ")");
    }
}

Output:输出:

(5,5)(5,5)(3,7)(2,8)(6,4)(2,8)(8,2)(5,5)(1,9)(1,9)(9,1)

I tried other approach which gave more pairs than expected我尝试了其他方法,它提供了比预期更多的对

Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < input.length; i++) {
    map.put(input[i], i);
}

for (int num : input) {
    if (map.containsKey((target - num))) {
        System.out.println("(" + num + "," + (target - num) + ")");
    }
}

Output:输出:

(1,9)(6,4)(3,7)(2,8)(5,5)(5,5)(7,3)(8,2)(4,6)(8,2)(2,8)(5,5)(9,1)(9,1)(1,9)

The issue with HashMap is occurring because you are looking for a value and target multiple times as you have added all the array elements in the beginning.发生HashMap的问题是因为您在开始时添加了所有数组元素,因此要多次查找值和目标。
For example : when the current map element num is 6, we found a pair as 4 (10-6) is there in the map.例如:当当前地图元素num为 6 时,我们找到了一对,因为地图中有 4(10-6)。
Again when num is 4, we again found a pair as 6 (10-4) is there in the map.再次当num为 4 时,我们再次找到一对,因为地图中存在 6 (10-4)。
So, to get the correct count and pairs, we need to check and add the numbers simultaneously.因此,要获得正确的计数和对,我们需要同时检查和添加数字。
Here is an O(N) implementation using HashMap .这是使用HashMapO(N)实现。

class Solution
{
    static int getPairsCount(int[] arr, int n, int target)
    {
        HashMap<Integer,Integer> map = new HashMap<>();
        int pairs=0;
        for (int i=0; i<n; i++)
        {
            if (map.containsKey(target - arr[i]))
            {
                pairs += map.get(target - arr[i]);
                for (int j=1; j<=map.get(target - arr[i]); j++)
                    System.out.print("(" + (target-arr[i]) + "," + arr[i] + ") ");
            }
            map.put(arr[i] , map.getOrDefault(arr[i],0)+1);
        }
        return pairs;
    }
    public static void main (String [] args)
    {
        int[] input = {1, 6, 3, 2, 5, 5, 7, 8, 4, 8, 2, 5, 9, 9, 1};
        int target = 10;
        System.out.println(getPairsCount(input , input.length , target));
    }
}

Output: 13 (pairs)输出: 13 (对)

(5,5) (3,7) (2,8) (6,4) (2,8) (8,2) (8,2) (5,5) (5,5) (1,9) (1,9) (9,1) (9,1)

And the issue with your HashSet approach is that it's removing the duplicate values and hence you are getting incorrect results.您的HashSet方法的问题在于它正在删除重复的值,因此您得到的结果不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在数组中查找值总和等于给定总和的索引对 - Find index pairs in array whose value sum is equal to given sum 从任意整数中求和到期望的总和,将数组结果作为集合返回 - From arbitrary integers,find pairs that sum to expected sum, return array results as collection 在 java 中通过 hashmap 从数组中查找所有元素对,其总和等于给定数 - Find all pairs of elements from an array whose sum is equal to given number by hashmap in java 如何在整数数组中找到所有对,其和等于给定数字 - How to Find all Pairs in an Array of Integers Whose sum is Equal to a Given Number 如何找到产品大于总和的货币对 - How to find pairs with product greater than sum 查找数组中所有可能的对 - Find all possible pairs in an array 在 Java 中的数组中查找互补对 - Find complementary pairs in array in Java 数组中数字对的差之和-Java - Sum of the difference of pairs of numbers in an array - Java 给定目标总和,找出给定数组中是否存在一对总和的元素 - Given a target sum, find if there is a pair of element in the given array which sums up to it 找到2个排序数组中的值对(每个数组中的1个值),其中和最接近目标值 - find the value pair in 2 sorted arrays (1 value from each array) where the sum is closest to a target value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM