- 0
- 0
- 约8.51千字
- 约 29页
- 2026-02-12 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年华为软件开发面试题库及答案参考
一、编程基础题(共5题,每题10分)
题目1
请编写一个函数,实现快速排序算法,并对以下数组进行排序:[34,7,23,32,5,62,78,4,56]
答案:
python
defquick_sort(arr):
iflen(arr)=1:
returnarr
pivot=arr[len(arr)//2]
left=[xforxinarrifxpivot]
middle=[xforxinarrifx==pivot]
right=[xforxinarrifxpivot]
returnquick_sort(left)+middle+quick_sort(right)
array=[34,7,23,32,5,62,78,4,56]
sorted_array=quick_sort(array)
print(sorted_array)
解析:
快速排序是一种分治算法,基本思想是:
1.选择一个基准值(pivot)
2.将数组分为两部分,一部分小于基准值,一部分大于基准值
3.递归地对这两部分进行快速排序
时间复杂度为O(nlogn),空间复杂度为O(logn)
题目2
请实现一个函数,检查一个字符串是否是回文串(正读反读都一样),例如:madam、racecar
答案:
python
defis_palindrome(s):
returns==s[::-1]
测试
print(is_palindrome(madam))#True
print(is_palindrome(racecar))#True
print(is_palindrome(hello))#False
解析:
回文串判断可以通过以下方法:
1.将字符串反转,比较反转前后是否相同
2.双指针法,从头尾开始向中间移动,比较对应字符是否相同
时间复杂度为O(n),空间复杂度为O(1)
题目3
请编写一个函数,找出数组中重复次数超过一半的元素,如果不存在则返回-1
答案:
python
defmajority_element(nums):
count=0
candidate=None
fornuminnums:
ifcount==0:
candidate=num
count+=(1ifnum==candidateelse-1)
验证
ifcandidateisnotNoneandnums.count(candidate)len(nums)//2:
returncandidate
return-1
测试
print(majority_element([3,2,3]))#3
print(majority_element([2,2,1,1,1,2,2]))#2
print(majority_element([1,1,2]))#-1
解析:
摩尔投票算法:
1.遍历数组,维护一个候选者和计数器
2.如果计数为0,将当前元素设为候选者
3.如果当前元素与候选者相同,计数加1,否则减1
4.最后验证候选者是否满足条件
时间复杂度为O(n),空间复杂度为O(1)
题目4
请实现一个LRU(最近最少使用)缓存,支持get和put操作
答案:
python
classLRUCache:
def__init__(self,capacity:int):
self.capacity=capacity
self.cache={}
self.order=[]
defget(self,key:int)-int:
ifkeyinself.cache:
self.order.remove(key)
self.order.append(key)
returnself.cache[key]
return-1
defput(self,key:int,value:int)-None:
ifkeyinself.cache:
self.order.remove(key)
eliflen(self.cache)=self.capacity:
oldest=self.order.pop(0)
delself.cache[oldest]
self.cache[key]=value
self.order.append(key)
测试
cache=LRUCache(2)
cache.put(1,1)
cache.p
原创力文档

文档评论(0)