以下leetcode问题中的运行时错误
Runtime error in following leetcode problem
问题 link - https://leetcode.com/problems/maximum-average-subarray-i/
class Solution
{
public:
double findMaxAverage(vector<int>& nums, int k)
{
deque<pair<int,int>> d; //deque since its a sliding window problem
vector<double> ans; //to return answer
double avg;
double sum=0;
int n=nums.size();
for(int i=0;i<n;i++)
{
if(!d.empty() && d.front().second<=(i-k)) //out of window size
{
avg=sum/k;
ans.push_back(avg); //push the average of k elements in answer vector
sum=sum-d.front().first; //remove the sum of first element when moving to next
d.pop_front(); //remove front element of deque
}
d.push_back(make_pair(nums[i],i)); //push current element in deque
sum=sum+d.back().first; //add it to sum
}
return *max_element(ans.begin(), ans.end()); //return maximum average of subarray
}
};
我试图解决 leetcode 问题 643 最大平均子数组 I ,这是一个基于滑动 window 方法的简单问题。
我写了代码并得到了运行时错误提示
“第 811 行:字符 16:运行时错误:引用绑定到 'double' 类型的空指针 (stl_iterator.h)
摘要:UndefinedBehaviorSanitizer:未定义行为 /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c"
有人可以帮忙吗?提前致谢。
错误在这里
return *max_element(ans.begin(), ans.end());
如果 ans
为空,则取消引用 ans.end()
。
问题 link - https://leetcode.com/problems/maximum-average-subarray-i/
class Solution
{
public:
double findMaxAverage(vector<int>& nums, int k)
{
deque<pair<int,int>> d; //deque since its a sliding window problem
vector<double> ans; //to return answer
double avg;
double sum=0;
int n=nums.size();
for(int i=0;i<n;i++)
{
if(!d.empty() && d.front().second<=(i-k)) //out of window size
{
avg=sum/k;
ans.push_back(avg); //push the average of k elements in answer vector
sum=sum-d.front().first; //remove the sum of first element when moving to next
d.pop_front(); //remove front element of deque
}
d.push_back(make_pair(nums[i],i)); //push current element in deque
sum=sum+d.back().first; //add it to sum
}
return *max_element(ans.begin(), ans.end()); //return maximum average of subarray
}
};
我试图解决 leetcode 问题 643 最大平均子数组 I ,这是一个基于滑动 window 方法的简单问题。
我写了代码并得到了运行时错误提示 “第 811 行:字符 16:运行时错误:引用绑定到 'double' 类型的空指针 (stl_iterator.h) 摘要:UndefinedBehaviorSanitizer:未定义行为 /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c"
有人可以帮忙吗?提前致谢。
错误在这里
return *max_element(ans.begin(), ans.end());
如果 ans
为空,则取消引用 ans.end()
。