【问题标题】:How do I account for duplicate values when solving the the two sum problem using a hash table?使用哈希表解决两个和问题时如何考虑重复值?
【发布时间】:2019-08-18 19:45:44
【问题描述】:

假设我有经典的二和问题,但有一个转折

如果给我一个整数列表和目标

我需要打印所有加起来为总和的值对

不重复对称值

不重用值

出于显而易见的原因,我试图避免使用蛮力方法,但如果我实现一个哈希映射,其中每个值作为键,元素是原始数组中该值的频率。如何让算法只打印每个值对一次?

function findPairs(arr, target){

  let hashMap = {};

  let results = [];

  for(let i = 0; i < arr.length; i++){
    if(hashMap.hasOwnProperty(arr[i])){
      hashMap[arr[i]]++;
    }else{
      hashMap[arr[i]] = 1;
    }
  }

  for(let i = 0; i < arr.length; i++){

    let diff = target - arr[i];

    if(hashMap.hasOwnProperty(diff) && hashMap[diff] > 0){ 
        results.push([arr[i], diff]);
        hashMap[diff]--;
    }
  }

  console.log(results);

}

findPairs([1, 3, -1, 11, 7], 10);
findPairs([5, 5, 5, 5, 5], 10);

findPairs([1, 3, -1, 11, 7], 10)

(3, 7) (-1, 11)

findPairs([5, 5, 5], 10)

(5, 5)

findPairs([5, 5, 5, 5], 10)

(5, 5) (5, 5)

findPairs([5, 5, 5, 5, 5], 10)

(5, 5) (5, 5)

findPairs([5, 5, 5, 5, 5, 5 ], 10)

(5, 5) (5, 5) (5, 5)

【问题讨论】:

    标签: algorithm hashmap big-o hashtable


    【解决方案1】:

    据我所知,这是问题的摘要:

    • 您的数组可以有重复的元素,例如:- [1, 2, 3, 2, 4]
    • 您想将重复的 [4, 1, 2, 3, 2, 4] 打印为 (2, 4), (2, 4)

      vector<pair<int, int> > findPairs(vector<int> arr, int target){
          int size = arr.size();
          map<int, int> hashMap;
      
          for(int i = 0; i < size; i++){
                  // C++ map assigns 0 as default if the key is not present, C++ map uses Red Black Tree 
                  if(hashMap[arr[i]] == 0)
                          hashMap[arr[i]] = 1;
                  else
                          hashMap[arr[i]]++;
          }
          /** Use to store result in (int, int) form
           *  Vector is a Dynamic array
           */
          vector<pair<int, int> > results;
          for(int i = 0; i < size; i++){
                  int diff = target - arr[i];
                  hashMap[arr[i]]--;
                  if(hashMap[diff] >= 1)
                          results.push_back(make_pair(arr[i], diff));
                  hashMap[diff]--;
          }
          return results;
      

      }

    此代码基于您在问题中提供的示例。

    【讨论】:

    • 谢谢,这是一个很好的解决方案。在进行查找时,我错过了减少频率计数器的步骤。
    • 没问题。将答案标记为已接受,这样其他人就不会再花时间回答了:)
    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 2021-08-30
    • 2021-08-13
    • 2020-06-13
    • 2020-12-21
    • 2021-07-19
    • 2011-01-22
    • 2010-09-21
    相关资源
    最近更新 更多