以下是 LeetCode Top 100 的一些精选题目及其解答,这些题目对面试非常有帮助。由于内容较多,下面将提供部分题目的解答。如果你需要更多题目的解答,请告诉我。
1. Two Sum (两数之和)
题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
解答
def two_sum(nums, target):
num_to_index = {
}
for i, num in enumerate(nums):
complement = target - num
if complement in num_to_index:
return [num_to_index[complement], i]
num_to_index[num] = i
return []
2. Add Two Numbers (两数相加)
题目描述
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
解答
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def add_two_numbers(l1, l2):
dummy_head = ListNode(0)
p, q, curr = l1, l2, dummy_head
carry = 0
while p is not None or q is not None:
x = p.val if p is not None else 0
y = q.val if q is not None else 0
total = carry + x + y
carry = total // 10
curr.next = ListNode(total % 10)
curr = curr.next
if p is not None: p = p.next
if q is not None: q = q.next
if carry > 0:
curr.next = ListNode(carry)
return dummy_head.next
3. Longest Substring Without Repeating Characters (无重复字符的最长子串)
题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
解答
def length_of_longest_substring(s)