Algorithm Notes
  • Introduction
  • Search & Backtracking 搜索与回溯
    • Tree 与 BackTracking 的比较
    • Subsets, Combination 与 Permutation
    • Subsets & Combinations & Combination Sum
    • 枚举法
    • N 皇后 + 矩阵 Index Trick
    • Sudoku 数独 + 矩阵 Index Trick
    • Word Ladder I & II
    • Number of ways 类
    • DFS flood filling
    • Strobogrammatic 数生成
    • String 构造式 DFS + Backtracking
    • Word Pattern I & II
    • (G) Binary Watch
    • (FB) Phone Letter Combination
    • 常见搜索问题的迭代解法
  • String,字符串类
    • 多步翻转法
    • Substring 结构和遍历
    • Palindrome 问题
    • Palindrome Continued
    • String / LinkedList 大数运算
    • 序列化与压缩
    • 5/24 String 杂题
    • Knuth–Morris–Pratt 字符串匹配
    • Lempel–Ziv–Welch 字符串压缩算法
    • (G) Decode String
    • (G) UTF-8 Validation
  • Binary Tree,二叉树
    • 各种 Binary Tree 定义
    • LCA 类问题
    • 三序遍历,vertical order
    • Post order traversal 的应用
    • Min/Max/Balanced Depth
    • BST
    • 子树结构
    • Level Order traversal
    • Morris 遍历
    • 修改结构
    • 创建 / 序列化
    • 子树组合,BST query
    • 路径与路径和
    • NestedInteger 类
    • (FB) 从 Binary Tree Path 看如何递归转迭代
    • (FB) Binary Tree Path 比较路径大小
    • 比较好玩的 Binary Tree 概率题
  • Segment & Fenwick Tree,区间树
    • Segment Tree 基础操作
    • Segment Tree 的应用
    • Fenwick Tree (Binary Indexed Tree)
    • Range Sum Query 2D - Immutable
  • Union-Find,并查集
    • Union-Find,并查集基础
    • Union-Find, 并查集应用
  • Dynamic Programming, 动态规划
    • 6/20, 入门 House Robber
    • 7/12, Paint Fence / House
    • 6/24, 滚动数组
    • 6/24, 记忆化搜索
    • 6/24, 博弈类 DP
    • 博弈类DP, Flip Game
    • 6/25, 区间类DP
    • 6/27, subarray 划分类,股票
    • 7/2, 字符串类
    • Bomb Enemies
    • 8/2,背包问题
    • (G) Max Vacation
    • (11/4新增) AST 子树结构 DP
  • LinkedList,链表
    • 6/9, LinkedList,反转与删除
    • 6/11, LinkedList 杂题
    • (FB) 链表的递归与倒序打印
  • LinkedIn 面经,算法题
    • 6/17, LinkedIn 面经题
    • 6/28, LinkedIn 面经题
    • 7/6, LinkedIn 面经
    • Shortest Word Distance 类
    • DFA Parse Integer
  • Two Pointers,双指针
    • 3 Sum, 3 Sum Closest / Smaller, 4 Sum
    • 对撞型,灌水类
    • 对撞型,partition类
    • Wiggle Sort I & II
    • 双指针,窗口类
    • 双指针,窗口类
    • Heap,排序 matrix 中的 two pointers
  • Bit & Math,位运算与数学
    • Bit Manipulation,对于 '1' 位的操作
    • Math & Bit Manipulation, Power of X
    • 坐标系 & 数值计算类
    • Add Digits
    • 用 int 做字符串 signature
  • Interval 与 扫描线
    • Range Addition & LCS
    • 7/5, Interval 类,扫描线
  • Trie,字典树
    • 6/9, Trie, 字典树
  • 单调栈,LIS
    • 4/13 LIS
    • 栈, 单调栈
    • Largest Divisible Subset
  • Binary Search 类
    • Matrix Binary Search
    • Array Binary Search
    • Find Peak Element I & II
    • **Median of Two Sorted Arrays
  • Graph & Topological Sort,图 & 拓扑排序
    • 有向 / 无向 图的基本性质和操作
    • 拓扑排序, DFS 做法
    • 拓扑排序, BFS 做法
    • Course Schedule I & II
    • Alien Dictionary
    • Undirected Graph, BFS
    • Undirected Graph, DFS
    • 矩阵,BFS 最短距离探索
    • 欧拉回路,Hierholzer算法
    • AI, 迷宫生成
    • AI, 迷宫寻路算法
    • (G) Deep Copy 无向图成有向图
  • 括号与数学表达式的计算
  • Iterator 类
  • Majority Element,Moore's Voting
  • Matrix Inplace Operations
  • 常见数据结构设计
  • (G) Design / OOD 类算法题
  • 随机算法 & 数据结构
  • (FB) I/O Buffer
  • (FB) Simplify Path, H-Index I & II
  • (FB) Excel Sheet, Remove Duplicates
  • Integer 的构造,操作,序列化
  • Frequency 类问题
  • Missing Number 类,元素交换,数组环形跳转
  • 8/10, Google Tag
  • (FB) Rearrange String k Distance Apart
  • Abstract Algebra
    • Chap1 -- Why Abstract Algebra ?
    • Chap2 -- Operations
    • Chap3 -- The Definition of Groups
