摘要:題目解答讀懂題目很重要,還是要多寫寫這種實(shí)際的的問題。實(shí)際文件讀到頭了的情況需要讀的文件個(gè)數(shù)達(dá)到了的情況
題目:
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.
解答:
讀懂題目很重要,還是要多寫寫這種實(shí)際的api的問題。
/* 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 */ public int read(char[] buf, int n) { boolean end = false; int total = 0; char[] temp = new char[4]; //有兩種情況:1. 需要read的character個(gè)數(shù)是n,但實(shí)際文件中character個(gè)數(shù)小于n個(gè),所以我們只能返回實(shí)際character的個(gè)數(shù);2. 需要read的character個(gè)數(shù)n小于實(shí)際文件中的個(gè)數(shù),所以最后一步只需要n - total個(gè)character就可以。 while (!end && total < n) { int count = read4(temp); //實(shí)際文件讀到頭了的情況 end = count < 4; //需要讀的文件個(gè)數(shù)達(dá)到了的情況 count = Math.min(count, n - total); for (int i = 0; i < count; i++) { buf[total++] = temp[i]; } } return total; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/64912.html
摘要:題目鏈接和那道不同的是這次,問題就是當(dāng)前的可能存在多讀了幾個(gè)字節(jié),那么下一次的時(shí)候要先算上上次多讀的部分,所以要保存上次讀的。和讀一次一樣有兩種要考慮的讀完了沒讀完,但是裝滿了 158. Read N Characters Given Read4 II - Call multiple times 題目鏈接:https://leetcode.com/problems... 和那道read...
摘要:臨時(shí)數(shù)組法復(fù)雜度時(shí)間空間思路用一個(gè)臨時(shí)數(shù)組,存放每次讀到字符,再用一個(gè)指針標(biāo)記數(shù)組目前存儲(chǔ)到的位置,然后將這個(gè)臨時(shí)數(shù)組的內(nèi)容存到相應(yīng)的位置就行了。 Read N Characters Given Read4 I The API: int read4(char *buf) reads 4 characters at a time from a file. The return valu...
Problem 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 i...
摘要:一題目描述空格分隔,逐個(gè)反轉(zhuǎn)二題目描述三題目描述當(dāng)然也可以用的做,不過用雙指針更快。 LeetCode: 557. Reverse Words in a String III 一、LeetCode: 557. Reverse Words in a String III 題目描述 Given a string, you need to reverse the order of chara...
摘要:最新更新思路和其他語言請(qǐng)?jiān)L問哈希表法復(fù)雜度時(shí)間空間思路用一個(gè)哈希表記錄字符串中字母到字符串中字母的映射關(guān)系,一個(gè)集合記錄已經(jīng)映射過的字母?;蛘哂脙蓚€(gè)哈希表記錄雙向的映射關(guān)系。這里不能只用一個(gè)哈希表,因?yàn)橐懦@種多對(duì)一的映射。 Isomorphic Strings 最新更新思路和其他語言請(qǐng)?jiān)L問:https://yanjia.me/zh/2018/11/... Given two st...
閱讀 858·2021-11-25 09:43
閱讀 3690·2021-11-19 09:40
閱讀 894·2021-09-29 09:34
閱讀 1808·2021-09-26 10:21
閱讀 885·2021-09-22 15:24
閱讀 4205·2021-09-22 15:08
閱讀 3281·2021-09-07 09:58
閱讀 2699·2019-08-30 15:55