【LeetCode】157. Read N Characters Given Read4
阿新 • • 發佈:2018-12-13
Difficulty: Easy
More:【目錄】LeetCode Java實現
Description
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there
is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n
characters from the file.
Note: The read function will only be called once for each test case.
Intuition
題意:int read4(char[] buffer):該函式功能是讀取某個檔案,每次讀取最多4個字元到buffer中,同時返回讀取字元個數。要求利用read4()函式來實現read(char[] buf, int n)函式,總共讀取n個字元到buf中。
要求很容易實現,每次用read4()來讀取字元,用System.arraycopy(src, srcPos, dest, destPos, length)來複制陣列即可。關鍵要注意的是檔案的字元數小於n或者大於n的情況。
Solution
public int read(char[] buf,int n) { char[] buffer = new char[4]; int index=0; boolean endOfFile=false; while(index<n && !endOfFile) { int size=read4(buffer); if(size<4) endOfFile=true; int bytes=Math.min(size, n-index); System.arraycopy(buffer, 0, buf, index, bytes); index+=bytes; } return index; }
Complexity
Time complexity : O(n)
Space complexity : O(1)
What I've learned
1.
More:【目錄】LeetCode Java實現