剑指 Offer(专项突击版)第19|20题:算法题解
2024-01-07 04:31:09
前言
随着前端技术的发展,越来越多的企业在招聘时会考察求职者的算法能力。算法题的出现,既是对求职者编程基础的考验,也是对他们思维敏捷程度的考察。而《剑指 Offer(专项突击版)》作为一本经典的算法题集,更是成为了许多求职者备战面试的必备教材。
本文将对《剑指 Offer(专项突击版)》中的第 19 题和第 20 题进行详细解答,帮助您轻松应对面试中的算法题挑战。
正文
第 19 题:缺失的数字
题目
给定一个长度为 n 的整数数组 nums ,其中 n 个数字范围在 0 到 n 之间,但数组中存在一个数字缺失。请找出缺失的数字。
解题思路:
本题的关键在于利用数字和的特性,即一个长度为 n 的整数数组中,所有数字的和等于 n * (n+1) / 2。因此,我们可以先计算数组中所有数字的和,再用 n * (n+1) / 2 减去这个和,即可得到缺失的数字。
实现步骤:
- 定义一个变量 sum,并将其初始化为 0。
- 遍历数组 nums,将数组中的每个数字累加到 sum 中。
- 计算数组中所有数字的和 total_sum = n * (n+1) / 2。
- 返回 total_sum - sum。
时间复杂度:
本题的时间复杂度为 O(n),因为我们需要遍历整个数组来计算数字和。
空间复杂度:
本题的空间复杂度为 O(1),因为我们只需要定义一个变量 sum 来存储数组中所有数字的和。
实例演示:
def missing_number(nums):
"""
Finds the missing number in a given array of integers.
Args:
nums: A list of integers in the range [0, n], where n is the length of the list.
Returns:
The missing number.
"""
sum = 0
for num in nums:
sum += num
total_sum = len(nums) * (len(nums) + 1) // 2
return total_sum - sum
if __name__ == "__main__":
# Example usage:
nums = [0, 1, 3, 4, 5, 7, 8, 9]
missing_number = missing_number(nums)
print("The missing number is:", missing_number)
第 20 题:表示数值的字符串
题目:
给定一个字符串 s ,它表示一个数值。请将这个字符串转换为对应的整数。
解题思路:
本题的关键在于考虑字符串 s 中可能出现的各种情况,包括正数、负数、小数点、科学计数法等。我们可以使用正则表达式来匹配这些情况,并根据匹配结果对字符串进行相应的处理。
实现步骤:
- 使用正则表达式匹配字符串 s 中的数字、正负号、小数点和科学计数法符号。
- 根据匹配结果,将字符串 s 转换为对应的整数。
- 如果字符串 s 中存在非法字符,则抛出异常。
时间复杂度:
本题的时间复杂度为 O(n),因为我们需要遍历整个字符串来匹配数字和符号。
空间复杂度:
本题的空间复杂度为 O(1),因为我们只需要定义几个变量来存储匹配结果。
实例演示:
import re
def string_to_number(s):
"""
Converts a string representing a number to an integer.
Args:
s: A string representing a number.
Returns:
The integer represented by the string.
"""
# Compile the regular expression pattern
pattern = re.compile(r"^(?P<sign>[+-]?)(?P<integer>\d+)(?:\.(?P<fraction>\d+))?(?:[eE](?P<exponent>[+-]?\d+))?import re
def string_to_number(s):
"""
Converts a string representing a number to an integer.
Args:
s: A string representing a number.
Returns:
The integer represented by the string.
"""
# Compile the regular expression pattern
pattern = re.compile(r"^(?P<sign>[+-]?)(?P<integer>\d+)(?:\.(?P<fraction>\d+))?(?:[eE](?P<exponent>[+-]?\d+))?$")
# Match the string against the regular expression pattern
match = pattern.match(s)
# If the string does not match the pattern, raise an exception
if not match:
raise ValueError("Invalid number format.")
# Extract the sign, integer, fraction, and exponent from the match
sign = match.group("sign")
integer = match.group("integer")
fraction = match.group("fraction")
exponent = match.group("exponent")
# Convert the integer and fraction to integers
integer = int(integer)
if fraction:
fraction = int(fraction)
# Convert the exponent to an integer
if exponent:
exponent = int(exponent)
# Calculate the value of the number
value = integer
# If the fraction is not empty, add it to the value
if fraction:
value += fraction / (10 ** len(fraction))
# If the exponent is not empty, multiply the value by 10 raised to the power of the exponent
if exponent:
value *= (10 ** exponent)
# If the sign is negative, negate the value
if sign == "-":
value = -value
# Return the value
return value
if __name__ == "__main__":
# Example usage:
s = "123"
number = string_to_number(s)
print("The number represented by the string is:", number)
quot;)
# Match the string against the regular expression pattern
match = pattern.match(s)
# If the string does not match the pattern, raise an exception
if not match:
raise ValueError("Invalid number format.")
# Extract the sign, integer, fraction, and exponent from the match
sign = match.group("sign")
integer = match.group("integer")
fraction = match.group("fraction")
exponent = match.group("exponent")
# Convert the integer and fraction to integers
integer = int(integer)
if fraction:
fraction = int(fraction)
# Convert the exponent to an integer
if exponent:
exponent = int(exponent)
# Calculate the value of the number
value = integer
# If the fraction is not empty, add it to the value
if fraction:
value += fraction / (10 ** len(fraction))
# If the exponent is not empty, multiply the value by 10 raised to the power of the exponent
if exponent:
value *= (10 ** exponent)
# If the sign is negative, negate the value
if sign == "-":
value = -value
# Return the value
return value
if __name__ == "__main__":
# Example usage:
s = "123"
number = string_to_number(s)
print("The number represented by the string is:", number)
总结
本文对《剑指 Offer(专项突击版)》中的第 19 题和第 20 题进行了详细解答,涵盖了解题思路、实现步骤、时间复杂度、空间复杂度以及实例演示。相信通过本文的学习,您能够对这些算法题的解决方法有更加深刻的理解。
希望本文能够对您顺利通关面试中的算法题挑战有所帮助。祝您在求职的道路上旗开得胜!