【问题标题】:Different outputs using different Data Structure使用不同数据结构的不同输出
【发布时间】:2021-04-21 10:16:29
【问题描述】:

我就以下问题提出这个问题:https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1

给定一个N整数数组和一个整数K,求数组中总和等于K的元素对数。

O(n) 时间和O(n) 空间中计算具有给定总和的对。 给定n = 4k = 6arr = [1 5 7 1]

这是我的代码的一部分:

#define MOD 1000007
int getPairsCount(int arr[], int n, int k) {
    // long long int h[MOD] = {0}; // This is the one I used originally
    // but it given 3 as the answer for the input n = 4, k = 6, arr = [1 5 7 1],
    
    unordered_map<long long, long long> h; // But when using map, it gives correct output as 2

    long long int count = 0;
    
    for(int i=0;i<n;i++){
        h[arr[i]]+=1;
    }
    
    for(int i=0;i<n;i++){
        count+=h[k - arr[i]];
        
        if(k == 2*arr[i])count--;
    }
    
    return (count/2);
    }
};

请任何人解释为什么会有差异。 MOD 是根据arr[i] 可以拥有(arr[i]&lt;=10^6) 的最大数量来选择的。 即使使用 memset 将所有值设置为 0 也不起作用。

那为什么使用maparray 作为哈希会有区别呢?

【问题讨论】:

  • 您希望从这些竞赛/挑战/竞争性编码/黑客网站中学到什么?如果是学习C++,那你什么都学不到。就像在这种情况下,正确的解决方案是基于数学或编程技巧。如果您不知道诀窍是什么并尝试编写蛮力方法,那么程序要么运行缓慢,要么无法处理模糊的边缘情况。如果你想学习 C++,你不会从毫无意义的在线竞赛网站 but only from a good C++ textbook 学到任何东西。
  • 好吧,@πάνταῥεῖ——一个漂亮的类比。除了飞机确实带来了一些对当地人有用的东西。
  • @Sam 是的,这就是丢失的原因there

标签: c++ arrays data-structures hash unordered-map


【解决方案1】:

基本调试:验证数据是否如您所想。使用调试器更容易做到这一点,但流式诊断也可以。让我们看看对count+=h[k - arr[i]] 的多次迭代评估(使用问题的输入)。

    for(int i=0;i<n;i++){
        std::cerr << "count += h[k - arr[i]]\t" // To remind us what we are looking at
                     "count += h[" << k << " - " << arr[i] << "]\t"
                     "count += h[" << k - arr[i] << "]\t"
                     << count << " += " << h[k - arr[i]] << "\n";
        count+=h[k - arr[i]];
        
        if(k == 2*arr[i])count--;
    }

可能的输出(使用数组而不是无序映射):

count += h[k - arr[i]]  count += h[6 - 1]   count += h[5]   0 += 1
count += h[k - arr[i]]  count += h[6 - 5]   count += h[1]   1 += 2
count += h[k - arr[i]]  count += h[6 - 7]   count += h[-1]  3 += 140720947826640
count += h[k - arr[i]]  count += h[6 - 1]   count += h[5]   140720947826643 += 1

此时,问题应该是显而易见的(至少,问题发生的迭代应该是显而易见的)。即使每个long long 值都是从long long 到某事物的unordered_map 的有效键,但这些值中至少有一半是数组的无效索引。

【讨论】:

  • 哦,我可能忘了使用 abs(k-arr[i])。谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
  • 2020-02-17
  • 2015-10-24
相关资源
最近更新 更多