一道来自腾讯基础架构部的笔试题
2020-07-14 05:45
429 查看
鹅厂的笔试题其实也会经常选择一些经典问题,比如这个题就是出自Cracking the code interview.
Q1.1: 打印一个文件的最后K行。
这个问题其实是比较简单的,如果用C实现,相对会比较棘手,但是借助于C++的容器vector,不需要考虑动态内存分配,思路其实是非常清晰的。
分析:常规思路下,一般会逆向推倒
这里的核心问题转换为求总行数, 实现转换后的问题当然很简单,我们可以通过getline()来处理。
在循环累加行数的同时,需要把读得的内容推入容器存储,以便接下来打印输出。
源码(CodeBlocks+GNU GCC编译):
1 /* 2 The MIT License (MIT) 3 4 Copyright (c) <2014> <oliver-lxtech2013@gmail.com> 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 <iostream> 26 #include <fstream> 27 #include <vector> 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
相关文章推荐
- 腾讯2014实习生基础研究方向笔试面试
- 腾讯-基础研究-实习岗 笔试
- 一道腾讯笔试题--Integer的比较
- 一道腾讯的笔试题,不使用任何判断语句求出两个数中的较大者(即 if、if...else...、>、<、==、while等语句)
- [笔试题目] 腾讯2015年9月基础研究笔试题
- C++ 一道基础笔试题
- 多个div并排显示的居中问题——来自腾讯的一道面试题
- [js高手之路]学生问的一道javascript面试题[来自腾讯]
- 指针与字符串操作-一道腾讯笔试题
- 数据结构基础(11)------------输出字符串的所有组合( Permutation)--腾讯笔试附加题
- 一道腾讯的笔试题
- 腾讯笔试题 1 算法基础-字符移位
- 一道笔试题,引发我的基础问题的反思
- 看博文《一道爱立信改自腾讯笔试题 》所想
- 腾讯笔试基础题
- 腾讯基础研究笔试题
- 腾讯实习生的一道笔试题
- 腾讯的笔试题一道
- 腾讯实习生【笔试--基础研究】
- 一道腾讯笔试题(已知一个数组,不使用除法构造另一数组)