一、数组
1 两数之和
nums = []
nums = list(map(int, input().split()))
target = int(input())
sum = 0
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
sum = nums[i]+nums[j]
if sum == target:
print(i, j)
else:
sum = 0
53 最大子数组和
在力扣的评论里看到了一句很经典的话来阐述该题的思想:
这一生,我会遇见很多人。如果我们能一起变好,那么我们就在一起,如果不能,我将丢下你。我回顾我最光辉的时刻就是和不同人在一起,变得更好的最长连续时刻。
# 这一生,我会遇见很多人。如果我们能一起变好,那么我们就在一起,如果不能,我将丢下你。
# 我回顾我最光辉的时刻就是和不同人在一起,变得更好的最长连续时刻。
nums = []
nums = list(map(int, input().split()))
pre = 0
MaxAns = nums[0]
for i in nums:
pre = max(pre+i, i)
MaxAns = max(pre, MaxAns)
print(MaxAns)
121 买卖股票的最佳时机
prices = []
prices = list(map(int, input().split()))
maxprofit = 0
minprice = 10e9
for i in prices:
maxprofit = max(i - minprice, maxprofit)
minprice = min(minprice, i)
print(maxprofit)
136 只出现一次的数字
a = list(map(int, input().split()))
for i in a:
if a.count(i)>1:
pass
else:
print(i)
169 多数元素
nums = list(map(int, input().split()))
# 方法1:超时
# for i in nums:
# if nums.count(i) > len(nums)/2:
# res = i
# print(res)
# 方法2:利用众数
nums.sort()
print(nums[len(nums) // 2])
283 移动零
nums = list(map(int, input().split()))
# 方法1:超时
# count = 0
# a = []
# for i in nums:
# if i == 0:
# count += 1
# else:
# a.append(i)
# for i in range(len(nums)):
# if i >= len(nums) - count:
# a.append(0)
# print(a)
# 方法2:使用双指针法,仅在nums中进行修改
left = right = 0
for i in range(len(nums)):
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1
print(nums)
448 找到所有数组中消失的数字
在输出结果时,无法用index来获取多个重复值的下标,需要借助enumerate函数。
# 利用nums自身作为hash数组
nums = list(map(int, input().split()))
n = len(nums)
for i in nums:
x = (i-1) % n
nums[x] += n
# index只能获取第一个匹配值的下标
# 如果想获取多个重复值的下标,需要用enumerate函数
ret = [i+1 for i, x in enumerate(nums) if x <= n]
print(ret)
二、字符串
20 有效的括号
如果字符串长度为奇数,则false
遍历字符串:
- 如果是左括号,直接入栈;
- 如果是右括号,则将其与栈顶元素进行匹配:
(1)如果此时栈为空,则说明右括号多余,false
(2)如果不匹配,则false
(3)如果匹配,则出栈 - 最后检查栈是否为空,若不空,则左括号多余,false
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
# 生成一个pairs字典存放 键为:右括号,值为左括号
pairs = {
")": "(",
"]": "[",
"}": "{",
}
# 定义一个栈列表
stack = list()
for i in s: # 遍历输入的括号
if i in pairs: # 遍历字典里的键,即遇到右括号,则进行以下判断
# 如果stack是空列表(说明右括号多余),或者stack列表的栈顶元素不等于当前的右括号(括号不匹配),则返回false
if not stack or stack[-1] != pairs[i]:
return False
# 若括号匹配,则用pop()函数用于移除列表中的一个元素,并返回该元素的值。
stack.pop()
else: # 将左括号全部输入到栈内
stack.append(i)
return not stack # return not总是返回一个布尔值,栈空则true,栈不空则false。
a = Solution().isValid('{[(]}')
print(a)