一道来自腾讯基础架构部的笔试题

鹅厂的笔试题其实也会经常选择一些经典问题,比如这个题就是出自Cracking the code interview.

Q1.1: 打印一个文件的最后K行。

这个问题其实是比较简单的,如果用C实现,相对会比较棘手,但是借助于C++的容器vector,不需要考虑动态内存分配,思路其实是非常清晰的。

分析:常规思路下,一般会逆向推倒

一道来自腾讯基础架构部的笔试题_第1张图片

这里的核心问题转换为求总行数, 实现转换后的问题当然很简单,我们可以通过getline()来处理。

在循环累加行数的同时,需要把读得的内容推入容器存储,以便接下来打印输出。

源码(CodeBlocks+GNU GCC编译):

 1 /*
 2 The MIT License (MIT)
 3 
 4 Copyright (c) <2014> 
 5 
 6 Permission is hereby granted, free of charge, to any person obtaining a copy
 7 of this software and associated documentation files (the "Software"), to deal
 8 in the Software without restriction, including without limitation the rights
 9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12 
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15 
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 */
24 
25 #include 
26 #include 
27 #include 
28 using namespace std;
29 
30 /*
31  **@
32  **@ param in 输入文件流
33  **@ param k  Last K行
34 */
35 void printLastK(ifstream &fin, int k) {
36     vector<string> vctStr;
37     string strTmp;
38     while(getline(fin, strTmp)) {
39         vctStr.push_back(strTmp);
40     }
41     //注意边界判断
42     int lineCnt = vctStr.size();
43     if(lineCnt < k) {
44         int i;
45         for(i = 0; i < lineCnt; i++)
46         cout << vctStr[i] << endl;
47     } else {
48         int i;
49         for(i = lineCnt - k; i <= lineCnt - 1; i++) {
50             cout << vctStr[i] << endl;
51         }
52     }
53 }
54 
55 int main(){
56     ifstream fin("test.txt");
57     int k = 8;
58 
59     printLastK(fin, k);
60     fin.close();
61     return 0;
62 }

这里通过vector,用牺牲空间的方式来减小复杂度,当然还有一种方法是更省内存的。具体请见:http://www.hawstein.com/posts/13.1.html

转载于:https://www.cnblogs.com/openIoT/p/4092216.html

你可能感兴趣的:(操作系统,c/c++)