[Algo] 181. 2 Sum All Pair I
Posted xuanlu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Algo] 181. 2 Sum All Pair I相关的知识,希望对你有一定的参考价值。
Find all pairs of elements in a given array that sum to the given target number. Return all the pairs of indices.
Assumptions
-
The given array is not null and has length of at least 2.
Examples
-
A = {1, 3, 2, 4}, target = 5, return [[0, 3], [1, 2]]
-
A = {1, 2, 2, 4}, target = 6, return [[1, 3], [2, 3]]
public class Solution { public List<List<Integer>> allPairs(int[] array, int target) { // Write your solution here // for the same number, need to keep all the index in List Map<Integer, List<Integer>> map = new HashMap<>(); List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < array.length; i++) { int tmp = target - array[i]; if (map.containsKey(tmp)) { List<Integer> idxList = map.get(tmp); for (int idx : idxList) { res.add(Arrays.asList(idx, i)); } } if (map.get(array[i]) == null) { map.put(array[i], new ArrayList<Integer>()); } map.get(array[i]).add(i); } return res; } }
以上是关于[Algo] 181. 2 Sum All Pair I的主要内容,如果未能解决你的问题,请参考以下文章
Sum All Primes-freecodecamp算法题目