[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;
  }
}
原文地址:https://www.cnblogs.com/xuanlu/p/12407362.html