获取LeetCode问题最大频率堆栈的未对齐地址错误的引用绑定



所以问题是实现一个最大频率堆栈,它将始终弹出最大频率元素,如果频率相同,则会弹出最接近顶部的元素。现在,我尝试实现一个堆栈映射,其中每个频率计数都映射到一个包含该频率元素的堆栈。

我面临的主要问题是这个错误:

第157行:字符16:运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebec0ba,这需要4字节对齐(stl_deque.h(0xbebebebeBebe0ba:注意:指针指向此处摘要:UndefinedBehaviorManitizer:未定义的行为/usr/bin//lib/gcc/x86_64-linux-gnu/8/../..//包括/c++/8/bits/stl_deque.h:162:16

失败的测试用例:

["FreqStack","push","push","push","push","push","push","pop","push","pop","push","pop","push","pop","push","pop","pop","pop","pop","pop","pop"]

[[],[4],[0],[9],[3],[4],[2],[],[6],[],[1],[],[1],[],[4],[],[],[],[],[],[]]

我不明白为什么会这样。我在SO上搜索了其他问题,错误似乎是由于未初始化的变量或越界访问造成的。但我似乎真的没有发现这个问题在我的代码中发生在哪里。

这是我的代码:

class FreqStack {
public:

unordered_map<int,int>freq;
unordered_map<int,stack<int>>st;
int maxfreq=0;
FreqStack() {


}

void push(int x) {
maxfreq=max(maxfreq,++freq[x]);
st[freq[x]].push(x);    
}

int pop() {
if(st[maxfreq].size()==0)
maxfreq--;
int t=st[maxfreq].top();
st[maxfreq].pop();
return t;
}
};
/*
* Your FreqStack object will be instantiated and called as such:
* FreqStack* obj = new FreqStack();
* obj->push(x);
* int param_2 = obj->pop();
*/

如有任何帮助,我们将不胜感激。

感谢:D

看起来不错

就在pop()中,我们可以简单地首先保存top,然后我们将stack.pop()和递减(如果堆栈不为空(,然后返回top:

// This block might trivially optimize the exec time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <unordered_map>
#include <stack>
#include <algorithm>
static const struct FreqStack {
using SizeType = std::uint_fast16_t;
FreqStack() {}
std::unordered_map<SizeType, SizeType> frequencies;
std::unordered_map<SizeType, std::stack<SizeType>> mapstack;
SizeType max_fr = 0;
const void push(const int x) {
max_fr = std::max(max_fr, ++frequencies[x]);
mapstack[frequencies[x]].push(x);
}

const int pop() {
const auto& top = mapstack[max_fr].top();
mapstack[max_fr].pop();
if (mapstack[frequencies[top]--].empty()) {
--max_fr;
}
return top;
}
};

最新更新