目录
计算题
1. 给定一个长度为 n 的整数数组 nums 和一个目标值 target,请你从 nums 中选出三个整数,使得它们的和与 target 最接近。
def threeSumClosest(nums, target):
nums.sort() # 对数组进行排序
closest_sum = float('inf') # 初始设定为正无穷大
for i in range(len(nums) - 2):
left = i + 1
right = len(nums) - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if current_sum == target:
return current_sum
# 更新最接近的和
if abs(current_sum - target) < abs(closest_sum - target):
closest_sum = current_sum
if current_sum < target:
left += 1
else:
right -= 1
return closest_sum
nums = [-1,2,1,-4]
target = 1
result = threeSumClosest(nums, target)
print(result) # 2
2.以下是一个函数的示例代码,它接受一个32位有符号整数x,并返回其数字部分反转后的结果。如果反转后的整数超出了32位有符号整数的范围[-2^31, 2^31-1],则返回0,假设环境不允许存储64位整数
def reverse_integer(x):
INT_MAX = 2 ** 31 - 1
INT_MIN = -2 ** 31
sign = 1
if x < 0:
sign = -1
x = -x
reversed_num = 0
while x > 0:
reversed_num = reversed_num * 10 + x % 10
x //= 10
if reversed_num > INT_MAX or reversed_num < INT_MIN:
return 0
return sign * reversed_num
res=reverse_integer(123)
print(res) # 321
3. 以下是一个函数的示例代码,它接受字符串s和t,并返回s中包含t所有字符的最小子串。如果s中不存在包含t所有字符的子串,则返回空字符串''
from collections import Counter
def min_window(s, t):
# 计算t中每个字符的出现次数
target_counts = Counter(t)
required_chars = len(target_counts)
# 初始化指针和计数器
left = 0
right = 0
formed_chars = 0
window_counts = {}
# 记录最小字串的起始位置和长度
min_length = float('inf')
min_window_start = 0
while right < len(s):
# 扩展窗口
char = s[right]
window_counts[char] = window_counts.get(char, 0) + 1
# 当前字符在t中,并且其出现次数匹配
if char in target_counts and window_counts[char] == target_counts[char]:
formed_chars += 1
# 尝试收缩窗口
while formed_chars == required_chars and left <= right:
# 更新最小字串的长度和起始位置
if right - left + 1 < min_length:
min_length = right - left + 1
min_window_start = left
# 收缩窗口左边界
char = s[left]
window_counts[char] -= 1
if char in target_counts and window_counts[char] < target_counts[char]:
formed_chars -= 1
left += 1
right += 1
if min_length == float('inf'):
return ''
else:
return s[min_window_start:min_window_start + min_length]
s = "ADOBECODEBANC"
t = "ABC"
min_substring = min_window(s, t)
print(min_substring) # BANC
4.
标签:总结,right,target,nums,sum,计算题,整数,counts
From: https://www.cnblogs.com/zhanglanhua/p/17421061.html