码迷,mamicode.com
首页 > 其他好文 > 详细

[Algo] 181. 2 Sum All Pair I

时间:2020-03-04 09:14:57      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:key   dice   ice   i++   ==   sam   array   pair   list   

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

标签:key   dice   ice   i++   ==   sam   array   pair   list   

原文地址:https://www.cnblogs.com/xuanlu/p/12407362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!