2026年程序员代码面试题及算法测试_第1页
2026年程序员代码面试题及算法测试_第2页
2026年程序员代码面试题及算法测试_第3页
2026年程序员代码面试题及算法测试_第4页
2026年程序员代码面试题及算法测试_第5页
已阅读5页,还剩25页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

2026年程序员代码面试题及算法测试一、编程语言基础(5题,每题10分,共50分)1.题目:请用Java实现一个方法,判断一个字符串是否是有效的括号组合。例如,输入`"()[]{}"`应返回`true`,输入`"(]"`应返回`false`。要求不使用额外的数据结构,时间复杂度尽可能低。2.题目:用Python编写一个函数,接收一个列表,返回一个新列表,其中包含原列表中所有不重复的元素,保持原顺序。例如,输入`[1,2,1,3,2]`,输出`[1,2,3]`。3.题目:请用C++实现一个函数,将一个罗马数字转换为整数。例如,输入`"III"`返回`3`,输入`"IV"`返回`4`,输入`"MCMXCIV"`返回`1994`。4.题目:用JavaScript编写一个闭包函数,实现一个计数器,每次调用时返回当前计数值并自增。例如:javascriptconstcounter=createCounter();console.log(counter());//1console.log(counter());//25.题目:请用Go语言实现一个简单的LRU(最近最少使用)缓存,支持`Get`和`Put`操作。缓存容量为3,例如:golru:=NewLRUCache(3)lru.Put(1,1)lru.Put(2,2)lru.Get(1)//返回1lru.Put(3,3)//原有2被淘汰lru.Get(2)//返回-1(未找到)二、算法与数据结构(8题,每题15分,共120分)6.题目:给定一个非负整数数组`nums`,返回一个数组`answer`,其中`answer[i]`等于`nums`中比`nums[i]`小的元素个数。例如,输入`[4,5,2,2,1]`,输出`[0,1,0,0,0]`。7.题目:请用Java实现快速排序算法,并分析其时间复杂度。输入一个整数数组,原地排序。8.题目:用Python实现二叉树的前序遍历(递归和迭代两种方式)。给定一棵二叉树:1/\23/\45前序遍历结果为`[1,2,4,5,3]`。9.题目:请用C++实现一个算法,检查一个字符串是否是回文串(忽略大小写和非字母字符)。例如,输入`"Aman,aplan,acanal:Panama"`应返回`true`。10.题目:用JavaScript实现一个深度优先搜索(DFS)算法,给定一个无向图(用邻接表表示),返回从起点到终点的所有路径。例如:javascriptconstgraph={1:[2,3],2:[1,4],3:[1],4:[2]};console.log(findAllPaths(graph,1,4));//[[1,2,4],[1,3]]11.题目:请用Go语言实现一个最小堆(MinHeap),支持`Push`和`Pop`操作。输入一系列整数,用堆排序输出有序数组。12.题目:用Java实现一个算法,找到链表的中间节点。例如,输入`1->2->3->4->5`,返回`3`。13.题目:用Python实现一个动态规划算法,计算斐波那契数列的第n项。优化时间复杂度至O(logn)。三、系统设计(5题,每题20分,共100分)14.题目:设计一个简单的消息队列系统,支持生产者-消费者模式。要求:-支持持久化消息(本地文件或数据库)。-支持至少1000个并发连接。-提供至少两种消息确认机制(如PUB/SUB)。15.题目:设计一个短链接服务(如TinyURL),要求:-输入任意长URL,输出固定长度短链接。-支持自定义短链接前缀。-支持点击统计和过期功能。16.题目:设计一个分布式限流系统,要求:-支持全局限流(如每秒1000个请求)。-支持分区分组限流。-高可用,支持Redis或Etcd。17.题目:设计一个实时推荐系统,输入用户行为日志(如点击、购买),输出个性化推荐列表。要求:-支持100万级用户。-推荐延迟小于500ms。-支持冷启动和热门商品优先。18.题目:设计一个分布式文件存储系统(类似HDFS),要求:-支持分片存储和自动容错。-支持多副本同步。-支持元数据索引和查询。答案与解析一、编程语言基础1.Java括号判断:javapublicbooleanisValidParentheses(Strings){if(s==null||s.length()%2!=0)returnfalse;Map<Character,Character>map=newHashMap<>();map.put(')','(');map.put('}','{');map.put(']','[');Stack<Character>stack=newStack<>();for(charc:s.toCharArray()){if(map.containsKey(c)){if(stack.isEmpty()||stack.pop()!=map.get(c))returnfalse;}else{stack.push(c);}}returnstack.isEmpty();}解析:-使用栈结构匹配括号,时间复杂度O(n),空间复杂度O(n)。-先用哈希表映射闭括号到开括号,简化匹配逻辑。2.Python去重保持顺序:pythondefunique_elements(lst):seen=set()result=[]foriteminlst:ifitemnotinseen:seen.add(item)result.append(item)returnresult解析:-使用集合记录已见元素,列表存储结果,保持遍历顺序。3.C++罗马数字转整数:cppintromanToInt(strings){unordered_map<char,int>values={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};inttotal=0,prev=0;for(inti=s.size()-1;i>=0;--i){intval=values[s[i]];if(val<prev)total-=val;elsetotal+=val;prev=val;}returntotal;}解析:-逆向遍历,遇到小值前缀则减去,否则累加。4.JavaScript计数器闭包:javascriptfunctioncreateCounter(){letcount=0;returnfunction(){return++count;};}解析:-闭包捕获`count`变量,每次调用自增。5.GoLRU缓存:gotypeLRUCachestruct{capacityintcachemap[int]intorder[]int}funcConstructor(capacityint)LRUCache{returnLRUCache{capacity:capacity,cache:make(map[int]int),order:make([]int,0)}}func(thisLRUCache)Get(keyint)int{ifval,ok:=this.cache[key];ok{this.order=append(this.order,key)this.order=remove(this.order,key)returnval}return-1}func(thisLRUCache)Put(keyint,valueint){if_,ok:=this.cache[key];ok{this.order=append(this.order,key)this.order=remove(this.order,key)}elseiflen(this.cache)==this.capacity{oldest:=this.order[0]delete(this.cache,oldest)this.order=this.order[1:]}this.cache[key]=valuethis.order=append(this.order,key)}funcremove(arr[]int,keyint)[]int{fori,v:=rangearr{ifv==key{returnappend(arr[:i],arr[i+1:]...)}}returnarr}解析:-使用`order`数组维护访问顺序,淘汰最久未使用项。二、算法与数据结构6.数组中比当前小的元素个数:pythondefsmallerNumbersThanCurrent(nums):sorted_nums=sorted(nums)rank={val:ifori,valinenumerate(sorted_nums)}return[rank[num]fornuminnums]解析:-先排序并记录排名,时间复杂度O(nlogn)。7.Java快速排序:javapublicvoidquickSort(int[]nums,intleft,intright){if(left>=right)return;intpivot=partition(nums,left,right);quickSort(nums,left,pivot-1);quickSort(nums,pivot+1,right);}intpartition(int[]nums,intleft,intright){intpivot=nums[right];inti=left-1;for(intj=left;j<right;j++){if(nums[j]<=pivot){i++;swap(nums,i,j);}}swap(nums,i+1,right);returni+1;}解析:-分治法,平均时间O(nlogn),最坏O(n²)。8.二叉树前序遍历:python递归defpreorder_recursive(root):ifnotroot:return[]return[root.val]+preorder_recursive(root.left)+preorder_recursive(root.right)迭代defpreorder_iterative(root):ifnotroot:return[]stack,result=[root],[]whilestack:node=stack.pop()result.append(node.val)ifnode.right:stack.append(node.right)ifnode.left:stack.append(node.left)returnresult解析:-递归天然符合前序,迭代需调整栈顺序。9.回文串判断:cppboolisPalindrome(strings){stringfiltered="";for(charc:s){if(isalnum(c)){filtered+=tolower(c);}}intleft=0,right=filtered.size()-1;while(left<right){if(filtered[left]!=filtered[right])returnfalse;left++,right--;}returntrue;}解析:-过滤非字母数字后双指针对称比较。10.图的DFS路径:javascriptfunctionfindAllPaths(graph,start,end){constpaths=[];constcurrentPath=[];functiondfs(node){currentPath.push(node);if(node===end){paths.push([...currentPath]);}else{for(constneighborofgraph[node]){dfs(neighbor);}}currentPath.pop();}dfs(start);returnpaths;}解析:-递归回溯,收集所有从start到end的路径。11.Go最小堆实现:gotypeMinHeap[]intfunc(hMinHeap)Len()int{returnlen(h)}func(hMinHeap)Less(i,jint)bool{returnh[i]<h[j]}func(hMinHeap)Swap(i,jint){h[i],h[j]=h[j],h[i]}func(hMinHeap)Push(xinterface{}){h=append(h,x.(int))}func(hMinHeap)Pop()interface{}{old:=hn:=len(old)item:=old[n-1]h=old[0:n-1]returnitem}解析:-使用`container/heap`包实现堆操作。12.链表中间节点:javapublicListNodemiddleNode(ListNodehead){ListNodeslow=head,fast=head;while(fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;}returnslow;}解析:-快慢指针,快指针走两步,慢指针走一步。13.斐波那契数列O(logn):pythondeffib(n):ifn==0:return0a,b=0,1forbitinbin(n)[2:]:a,b=aa+bb,2abifbit=='1':a,b=aa+bb,2abreturna解析:-使用矩阵快速幂加速计算。三、系统设计14.消息队列设计:go//核心接口typeMessagestruct{TopicstringPayload[]byte}typeProducerinterface{Publish(topicstring,msgMessage)}typeConsumerinterface{Subscribe(topicstring)(<-chanMessage,error)}//实现示例typeRedisMQstruct{pubSubredis.PubSub}func(mRedisMQ)Publish(topicstring,msgMessage){m.pubSub.Publish(topic,msg.Payload)}func(mRedisMQ)Subscribe(topicstring)(<-chanMessage,error){ch:=make(chanMessage)gofunc(){formsg:=rangem.pubSub.SubscribeTopic(topic){ch<-Message{Topic:topic,Payload:msg.Payload}}}()returnch,nil}解析:-基于Redis实现PUB/SUB,支持持久化。15.短链接设计:pythonimportbase64importhashlibclassShortener:def__init__(self):self.base_url="http://short.ly/"self.chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"defencode(self,num):encoded=""whilenum>0:encoded=self.chars[num%62]+encodednum//=62returnencoded.zfill(6)defshorten(self,long_url):hash_obj=hashlib.sha256(long_url.encode())num=int.from_bytes(hash_obj.digest()[:8],byteorder='big')short_code=self.encode(num)returnf"{self.base_url}{short_code}"示例shortener=Shortener()print(shortener.shorten(""))解析:-使用62进制编码哈希值,生成6位短码。16.分布式限流:gotypeRateLimiterstruct{bucketsmap[string]Bucketlocksync.Mutex}typeBucketstruct{capacityinttokensintlastRefilltime.Time}funcNewRateLimiter(capacityint,refillRateint)RateLimiter{return&RateLimiter{buckets:make(map[string]Bucket),lock:sync.Mutex{},}}func(rRateLimiter)Allow(keystring)bool{r.lock.Lock()deferr.lock.Unlock()bucket,exists:=r.buckets[key]if!exists{bucket=&Bucket{capacity:capacity,tokens:capacity,lastRefill:time.Now()}r.buckets[key]=bucket}now:=time.Now()refillTokens:=int(now.Sub(bucket.lastRefill).Seconds()float64(refillRate))bucket.tokens=min(bucket.capacity,bucket.tokens+refillTokens)bucket.lastRefill=nowifbucket.tokens>0{bucket.tokens--returntrue}returnfalse}解析:-使用漏桶算法,支持动态调整。17.实时推荐系统:go//核心逻辑typeRecommenderstruct{userItemsmap[string][]ItemitemScoresmap[string]float64}func(rRecommender)ProcessEvent(userstring,itemstring,actionstring){//更新用户行为r.userItems[user]=append(r.userItems[user],Item{Item:item,Action:action})//实时更新评分r.updateScores(user,item,action)}func(rRecommender)updateScores(userstring,itemstring,actionstring){//简化:根据action更新评分ifaction=="click"{r.itemScores[item]+=1.0}}func(rRecommender)Recommend(userstring)[]string{//基于评分排序推荐ifitems,ok:=r.userItems[user];ok{scores:=make(map[st

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论