引言
在互联网行业,编程面试是求职者进入一线互联网公司的重要关卡。面试官通常会通过一系列编程题目来考察应聘者的编程能力、逻辑思维和解决问题的能力。本文将揭秘一线互联网公司的编程面试真题,并提供相应的解题思路,助你轻松通关面试。
一、算法题
1. 快速排序
题目描述:给定一个整数数组,实现快速排序算法。
解题思路:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# 示例
arr = [3, 6, 8, 10, 1, 2, 1]
print(quick_sort(arr))
2. 合并两个有序链表
题目描述:给定两个有序链表,合并它们为一个新的有序链表。
解题思路:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_sorted_lists(l1, l2):
dummy = ListNode()
current = dummy
while l1 and l2:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
current.next = l1 or l2
return dummy.next
# 示例
l1 = ListNode(1, ListNode(2, ListNode(4)))
l2 = ListNode(1, ListNode(3, ListNode(4)))
print(merge_sorted_lists(l1, l2))
二、数据结构题
1. 二叉树遍历
题目描述:给定一个二叉树,实现前序、中序和后序遍历。
解题思路:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder_traversal(root):
if not root:
return []
return [root.val] + preorder_traversal(root.left) + preorder_traversal(root.right)
def inorder_traversal(root):
if not root:
return []
return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right)
def postorder_traversal(root):
if not root:
return []
return postorder_traversal(root.left) + postorder_traversal(root.right) + [root.val]
# 示例
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
print(preorder_traversal(root))
print(inorder_traversal(root))
print(postorder_traversal(root))
2. 链表反转
题目描述:给定一个单链表,实现链表反转。
解题思路:
def reverse_linked_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
# 示例
head = ListNode(1, ListNode(2, ListNode(3)))
print(reverse_linked_list(head))
三、系统设计题
1. 缓存系统
题目描述:设计一个缓存系统,支持添加、删除和查询操作。
解题思路:
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key: int) -> int:
if key not in self.cache:
return -1
else:
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
# 示例
lru_cache = LRUCache(2)
lru_cache.put(1, 1)
lru_cache.put(2, 2)
print(lru_cache.get(1)) # 输出 1
lru_cache.put(3, 3) # 删除键 2
print(lru_cache.get(2)) # 输出 -1
总结
本文揭秘了一线互联网公司编程面试中的常见题目,包括算法题、数据结构题和系统设计题。通过学习和练习这些题目,相信你能够在面试中取得优异的成绩。祝你面试顺利!
