携程技术部面试题及答案详解.docxVIP

  • 0
  • 0
  • 约6.07千字
  • 约 17页
  • 2026-01-27 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年携程技术部面试题及答案详解

一、编程能力测试(共5题,每题20分,总分100分)

1.题目:

实现一个函数,输入一个正整数`n`,返回`n`的阶乘。要求使用递归方式实现,并考虑大数问题(即结果可能超出JavaScript中`Number`类型的范围)。

答案:

javascript

functionfactorial(n){

if(n===0||n===1)return1;

returnBigInt(n)factorial(n-1);

}

解析:

-使用递归实现阶乘是最直观的方式,但需要注意递归深度和数值范围。

-JavaScript中`Number`类型最大支持`2^53-1`,超出此范围会溢出。因此,使用`BigInt`类型来存储大数结果。

-递归的终止条件是`n===0`或`n===1`,返回1。

-每次递归将`n`与`n-1`的阶乘相乘,并使用`BigInt`确保不溢出。

2.题目:

给定一个字符串`s`,返回其中最长的回文子串的长度。例如,输入`babad`,输出`3`(bab或aba)。

答案:

javascript

functionlongestPalindrome(s){

if(!s||s.length===0)return0;

letstart=0,end=0;

for(leti=0;is.length;i++){

constlen1=expandAroundCenter(s,i,i);//奇数长度回文

constlen2=expandAroundCenter(s,i,i+1);//偶数长度回文

constmaxLen=Math.max(len1,len2);

if(maxLenend-start){

start=i-Math.floor((maxLen-1)/2);

end=i+Math.floor(maxLen/2);

}

}

returnend-start+1;

}

functionexpandAroundCenter(s,left,right){

while(left=0rights.lengths[left]===s[right]){

left--;

right++;

}

returnright-left-1;

}

解析:

-使用“中心扩展法”解决,即遍历每个字符作为回文中心,向两边扩展。

-对于每个中心,分别尝试奇数长度和偶数长度的回文。

-记录最长回文的起始和结束位置,最后计算长度。

-时间复杂度:O(n2),空间复杂度:O(1)。

3.题目:

实现一个LRU(LeastRecentlyUsed)缓存,支持`get`和`put`操作。缓存容量为`capacity`。例如:

javascript

constlru=newLRUCache(2);

lru.put(1,1);//缓存是{1=1}

lru.put(2,2);//缓存是{1=1,2=2}

lru.get(1);//返回1

lru.put(3,3);//去除键2,缓存是{1=1,3=3}

lru.get(2);//返回-1(未找到)

答案:

javascript

classLRUCache{

constructor(capacity){

this.capacity=capacity;

this.map=newMap();

}

get(key){

if(!this.map.has(key))return-1;

constvalue=this.map.get(key);

this.map.delete(key);

this.map.set(key,value);

returnvalue;

}

put(key,value){

if(this.map.has(key)){

this.map.delete(key);

}elseif(this.map.size=this.capacity){

this.map.delete(this.map.keys().next().value);

}

this.map.set(key,value);

}

}

解析:

-使用`Map`实现LRU缓存,`Map`自带删除最久未使用元素的功能(按插入顺序维护键值对)。

-`get`操作:若存在键,则将其移到`Map`末尾(表示

文档评论(0)

1亿VIP精品文档

相关文档