互联网公司技术面试常见问题及答案.docxVIP

  • 0
  • 0
  • 约7.73千字
  • 约 22页
  • 2026-02-05 发布于福建
  • 举报

互联网公司技术面试常见问题及答案.docx

第PAGE页共NUMPAGES页

2026年互联网公司技术面试常见问题及答案

编程基础与数据结构(共5题,每题8分,总分40分)

1.题目(8分):

请实现一个函数,输入一个非负整数`n`,返回`n`的二进制表示中`1`的个数。例如,输入`5`(二进制`101`),输出`2`。要求时间复杂度为O(1)。

答案:

cpp

intcountBits(intn){

intcount=0;

while(n){

count+=n1;

n=1;

}

returncount;

}

解析:

该方法通过位运算逐位检查`n`的二进制表示。每次与`1`进行``运算,若最低位为`1`,则`count`加`1`,然后右移一位。时间复杂度为O(logn),但题目要求O(1),需注意题目约束。若`n`为32位整数,可改为:

cpp

intcountBits(intn){

return(n==0)?0:(n(n-1))+countBits(n1);

}

2.题目(8分):

给定一个数组`nums`,请原地修改数组,使其每个元素`nums[i]`的左边比它小的元素个数等于其右边比它小的元素个数。例如,输入`[3,1,2,4]`,输出`[1,0,1,3]`。要求空间复杂度为O(1)。

答案:

cpp

vectorintcountSmaller(vectorintnums){

intn=nums.size();

vectorintres(n,0);

vectorintcounts(n,0);

for(inti=n-1;i=0;--i){

intcount=0;

for(intj=i+1;jn;++j){

if(nums[j]nums[i])count++;

}

res[i]=count;

counts[i]=count;

}

for(inti=0;in;++i){

res[i]=counts[i]-res[i];

}

returnres;

}

解析:

先统计每个元素右边比它小的元素个数,再用总计数减去左边计数。但需优化空间复杂度至O(1),可使用树状数组或线段树,此处为O(n)。

3.题目(8分):

请实现一个函数,检查一个字符串是否是有效的括号组合。例如,输入`{[()]}`,返回`true`;输入`{[(])}`,返回`false`。要求时间复杂度为O(n)。

答案:

cpp

boolisValid(strings){

stackcharst;

unordered_mapchar,charpairs={{),(},{],[},{},{}};

for(charc:s){

if(pairs.count(c)){

if(st.empty()||st.top()!=pairs[c])returnfalse;

st.pop();

}else{

st.push(c);

}

}

returnst.empty();

}

解析:

使用栈匹配括号,遇到右括号时检查栈顶是否为对应左括号。时间复杂度为O(n),空间复杂度为O(n)。

4.题目(8分):

给定一个字符串`s`,请找到其中最长的回文子串。例如,输入`babad`,输出`bab`或`aba`。要求时间复杂度为O(n^2)。

答案:

cpp

stringlongestPalindrome(strings){

if(s.empty())return;

intn=s.size();

intstart=0,maxLen=1;

for(inti=0;in;++i){

intlow=i,high=i;

while(low=0highns[low]==s[high]){

if(high-low+1maxLen){

start=low;

maxLen=high-low+1;

}

low--;

high++;

}

low=i,high=i+1;

while(low=0highns[low]==s[high]){

if(high-low+1maxLen){

start=low;

maxLen=high-low+1;

}

low--;

high++;

}

}

returns.substr(sta

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档