【发布时间】:2023-01-25 14:07:52
【问题描述】:
while(!st.empty() && nums[i%n] >= st.top()) st.pop();
这段代码有效但是
while(nums[i%n] >= st.top() && !st.empty()) st.pop();
这不是!
我正在解决 leetcode 503(Next Greater Element II),我的答案是
int n = nums.size();
stack<int> st;
vector<int> nge(n, -1);
for(int i = 2*n-1; i >= 0; i--) {
while(nums[i%n] >= st.top() && !st.empty()) st.pop();
if(i < n && !st.empty()) nge[i%n] = st.top();
st.push(nums[i%n]);
}
return nge;`
但它没有用,除非我把!st.empty()放在nums[i%n] >= st.top()之前
【问题讨论】:
-
听起来一切正常。如果 st.empty() 为真,那么访问 st.top() 将无效,因为它不存在。因此,您需要先测试 st.empty ,短路评估将使 st.top() 在没有时被评估。
-
逻辑 AND 和 OR 运算符
&&和||使用 short-circuit evaluation。简而言之,使用您显示的代码,即使堆栈为空,您也可以调用st.top(),这会导致未定义的行为.
标签: c++ data-structures stl