百度技术大牛面试攻略及答案.docxVIP

  • 0
  • 0
  • 约6.33千字
  • 约 18页
  • 2026-01-28 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年百度技术大牛面试攻略及答案

一、编程与算法(5题,每题20分,共100分)

题目1(20分):

给定一个非空字符串`s`,其中包含大写字母、小写字母和数字,请编写一个函数,统计并返回字符串中不同字母(区分大小写)和数字的总数量。例如,输入`aA1`,返回值为3(字母`a`、`A`和数字`1`各算一个)。要求时间复杂度O(n)。

答案1:

python

defcount_unique_characters(s:str)-int:

unique_chars=set(s)

returnlen(unique_chars)

示例

print(count_unique_characters(aA1))#输出:3

解析1:

使用集合`set`可以高效去重,时间复杂度为O(n),空间复杂度也为O(n)。对于字符串中的每个字符,集合会自动处理重复项,最终返回集合的大小即可。

题目2(20分):

设计一个算法,找出数组中未排序的部分的最短长度。例如,输入`[1,2,3,5,4,7,6]`,返回值为3(从索引3开始,`[5,4,7]`未排序)。要求时间复杂度O(n)。

答案2:

python

deffind_shortest_unsorted_length(nums:list)-int:

n=len(nums)

start,end=-1,-2

max_seen,min_seen=float(-inf),float(inf)

foriinrange(n):

ifnums[i]max_seen:

end=i

else:

max_seen=nums[i]

ifnums[n-i-1]min_seen:

start=n-i-1

else:

min_seen=nums[n-i-1]

returnend-start+1

示例

print(find_shortest_unsorted_length([1,2,3,5,4,7,6]))#输出:3

解析2:

通过两次遍历数组:

1.从左到右遍历,记录当前最大值,若当前值小于最大值,则更新`end`为当前索引。

2.从右到左遍历,记录当前最小值,若当前值大于最小值,则更新`start`为当前索引。

最终`end-start+1`即为未排序部分的最短长度。

题目3(20分):

实现一个函数,将一个链表的节点随机打乱,但保证每次调用返回的结果是等概率的。例如,输入链表`1-2-3-4`,随机打乱后可能为`3-1-4-2`。要求不修改节点值,仅交换节点。

答案3:

python

importrandom

classListNode:

def__init__(self,val=0,next=None):

self.val=val

self.next=next

defshuffle_linked_list(head:ListNode)-ListNode:

current=head

result=None

whilecurrent:

next_node=current.next

current.next=result

result=current

current=next_node

returnresult

defrandom_shuffle(head:ListNode)-ListNode:

dummy=ListNode(0)

dummy.next=head

n=0

current=head

whilecurrent:

n+=1

current=current.next

new_head=None

for_inrange(n):

index=random.randint(0,n-1)

current=dummy

for_inrange(index):

current=current.next

node=current.next

current.next=node.next

node.next=new_head

new_head=node

returnnew_head

示例

head=ListNode(1,ListNode(2,ListNode(3,ListNode(4))))

shuffled=random_shuffle(head)

whileshuffled:

print(shuffled.val,end=-)

shuffled

文档评论(0)

1亿VIP精品文档

相关文档