2026年华为技术面试工程助理攻略及答案.docxVIP

  • 0
  • 0
  • 约7.76千字
  • 约 24页
  • 2026-02-12 发布于福建
  • 举报

2026年华为技术面试工程助理攻略及答案.docx

第PAGE页共NUMPAGES页

2026年华为技术面试工程助理攻略及答案

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

1.编程题1(20分):

题目:

编写一个函数,实现快速排序算法。输入一个整数数组,输出排序后的数组。

要求:

-使用原地排序(不额外分配数组空间)。

-处理包含重复元素的数组。

-时间复杂度O(nlogn),空间复杂度O(logn)。

答案:

python

defquick_sort(arr,low,high):

iflowhigh:

pivot_index=partition(arr,low,high)

quick_sort(arr,low,pivot_index-1)

quick_sort(arr,pivot_index+1,high)

defpartition(arr,low,high):

pivot=arr[high]

i=low-1

forjinrange(low,high):

ifarr[j]=pivot:

i+=1

arr[i],arr[j]=arr[j],arr[i]

arr[i+1],arr[high]=arr[high],arr[i+1]

returni+1

示例调用

arr=[3,6,8,10,1,2,1]

quick_sort(arr,0,len(arr)-1)

print(arr)#输出:[1,1,2,3,6,8,10]

解析:

-快速排序采用分治法,通过基准值(pivot)将数组分成两部分,左部分均小于等于基准值,右部分均大于等于基准值。

-递归排序左右子数组,直到子数组长度为1。

-时间复杂度:平均O(nlogn),最坏O(n2)(当数组已排序或逆序)。空间复杂度:O(logn)(递归栈空间)。

2.编程题2(20分):

题目:

实现一个LRU(最近最少使用)缓存。缓存容量为固定值,当缓存满时,删除最久未使用的元素。支持`get`和`put`操作。

要求:

-`get(key)`:如果缓存中有key,返回其值并更新最近使用时间;否则返回-1。

-`put(key,value)`:如果缓存中有key,更新其值并更新最近使用时间;否则,如果缓存已满,删除最久未使用的元素后插入新元素。

答案:

python

classLRUCache:

def__init__(self,capacity):

self.capacity=capacity

self.cache={}

self.order=[]

defget(self,key):

ifkeyinself.cache:

self.order.remove(key)

self.order.append(key)

returnself.cache[key]

return-1

defput(self,key,value):

ifkeyinself.cache:

self.order.remove(key)

eliflen(self.cache)==self.capacity:

oldest_key=self.order.pop(0)

delself.cache[oldest_key]

self.cache[key]=value

self.order.append(key)

示例调用

lru=LRUCache(2)

lru.put(1,1)

lru.put(2,2)

print(lru.get(1))#输出:1

lru.put(3,3)#假设容量为2,删除key=2

print(lru.get(2))#输出:-1

解析:

-使用哈希表存储键值对(O(1)访问),使用双向链表维护使用顺序(O(1)插入和删除)。

-`get`操作将访问的key移到链表末尾(表示最近使用)。

-`put`操作若key已存在,更新值并移动到末尾;若不存在且缓存已满,删除链表头部元素(最久未使用)后插入新元素。

3.编程题3(20分):

题目:

编写一个函数,统计一个字符串中所有字母的出现次数,忽略大小写,仅统计字母字符。

要求:

-输入:字符串`s`。

-输出:字典,键为字母,值为出现次数。

答案:

python

defcount_letters(s):

count={}

forcharins.lower():

ifchar.isalpha():

count[char]=count.get(char,0)+1

returncount

示例调

文档评论(0)

1亿VIP精品文档

相关文档