-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-157-Read-N-Characters-Given-Read4.java
83 lines (65 loc) · 2.26 KB
/
LeetCode-157-Read-N-Characters-Given-Read4.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Use read4() to implement read(), return the actual number read.
Becareful, it's possible that the actual number of elements in buf is < n
https://leetcode.com/discuss/85767/java-easy-version-to-understand
*/
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */
public class Solution extends Reader4 {
// 1.
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
// public int read(char[] buf, int n) {
// if(n <= 0) return 0;
// char[] tmp = new char[4];
// int j = 0;
// while(true){
// int readCount = read4(tmp); //put data from read4 into tmp
// // copy date from temp to buf
// for(int i = 0; i < readCount && j < n; j++, i++){
// buf[j] = tmp[i];
// }
// // readCount < 4 means file is all read. j==n means we have already get all we need from file.
// if(readCount < 4 || j == n){
// break;
// }
// }
// return j;
// }
// 2.
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
int total = 0;
char[] buf4 = new char[4];
while (total < n) {
int count = read4(buf4);
count = Math.min(count, n - total);
int k = 0;
while(total < n && k < count) buf[total++] = buf4[k++];
if (count < 4) break; // means we reached the EOF
}
return total;
}
// Another way
public int read(char[] buf, int n) {
int total = 0;
char[] buf4 = new char[4];
int len4 = read4(buf4);
while (len4 > 0) {
if (total >= n) break;
len4 = Math.min(len4, n - total);
int k = 0;
while(total < n && k < len4) buf[total++] = buf4[k++];
buf4 = new char[4];
len4 = read4(buf4);
}
return total;
}
}