C++ solution without redundant memory copy


  • 1
    C
    // Forward declaration of the read4 API.
    int read4(char *buf);
    
    class Solution {
    public:
        /**
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
         */
        int remain = 0;
        char buffer[4];
        int idx = 0;
        int read(char *buf, int n) {
            int count = 0;
            char *org_buf = buf;
            int i, j;
            for (i = idx, j = 0; j < remain && count < n; i++, j++)
            {
                if (i == 4)
                    i = 0;
                buf[j] = buffer[i];
                count++;
            }
            idx = i;
            remain -= count;
            buf += count;
            
            if (count == n) return n;
            
            while (count < n)
            {
                int r = read4(buf);
                count += r;
                buf += r;
                if (r < 4)
                    break;
            }
            int len = min(count, n);
            remain = max(count - len, 0);
            if (remain)
            {
                memcpy(buffer, org_buf+len, remain);
                idx = 0;
            }
            return len;
        }
    };

Log in to reply
 

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