Powered by GitBook
On this page
  • Read N Characters Given Read4
  • 主要的注意点就是,有的时候 read4 是短板,有的时候 readN 自己是短板(不需要4个那么多的字符),在写入的时候要注意处理下。
  • Read N Characters Given Read4 II - Call multiple times
  • 多次调用之后,这题的难点就变成了 “如何处理剩余字符”。因为一次 call 拿到的字符很可能超过我们实际需要的,这时候就需要依赖外部 buffer 记录下来,每次新 read() call 的时候,先从缓存里拿。
  • 这个写法就巧妙简洁多了,而且原封不动就可以做原来的问题,非常巧妙。

Was this helpful?

(FB) I/O Buffer

Previous随机算法 & 数据结构Next(FB) Simplify Path, H-Index I & II

Last updated 4 years ago

Was this helpful?

这题的 API 和题目描述都有点模糊,重新理一下:

  • int read4(char[] buf)

  • 你扔一个 char[] 过去,函数写入最多 4 个 char 在上面,然后返回写入 char 的长度; 到文件末尾的时候返回 char 长度会小于 4.

  • 于是我们的目标是把最终长度为 n 的字符串写入自己函数的 read(char[] buf) 里,然后返回实际长度。

主要的注意点就是,有的时候 read4 是短板,有的时候 readN 自己是短板(不需要4个那么多的字符),在写入的时候要注意处理下。

    public int read(char[] buf, int n) {
        // file has less than n chars
        // n is not divisible by 4

        boolean EOF = false;
        char[] temp = new char[4];
        int curPtr = 0;

        while(curPtr < n && !EOF){
            int charCount = read4(temp);
            EOF = (charCount < 4);

            for(int i = 0; i < charCount && curPtr < n; i++){
                buf[curPtr++] = temp[i];
            }
        }

        return curPtr;
    }

多次调用之后,这题的难点就变成了 “如何处理剩余字符”。因为一次 call 拿到的字符很可能超过我们实际需要的,这时候就需要依赖外部 buffer 记录下来,每次新 read() call 的时候,先从缓存里拿。

两次 AC,但是这个代码的简洁性实在不忍直视。。。待我好好改改。。

public class Solution extends Reader4 {
    char[] leftOver = new char[4];
    int leftCount = 0;
    int leftPtr = 0;
    /**
     * @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 totalLen = 0; // always points to next pos to be filled
        boolean EOF = false;
        char[] temp = new char[4];
        while(!EOF && totalLen < n){
            while(leftCount > 0 && totalLen < n){
                buf[totalLen++] = leftOver[leftPtr++];
                leftCount--;
            }

            if(totalLen < n){
                int newLen = read4(temp);
                EOF = newLen < 4;

                if(totalLen + newLen <= n){
                    // did not exceed 
                    for(int i = 0; i < newLen; i++) buf[totalLen++] = temp[i];

                } else {
                    // points to next extra char
                    int ptr = 0;
                    // write needed char into buffer
                    while(totalLen < n) buf[totalLen++] = temp[ptr++];
                    // write extra char into leftover
                    int size = newLen - ptr;
                    for(int i = 0; i < size; i++){
                        leftOver[i] = temp[ptr++];
                        leftCount = i + 1;
                    }
                    leftPtr = 0;
                }
            }
        }

        return totalLen;
    }
}

这个写法就巧妙简洁多了,而且原封不动就可以做原来的问题,非常巧妙。

  • 我们只用一个 buffer,大小为 4. 因为一次读取的字符数量不会超过 4,而且每次 read() 之后剩余的字符数量也不会超过 4.

  • 因此这一个全局 buffer,就代表了我们全部的可用字符,一个 int 存数量,一个 int 存起点。

  • 需要写入 buffer 的时候就写,如果没有了,就向 read4 要,到时候 ptr 会自动记录下一轮的起始位置和剩余字符串数量。

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */

    char[] temp = new char[4];
    int bufPtr = 0;
    int bufCount = 0;
    int bufEnd = 0;

    public int read(char[] buf, int n) {
        int curPtr = 0;
        while(curPtr < n){
            if(bufCount == 0){
                bufCount = read4(temp);
                bufEnd = bufCount;
                bufPtr = 0;
            }
            if(bufCount == 0) break;

            while(bufPtr < bufEnd && curPtr < n){
                buf[curPtr++] = temp[bufPtr++];
                bufCount --;
            }
        }
        return curPtr;
    }
}

Read N Characters Given Read4
Read N Characters Given Read4 II - Call multiple times