1、两数之和
arg = [2, 3, 6, 5]
target = 4
for i in range(len(arg)):
other = target - arg[i]
if other in arg[i+1:]:
print(i, arg[i+1:].index(other)+i+1)
else:
print(“输入目标数在该列表中不存在”)
2、回文数
方法一:
class Solution:
def isPalindrome(self, x):
return str(x) == str(x)[::-1]
方法二:
class Solution:
def isPalindrome(self, x):
# 不用字符串,则用数学思想解
if x < 0 or (x % 10 == 0 and x !=0 ):
return False
rem = 0
while x > rem:
rem = rem*10 + x%10
x = x//10
return x == rem or x == rem//10
3、罗马数字转换为整数:
class Solution:
def romanToInt(self, s):
# I 1
# V 5
# X 10
# L 50
# C 100
# D 500
# M 1000
dict_num = {'I':1,'IV':4,'V':5,'IX':9,'X':10,'XL':40,'L':50,'XC':90,'C':100,'CD':400,'D':500,'CM':900,'M':1000}
ret, i =0, 0
while i < len(s):
if s[i: i+2] in dict_num:
ret += dict_num[s[i:i+2]]
i += 2
else:
ret += dict_num[s[i]]
i += 1
return ret
if name == ‘main’:
method = Solution()
x = input()
ret = method.isPalindrome(x)
print(ret)
4、最长公共前缀
class Solution(object):
def longestCommonPrefix(self, strs):
“”"
:type strs: List[str]
:rtype: str
“”"
if not strs:
return ‘’
s1, s2 = min(strs), max(strs)
print(s1, s2)
for i in range(len(s1)):
if s1[i] != s2[i]:
return s1[:i]
return s1
if name == ‘main’:
method = Solution()
x = [“flower”,“flow”,“flightwe”]
ret = method.longestCommonPrefix(x)
print(ret)
5、有效的括号
class Solution(object):
def longestCommonPrefix(self, s):
# 判断字符串3种括号的个数
if s.count(‘()’) + s.count(‘[]’) + s.count(‘{}’) != 0:
# 当个数不为0的时候,以此替换3种括号为空,直到字符串中不存在完整的括号时退出循环
s = s.replace(‘()’, ‘’)
s = s.replace(‘{}’, ‘’)
s = s.replace(‘[]’, ‘’)
# 退出循环后,如果字符串为空,则字符串包含有效的括号;反之,则包含无效(不完整)括号
if s:
return False
else:
return True
6、合并两个有序链表
class Solution:
def mergeTwoLists(self, list1, list2):
for i in range(len(list2)):
list1.append(list2[i])
ret = sorted(list1)
return ret
if name == ‘main’:
method = Solution()
list1 = []
list2 = []
ret = method.mergeTwoLists(list1, list2)
print(ret)
Definition for singly-linked list.
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
将链表转换为list
def iterNode(self,node):
output=list()
while True:
try:
output.append(node.val)
node=node.next
except:
break
return output
将list转换为链表
def iterList(self,array):
output=ListNode(array[0])
array=array[1:]
while True:
try:
output=ListNode(array[0],output)
array.pop(0)
except:
break
return output
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
避免l1和l2都是空的情况
try:
if l1==l2:
l1.next
except:
return l1
l1和l2转list
l1=self.iterNode(l1)
l2=self.iterNode(l2)
list相加,排序,翻转
total=l1+l2
total.sort()
total.reverse()
返回list转链表
return self.iterList(total)
7、删除有序数组中的重复项
方法一:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# 对列表进行循环修改时要使用nums[:]而不是nums
for n in nums[:]:
if nums.count(n) > 1:
nums.remove(n)
return len(nums)
方法二:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
nums[:] = list(sorted(set(nums)))
return len(nums)
# 因为python中的集合的自动排序是正数负数分开的,所以要用sorted排序
# 如果等号左边是nums而不是nums[:],那么nums只是指向了另一个列表而已,
# 并没有原地修改列表,原来的列表也就没有变
8、移除元素
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
for i in nums[:]:
if i == val:
if nums.count(i) > 0:
nums.remove(i)
return len(nums)
9、搜索插入位置
class Solution:
def sameTarget(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] == target:
return i
def searchInsert(self, nums: List[int], target: int) -> int:
if target in nums:
return self.sameTarget(nums,target)
else:
if target not in nums:
nums.append(target)
nums = sorted(nums)
return self.sameTarget(nums,target)
10、最后一个单词的长度
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.split()[-1])
11、加一
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
digits = digits[-1]+1
return digits
12、二进制求和
class Solution:
def addBinary(self, a: str, b: str) -> str:
a, b = int(a,2),int(b,2)
sum = a + b
binNum = str(bin(sum))[2:]
return binNum
13、x的平方根
14、爬楼梯
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return n
if n == 2:
return n
temp1 = 1
temp2 = 2
temp = 0
for i in range(3, n+1):
temp = temp1+temp2
temp1 = temp2
temp2 = temp
return temp
15、删除排序链表的重复元素
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
p = head
while p and p.next:
if p.val == p.next.val:
p.next = p.next.next
continue
p = p.next
return head
16、合并两个有序数组
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
“”"
Do not return anything, modify nums1 in-place instead.
“”"
nums1[m:] = nums2
nums1.sort()
return nums1
17、二叉树的遍历
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
left = self.inorderTraversal(root.left)
right = self.inorderTraversal(root.right)
return left + [root.val] + right
18、相同的树
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def preorder(root):
if not root:
return [None]
else:
return [root.val] +preorder(root.left)+preorder(root.right)
return preorder§==preorder(q)
19、判断对称二叉树
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def helper(left_root, right_root):
if not left_root and not right_root:
return True
if not left_root or not right_root or abs(left_root.val-right_root.val)>0:
return False
return helper(left_root.left, right_root.right) and helper(left_root.right, right_root.left)
return helper(root.left, root.right)
- 求最小公倍数的算法:
最小公倍数 = 两个整数的乘积 / 最大公约数
所以我们首先要求出两个整数的最大公约数, 求两个数的最大公约数思路如下:
- 求最大公约数算法:
① 整数A对整数B进行取整, 余数用整数C来表示 举例: C = A % B
② 如果C等于0,则C就是整数A和整数B的最大公约数
③ 如果C不等于0, 将B赋值给A, 将C赋值给B ,然后进行 1, 2 两步,直到余数为0, 则可以得知最大公约数
20、最小公倍数为 K 的子数组数目:
class Solution:
def gcd(self, x, y):
z = 0
while y:
x, y = y, x%y
return x
def lcm(self, a, b):
g = gcd(a,b)
lcm = a*b/g
return lcm
def subarrayLCM(self, nums: List[int], k: int) -> int:
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
count = 0
m = 0
for i in range(len(nums)):
m = nums[i]
for j in range(i, len(nums)):
m = lcm(m, nums[j])
if m == k:
count += 1
elif m > k:
break
else:
continue
return count
21、只出现一次的数字
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for i in range(len(nums)):
if nums.count(nums[i]) == 1:
return nums[i]
22、二叉树的最大深度
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
else:
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left,right)+1
23、颠倒二进制位
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
res = ‘{:032b}’.format(n) # 注意转换成32为无符号整形,res=bin(n)在这里会出错,ide不会
res = res[::-1] # 翻转
res = int(res, 2)
return res
24、位1的个数:
class Solution:
def hammingWeight(self, n: int) -> int:
ret = ‘{:032b}’.format(n)
return str(ret).count(‘1’)
25、有效电话号码:
cat file.txt | grep -P “^(([0-9]{3})\s|[0-9]{3}-)[0-9]{3}-[0-9]{4}$”
26、第十行
cat file.txt | sed -n 10p
27、 删除重复的电子邮箱
DELETE p1 FROM Person p1,Person p2 WHERE p1.email = p2.email and p1.id > p2.id;
28、有效的字母异位词
class Solution(object):
def isAnagram(self, s, t):
“”"
:type s: str
:type t: str
:rtype: bool
“”"
for aphal in s:
if s.count(aphal) == t.count(aphal):
ret = True
else:
ret = False
return ret
29、冒泡排序:
num = [1,4,5,2,3,6,8]
for i in range(len(num)-1):
for j in range(len(num)-i-1):
if num[j] > num[j+1]:
num[j],num[j+1] = num[j+1],num[j]
print(num)