zoukankan      html  css  js  c++  java
  • [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;
      }
    }
  • 相关阅读:
    asp.net mvc (三)
    asp.net mvc(二)
    实现属于自己的Custom Formatter
    属性(Properties)和字段在C#中的关系
    LINQ 和泛型
    asp.net mvc(一)
    asp.net mvc(四)
    C#中的string
    asp.net mvc(五)
    Nullable Value Type
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12407362.html
Copyright © 2011-2022 走看看