C++ 0ms 8 lines solution using queue to store extra chars


  • 2
    int read4(char *buf);
    
    class Solution {
    private:
        queue<char> q;
    
    public:
        int read(char *buf, int n) {
            int cnt = 0;
            
            for (; n && q.size(); n--) { buf[cnt++] = q.front(); q.pop(); }    // read out chars in q first
            
            for (int k = 4; n > 0 && k == 4; cnt += min(k, n), n -= k) {
                k = read4(buf + cnt);                                           // read the rest from file
                for (int i = 0; i < k - n; i++) { q.push(buf[cnt + n + i]); }   // save extra chars in q
            }
            
            return cnt;
        }
    };
    

Log in to reply
 

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