Sunday, November 29, 2015

[leetcode]Read N Characters Given Read4 II - Call multiple times

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    List<Character> last = new LinkedList<Character>();
    public int read(char[] buf, int n) {
        int total = 0;
        int fromFour = 4;
        char temp[] = new char[4];
        while (total < n && fromFour == 4){
            fromFour = read4(temp);
            for (int i = 0; i < fromFour; i++){
                last.add(temp[i]);
            }
            total+= fromFour;
        }
        int size = last.size();
        for (int i = 0; i < n && i < size; i++, count++){
            buf[i] = last.remove(0);
        }
        return Math.min(n, size);
    }
}

No comments:

Post a Comment