ac solution code


  • 0
        /*
         Solution1. time = O(n); space = O(1)     
         Append read bits by `read4` to buffer in while loop until meets buffer end or n length limit
         `read4`: read 4 bits from buffer easy time. This question is to use `read4` to read from buffer.
         */
        func read(_ buff: inout [Character], _ n: Int) -> Int {
            var count = 0, buffPointer = 0, buffCount = 0 // count: total count; buffPointer: pointer in oneBuffer; buffCount: count in oneBuffer
            
            while count  < n {
                var oneBuff = [Character]()
                if buffPointer == 0 {
                    buffCount = read4(&oneBuff)
                }
                
                if buffCount == 0 {break} // End of file
                while count < n && buffPointer < buffCount {
                    buff.append(oneBuff[buffPointer])
                    buffPointer += 1
                    count += 1
                }
                if buffPointer >= buffCount {// Don't reach `n` length limit, reset `buffPointer` to keep reading
                    buffPointer = 0
                }
            }
            return count
        }
    

Log in to reply
 

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