简单题简单做
9: 回文数

解法:str化然后判断和逆序是否相等
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x)==str(x)[::-1]
7:整数反转

class Solution:
def reverse(self, x: int) -> int:
if x >= 0:
result = int(str(x)[::-1])
if result > (2 ** 31 - 1):
return 0
return result
else:
result = int(str(-x)[::-1]) * -1
if result < -(2 ** 31 - 1):
return 0
return result
13.罗马数字转整数
解析:
-
构建一个字典记录所有罗马数字子串,注意长度为2的子串记录的值是(实际值 - 子串内左边罗马数字代表的数值)
-
这样一来,遍历整个 ss 的时候判断当前位置和前一个位置的两个字符组成的字符串是否在字典内,如果在就记录值,不在就说明当前位置不存在小数字在前面的情况,直接记录当前位置字符对应值
举个例子,遍历经过 IV 的时候先记录 I 的对应值 1 再往前移动一步记录 IV 的值 3,加起来正好是 IV 的真实值 4。max 函数在这里是为了防止遍历第一个字符的时候出现 [-1:0][−1:0] 的情况
class Solution:
def romanToInt(self, s: str) -> int:
d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}
return sum(d.get(s[max(i-1, 0):i+1], d[n]) for i, n in enumerate(s))
14.最长公共前缀

class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if strs ==[]:
return ""
min_len = min([len(s) for s in strs])
r = []
for id,c in enumerate(zip(*strs)):
if len(set(c)) == 1 and id< min_len:
r.append(c[0])
else:
break
return "".join(r)
20.有效的括号

class Solution:
def isValid(self, s: str) -> bool:
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''
21.合并两个有序链表

class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
l1, l2 = sorted((l1, l2), key=lambda x: x.val)
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2
26. 删除排序数组中的重复项

class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
nums[:]= sorted(list(set(nums)))#一定还有排序
#这个地方如果是nums= 就会错,因为只是单纯实现值传递,
return len(nums)
27. 移除元素

class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
for i in range(nums.count(val)):
nums.remove(val)
return len(nums)
28. 实现strStr()

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
p = haystack.find(needle)
return p
35. 搜索插入位置

class Solution(object):
def searchInsert(self, nums, target):
for i in range(len(nums)):
if nums[i] >= target:
return i
return i+1
38. 报数
没读懂题。。。
53.最大子序和

class Solution:
def maxSubArray(self, nums: List[int]) -> int:
for i in range(1, len(nums)):
nums[i]= nums[i] + max(nums[i-1], 0)
return max(nums)
66. 加一

class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
d = int(''.join([str(i) for i in digits]))+1
return [int(i) for i in str(d) ]
67. 二进制求和

class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a,2)+int(b,2))[2:]
69. x 的平方根

class Solution:
def mySqrt(self, x: int) -> int:
return int(x**(1/2))
83. 删除排序链表中的重复元素

class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head: return head
pre, post = head, head.next
while post:
if pre.val == post.val:
pre.next = post.next
post = pre.next
else:
post = post.next
pre = pre.next
return head
88. 合并两个有序数组

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()
100. 相同的树

class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def dfs(tree):
if tree:
yield tree.val
if not tree.left and tree.right:
yield 'null'
yield from dfs(tree.left)
yield from dfs(tree.right)
p_list = list(dfs(p))
q_list = list(dfs(q))
return p_list == q_list
136: 只出现一次的数字
题目:给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
解法1:所有出现数字和的两倍-所有数字的和
代码:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return 2*sum(set(nums))-sum(nums)
解法2:异或运算
代码:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
a = 0
for i in nums:
a ^= i
return a
141. 环形链表

class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = fast = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
70.爬楼梯

class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
a, b = 1, 1
for i in range(n):
a, b = b, a + b
return a
使用缓存也可以,C语言实现的:fastcache
from functools import lru_cache
class Solution:
@lru_cache(10**8)
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
elif n == 2:
return 2
else:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
160. 相交链表

class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
d = dict()
while headA:
d[headA] = 1
headA = headA.next
while headB:
if headB in d:
return headB
headB = headB.next
return None
169. 求众数

class Solution:
def majorityElement(self, nums: List[int]) -> int:
l = len(nums)
if l == 1:
return nums[0]
nums.sort()
return nums[(l-1)//2]
217. 存在重复元素

class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return not len(nums) == len(set(nums))
231. 2的幂

class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
res = 1
while res < n:
res *= 2
return res == n
292. Nim 游戏

class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n%4
344. 反转字符串

class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
return s.reverse()
或者双指针,交换头尾两个指针所指的两个位置的值,指针向中间移动一个位置,重复以上操作,直到两个指针交错
374. 猜数字大小

383. 赎金信

class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
a = list(ransomNote)
b = list(magazine)
try:
for i in a:
b.remove(i)
return True
except:
return False
389. 找不同

class Solution(object):
def findTheDifference(self, s, t):
a1 = sum([ord(x) for x in s])
a2 = sum([ord(x) for x in t])
return chr(a2-a1)
400. 第N个数字

class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
digit = 1
while True:
first = 10**(digit-1)
cnt = 9 * first * digit
if cnt >= n:
return int(str(first + (n-1)//digit)[(n-1) % digit])
n -= cnt
digit += 1
557. 反转字符串中的单词 III

class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return " ".join([i[::-1] for i in s.split(" ")])
中等题简单做
2. 两数相加

class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
x1 = ''
while l1:
x1 += str(l1.val)
l1 = l1.next
x2 = ''
while l2:
x2 += str(l2.val)
l2 = l2.next
res = int(x1[::-1]) + int(x2[::-1])
res = str(res)[::-1]
ans = ListNode(int(res[0]))
ans1 = ans
for i in res[1:]:
ans.next = ListNode(int(i))
ans = ans.next
return ans1