1.字符串中的第一个唯一字符
python
def first_uniq_char(s: str) -> int:
from collections import Counter
count = Counter(s)
for i, ch in enumerate(s):
if count[ch] == 1:
return i
return -1
2. 合并两个有序数组(双指针,in-place)
题目 :给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n,分别表示 nums1 和 nums2 中的元素个数。请你合并 nums2 到 nums1 中,使合并后的数组同样按非递减顺序排列。
注意 :nums1 的长度为 m+n,其中前 m 个是有效元素,后面 n 个为 0 占位。
考察点 :逆向双指针、原地修改、避免额外空间
参考代码:
python
def merge(nums1, m, nums2, n):
i, j, k = m-1, n-1, m+n-1
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1
# 如果 nums2 还有剩余
while j >= 0:
nums1[k] = nums2[j]
j -= 1
k -= 1
3. 判断链表是否有环(快慢指针)
题目 :给定一个链表,判断链表中是否有环。
考察点 :链表操作、快慢指针、空间复杂度 O(1)
参考代码:
题目理解
给定一个链表,判断链表中是否有环。如果链表中某个节点可以通过连续 next 指针再次到达,则说明有环。
核心思路:快慢指针(Floyd判圈算法)
原理:
-
两个指针同时从头节点出发
-
慢指针每次移动1步
-
快指针每次移动2步
-
如果有环,快指针一定会追上慢指针(在环内相遇)
-
如果无环,快指针会先到达链表末尾(null)
python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def hasCycle(head: ListNode) -> bool:
# 边界条件:空链表或只有一个节点且无环
if not head or not head.next:
return False
slow = head
fast = head
while fast and fast.next:
slow = slow.next # 慢指针走一步
fast = fast.next.next # 快指针走两步
if slow == fast: # 相遇,说明有环
return True
return False # 快指针到达终点,无环
Q: 如何计算环的长度?
python
def cycle_length(head: ListNode) -> int:
slow = fast = head
# 先找到相遇点
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
# 计算环长度
length = 1
fast = fast.next
while slow != fast:
fast = fast.next
length += 1
return length
return 0
4. 最长公共前缀(字符串处理)
题目 :编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
示例 :["flower","flow","flight"] → "fl"
考察点 :字符串遍历、边界处理、工程健壮性(空数组)
参考代码:
python
def longest_common_prefix(strs):
if not strs:
return ""
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ""
return prefix