2026年程序员面试题及答案参考.docxVIP

  • 1
  • 0
  • 约6.41千字
  • 约 18页
  • 2026-02-12 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年程序员面试题及答案参考

一、编程语言基础(3题,每题10分,共30分)

1.题目:

请用Python实现一个函数,输入一个正整数n,返回其二进制表示中1的个数。例如,输入7(二进制为111),返回3。

答案:

python

defcount_bits(n):

returnbin(n).count(1)

解析:

Python的`bin()`函数可以将整数转换为二进制字符串,如`bin(7)`返回`0b111`。`count(1)`统计字符串中1的个数,结果为3。此方法简洁高效。

2.题目:

请用Java实现一个方法,判断一个字符串是否为有效的括号组合,如`()[]{}`为有效,`(]`为无效。

答案:

java

importjava.util.Stack;

publicclassParenthesesValidator{

publicstaticbooleanisValid(Strings){

StackCharacterstack=newStack();

for(charc:s.toCharArray()){

if(c==(||c==[||c=={){

stack.push(c);

}elseif(c==)stack.isEmpty()||c==]stack.peek()!=[||c==}stack.peek()!={){

returnfalse;

}else{

stack.pop();

}

}

returnstack.isEmpty();

}

}

解析:

使用栈结构,遇到左括号入栈,遇到右括号时检查栈顶是否匹配。若栈为空或栈顶不匹配,则返回false。最终栈为空则有效。

3.题目:

请用C++实现快速排序算法,输入一个整数数组,返回排序后的数组。

答案:

cpp

includevector

usingnamespacestd;

voidquickSort(vectorintarr,intleft,intright){

if(left=right)return;

intpivot=arr[left],l=left,r=right;

while(lr){

while(lrarr[r]=pivot)r--;

arr[l]=arr[r];

while(lrarr[l]=pivot)l++;

arr[r]=arr[l];

}

arr[l]=pivot;

quickSort(arr,left,l-1);

quickSort(arr,l+1,right);

}

vectorintsortArray(vectorintnums){

quickSort(nums,0,nums.size()-1);

returnnums;

}

解析:

快速排序通过分治思想实现,选择基准值(pivot),将数组分为两部分,分别排序。时间复杂度为O(nlogn),空间复杂度为O(logn)。

二、数据结构与算法(5题,每题10分,共50分)

1.题目:

请用Java实现一个LRU(最近最少使用)缓存,支持get和put操作,容量为3。例如:

-put(1,1)→缓存为{1=1}

-get(1)→返回1

-put(2,2)→缓存为{1=1,2=2}

-put(3,3)→缓存为{1=1,2=2,3=3}

-get(1)→返回1

-put(4,4)→需要淘汰1,缓存为{2=2,3=3,4=4}

答案:

java

importjava.util.HashMap;

importjava.util.Map;

classLRUCache{

privateMapInteger,Integercache;

privateintcapacity;

publicLRUCache(intcapacity){

this.capacity=capacity;

cache=newHashMap();

}

publicintget(intkey){

if(!cache.containsKey(key))return-1;

intvalue=cache.get(key);

cache.remove(key);

cache.put(key,value);

returnvalue;

}

publicvoidput(intkey,intvalue){

if(cache.

文档评论(0)

1亿VIP精品文档

相关文档