C++ 84ms, priority_queue and break early if that whole line won't be applicable


  • 0
    Z

    // this is accepted, 84ms
    int kthSmallest(vector<vector<int>>& matrix, int k) {

        priority_queue<int> pq;
        
        for(int i = 0;i< matrix.size() && i<k;i++)
        {
            for(int j = 0;j< matrix[i].size() && j<k;j++)
            {
                if(pq.size()<k)
                {
                    pq.push(matrix[i][j]);
                }
                else
                {
                    if(pq.top()>matrix[i][j])
                    {
                        pq.pop();
                        pq.push(matrix[i][j]);
                    }
                    else
                    {
                        break; // this rest of this line won't be applicable.
                    }
                }
            }
        }
        
        return pq.top();
        
    }

Log in to reply
 

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