Python算法岗面试典型题目及答案
·
面试Python算法岗位时,候选人通常会遇到一系列设计来考察其编程能力、算法理解和解决问题能力的题目。这些题目范围可以从基本的数据结构操作到更复杂的算法问题。下面是一些典型的上机测试题及其解答示例:
1. 两数之和
题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
答案:
def two_sum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
return []
2. 反转链表
题目描述: 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
答案:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def reverse_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
3. 有效的括号
题目描述: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
示例:
输入: "()[]{}"
输出: True
答案:
def is_valid(s):
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
4. 合并两个有序链表
题目描述: 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
答案:
def merge_two_lists(l1, l2):
dummy = ListNode(-1)
prev = dummy
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
prev.next = l1 if l1 else l2
return dummy.next
更多推荐



所有评论(0)