Why can't I use ">=" instead of "=="?


  • 0
    L

    Why can't I use ">=" here? it gave me a runtime error when k=5000

     if(!dq.empty() && dq.back()+k>=i)
    

    My answer was accepted when I change it to

     if(!dq.empty() && dq.back()+k==i)
    

    The code is here:

    class Solution {
    public:
        vector<int> maxSlidingWindow(vector<int>& nums, int k) {
            deque<int> dq;
            vector<int> res;
            for(int i=0;i<nums.size();i++){
                while(!dq.empty() && nums[i]>nums[dq.front()]){
                    dq.pop_front();
                }
                dq.push_front(i);
                if(!dq.empty() && dq.back()+k==i){
                    dq.pop_back();
                }
        
                if(i>=(k-1)){
                    res.push_back(nums[dq.back()]);
                }
            }
            if((nums.size()<k-1)&&(k>0)){
                res.push_back(nums[dq.back()]);
            }
            return res;
        }
    };

  • 2

    Well think about what this does with >=:

            dq.push_front(i);
            if(!dq.empty() && dq.back()+k>=i){
                dq.pop_back();
            }
    

    You push i, and then you always pop it off right away. The dq isn't empty because you just pushed i, and i+k>=i is also always true (unless k<0 or overflow). And then you access nums[dq.back()] when dq is empty, which is rather dangerous.

    This makes no sense. Did you mean <= instead of >=?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.