【LeetCode】158. Read N Characters Given Read4 II - Call multiple times

Difficulty: Hard

 More:【目錄】LeetCode Java實現html

Description

Similar to Question [Read N Characters Given Read4], but the read function may be called multiple times.java

Intuition

題意:本題與上一題的區別就是連續屢次調用read()函數,因此須要將存儲4個字符的緩存buffer定義爲全局變量,此外全局變量還須要定義buffer[]中的開始下標和緩存長度。本題中,須要注意的是,調用完一次read()函數後,可能沒辦法把buffer所有讀完,因此要考慮到下一次調用read()函數時,對buffer的操做。詳見代碼。緩存

Solution

public class Solution extends Reader4 {
	private char[] buffer = new char[4];
	int offset = 0, bufsize = 0;  //buffer[]中的開始下標和緩存長度

	/**
	* @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) {
		int readBytes=0;  //已讀的字符個數
		boolean eof=false;
		while(readBytes<n && !eof) {
			if(bufsize==0) {  //buffer[]中沒有緩存了
				bufsize=read4(buffer);
				eof=(bufsize<4);  //不能放到外面!
			}
			int bytes=Math.min(bufsize, n-readBytes);
			System.arraycopy(buffer, offset, buf, readBytes, bytes);
			offset=(offset+bytes)%4;
			bufsize-=bytes;
			readBytes+=bytes;
		}
		return readBytes;
	}
}

  

What I've learned

1.函數

 

 More:【目錄】LeetCode Java實現post

相關文章
相關標籤/搜索