python版LeetCode
算法部分


811. 子域名访问计数
class Solution:def subdomainVisits(self, cpdomains):""":type cpdomains: List[str]:rtype: List[str]"""topdomain = dict()seconddomain = dict()thirddomain = dict()# 创建各三级域名和访问计数的键值对for cpd in cpdomains:domain = cpd.split()[1]if len(domain.split('.')) == 2:topdomain[domain.split('.')[1]] = 0seconddomain['.'.join(domain.split('.')[:])] = 0if len(domain.split('.')) == 3:topdomain[domain.split('.')[2]] = 0seconddomain['.'.join(domain.split('.')[1:])] = 0thirddomain['.'.join(domain.split('.')[:])] = 0# 进行访问计数for cpd in cpdomains:count = int(cpd.split()[0])domain = cpd.split()[1]for top in topdomain:if domain.endswith(top):topdomain[top] += countfor second in seconddomain:if domain.endswith(second):seconddomain[second] += countfor third in thirddomain:if domain.endswith(third):thirddomain[third] += countreturn [str(c) + ' ' + d for d, c in topdomain.items()] + \[str(c) + ' ' + d for d, c in seconddomain.items()] + \[str(c) + ' ' + d for d, c in thirddomain.items()]709. 转换成小写字母
class Solution:def toLowerCase(self, str):""":type str: str:rtype: str"""return str.lower()557. 反转字符串中的单词 III
class Solution:def reverseWords(self, s):""":type s: str:rtype: str"""ls = s.split()for i in range(len(ls)):ls[i] = ls[i][::-1]return ' '.join(ls)414. 第三大的数
class Solution:def thirdMax(self, nums):""":type nums: List[int]:rtype: int"""min_nums = min(nums)first = min_numssecond = min_numsthird = min_numsfor n in nums:if first < n:first = nfor n in nums:if n < first and second < n:second = nfor n in nums:if n < second and third < n:third = nif second == third:return firstelse:return third344. 反转字符串
class Solution:def reverseString(self, s):""":type s: str:rtype: str"""return s[::-1]231. 2的幂
class Solution:def isPowerOfTwo(self, n):""":type n: int:rtype: bool"""return bin(n).startswith('0b1') and bin(n).count('1') == 1217. 存在重复元素
class Solution:def containsDuplicate(self, nums):""":type nums: List[int]:rtype: bool"""return len(list(set(nums))) != len(nums)169. 求众数
class Solution:def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""for i in set(nums):if nums.count(i) > len(nums)/2:return i136. 只出现一次的数字
class Solution:def singleNumber(self, nums):""":type nums: List[int]:rtype: int"""num = 0for i in nums:num = num ^ ireturn num88. 合并两个有序数组
class Solution:def merge(self, nums1, m, nums2, n):""":type nums1: List[int]:type m: int:type nums2: List[int]:type n: int:rtype: void Do not return anything, modify nums1 in-place instead."""# a = 0# b = 0# # nums1中的0真折腾,暂时未解决# if nums1[0]==0 and m == 0:#     nums1[:] = nums2[:]# else:#     while b < n and a < m+n:#         if nums1[a] > nums2[b]:#             nums1[a:a] = [nums2[b]]#             b += 1#         elif nums1[a] == 0 and nums1[a-1] > 0:#             nums1[a:] = nums2[b:]#             break#         a += 1# # 去掉nums1结尾的0# while not nums1[-1]:#     nums1.pop()for i in range(n):nums1[m] = nums2[i]m += 1nums1.sort()70. 爬楼梯
class Solution:def climbStairs(self, n):""":type n: int:rtype: int"""way = [0, 1, 2]for i in range(3, n + 1):way.append(way[i - 1] + way[i - 2])return way[n]26. 删除排序数组中的重复项
class Solution:def removeDuplicates(self, nums):""":type nums: List[int]:rtype: int"""# a慢指针, b快指针a = 0b = 0for i in range(len(nums)):# 如果快慢不同,则慢指针后移,再赋快指针的值if nums[a] != nums[b]:a += 1nums[a] = nums[b]# 快指针从头移动到尾b += 1# 如果数组为[]返回0return a+1 if nums else 020. 有效的括号
class Solution:def isValid(self, s):""":type s: str:rtype: bool"""d = {'(': ')', '[': ']', '{': '}'}ls = []for ss in s:if not ls:ls.append(ss)else:if d.get(ls[-1]) == ss:ls.pop()else:ls.append(ss)return False if ls else True14. 最长公共前缀
class Solution:def longestCommonPrefix(self, strs):""":type strs: List[str]:rtype: str"""# 如果含有''if not strs or '' in strs:return ''# 按照字符串长度排序,看来是没必要的,# strs = sorted(strs, key=lambda s:len(s))# 只要找到最短的字符串中的字符,作为暂定的前缀进行判断即可prefix = strs[0]for s in strs:if len(prefix) > len(s):prefix = s# 切片位置初置为-1n = -1for i in range(len(prefix)):# 如果前缀字符是所有字符串的公共前缀,则切片位置为i,继续判断下一个字符是否匹配if all([prefix[i] == s[i] for s in strs]) :n = i# 否则就找到了最长前缀,退出循环else:break# 如果切片值为-1,则返回'',否则返回从最短的字符串切好的片作为最长公共前缀return prefix[:n+1]9. 回文数
class Solution:def isPalindrome(self, x):""":type x: int:rtype: bool"""x = str(x)return x == x[::-1]7. 整数反转
class Solution:def reverse(self, x):""":type x: int:rtype: int"""if x < 0:# 去掉'-'x = '-' + str(x)[1:][::-1]elif x > 0:x = str(x)# 去掉结尾的0while x.endswith('0'):x = x[:-1]x = x[::-1]else:x = '0'# 如果x反转后溢出,或者x==0,那么就返回 0。x = int(x)if x < -2 ** 31 or x > 2 ** 31 - 1 or x == 0:return 0return x771. 宝石与石头
class Solution:def numJewelsInStones(self, J, S):""":type J: str:type S: str:rtype: int"""n = 0for j in J:n += S.count(j)return n657. 机器人能否返回原点
class Solution:def judgeCircle(self, moves):""":type moves: str:rtype: bool"""return False if (moves.count('R') - moves.count('L')) or (moves.count('U') - moves.count('D')) else True832. 翻转图像
class Solution:def flipAndInvertImage(self, A):""":type A: List[List[int]]:rtype: List[List[int]]"""for i in range(len(A)):A[i] = A[i][::-1]for j in range(len(A[i])):A[i][j] = int(not A[i][j])return A476. 数字的补数
class Solution:def findComplement(self, num):""":type num: int:rtype: int"""num = bin(num)cpl = list('0b')for i in num[2:]:if i == '1':cpl.append('0')else:cpl.append('1')return int(''.join(cpl), 2)852. 山脉数组的峰顶索引
class Solution:def peakIndexInMountainArray(self, A):""":type A: List[int]:rtype: int"""return A.index(max(A))500. 键盘行
class Solution:def findWords(self, words):""":type words: List[str]:rtype: List[str]"""tab = 'qwertyuiop'capslock = 'asdfghjkl'shift = 'zxcvbnm'inline = []for W in words:w = W.lower()if all(c in tab for c in w) or all(c in capslock for c in w) or all(c in shift for c in w):inline.append(W)return inline        867. 转置矩阵
class Solution:def transpose(self, A):""":type A: List[List[int]]:rtype: List[List[int]]"""return [[row[col] for row in A] for col in range(len(A[0]))]349. 两个数组的交集
class Solution:def intersection(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]"""return list(set(nums1) & set(nums2))680. 验证回文字符串 Ⅱ
class Solution:def validPalindrome(self, s):""":type s: str:rtype: bool"""l = 0r = len(s) - 1while l < r:if s[l] != s[r]:# 尝试跳过一个字符,直接调用判断接口,去判断剩下的即可def judge(s, i, j):while i < j:if s[i] != s[j]:return Falsei += 1j -= 1return Truereturn judge(s, l+1, r) or judge(s, l, r-1)l += 1r -= 1return True836. 矩形重叠
class Solution:def isRectangleOverlap(self, rec1, rec2):""":type rec1: List[int]:type rec2: List[int]:rtype: bool"""    # rec1中扫描区间# 扫描精度prec,步长prec*区间长度x = (rec1[3]-rec1[1])y = (rec1[2]-rec1[0])prec = 1# 似乎最高精度设置为1/16即可通过测试PREC = 1/16while prec > PREC:i = rec1[0]while i < rec1[2]:j = rec1[1]while j < rec1[3]:if i > rec2[0] and i < rec2[2] and j > rec2[1] and j < rec2[3]:return Truej += prec*xi += prec*yprec /= 2return False389. 找不同
class Solution:def findTheDifference(self, s, t):""":type s: str:type t: str:rtype: str"""un = s + tdif = 0for i in un:dif ^= ord(i)return chr(dif)191. 位1的个数
class Solution(object):def hammingWeight(self, n):""":type n: int:rtype: int"""return bin(n).count('1')205. 同构字符串
class Solution:def isIsomorphic(self, s, t):""":type s: str:type t: str:rtype: bool"""# 遍历s,t,如果s中字符不在映射中,则在字典建立映射,如果存在且不满足映射,则异构d = dict()for i in range(len(s)):if s[i] in d:if t[i] != d[s[i]]:return Falseelse:d[s[i]] = t[i]# 字典的值必须不同,否则是虚假的映射if len(set(i for i in d.values())) != len(d):return Falsereturn True225. 用队列实现栈
from collections import dequeclass MyStack(deque):def __init__(self):"""Initialize your data structure here."""passdef push(self, x):"""Push element x onto stack.:type x: int:rtype: void"""self.append(x)def pop(self):"""Removes the element on top of the stack and returns that element.:rtype: int"""# 重写了pop(),需要调用父类的pop()return super(MyStack, self).pop()def top(self):"""Get the top element.:rtype: int"""return self[-1]def empty(self):"""Returns whether the stack is empty.:rtype: bool"""return False if len(self) else True# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()520. 检测大写字母
# class Solution:
#     def detectCapitalUse(self, word):
#         """
#         :type word: str
#         :rtype: bool
#         """
#         return word.upper() == word or word.lower() == word or \
#                 word.capitalize() == word
#788. 旋转数字
# class Solution:
#     def rotatedDigits(self, N):
#         """
#         :type N: int
#         :rtype: int
#         """
#         count = 0
#         ls_all = ['0', '1', '8', '2', '5', '6', '9']
#         ls_any = ['2', '5', '6', '9']
#         for i in range(1, N+1):
#             s = str(i)
#             if all((al in ls_all for al in s)) and any((an in ls_any for an in s)):
#                 count += 1
#         return count9. 回文数
# class Solution:
#     def isPalindrome(self, s):
#         """
#         :type s: str
#         :rtype: bool
#         """
#         s = ''.join([i.lower() for i in s if i >= '0' and i <= '9' or \
#                 i >= 'A' and i <= 'Z' or i >= 'a' and i <= 'z'
#               ])
#         return s == s[::-1]345. 反转字符串中的元音字母
# class Solution:
#     def reverseVowels(self, s):
#         """
#         :type s: str
#         :rtype: str
#         """
#         vowels = 'aeiouAEIOU'
#         i = 0
#         j = len(s) - 1
#         s = list(s)
#         while i < j:
#             if s[i] in vowels:
#                 if s[j] in vowels:
#                     pass
#                     temp = s[j]
#                     s[j:j+1] = s[i:i+1]
#                     s[i:i+1] = temp
#                     i += 1
#                     j -= 1
#                 else:
#                     j -= 1
#             else:
#                 i += 1
#         return ''.join(s)459. 重复的子字符串
# class Solution:
#     def repeatedSubstringPattern(self, s):
#         """
#         :type s: str
#         :rtype: bool
#         """
#         ls = []
#         # 转化成素数问题
#         for i in range(1, len(s)):
#             if len(s) % i == 0:
#                 ls.append(i)
#         for i in ls[::-1]:
#             if s.replace(s[:i], '') == '':
#                 return True
#         return False
#         # return (s+s)[1:-1].find(s) != -1941. 有效的山脉数组
# class Solution:
#     def validMountainArray(self, A):
#         """
#         :type A: List[int]
#         :rtype: bool
#         """
#         if len(A) < 3:
#             return False
#         index_max = A.index(max(A))
#         for i in range(index_max):
#             if A[i] >= A[i+1]:
#                 return False
#         for i in range(index_max, len(A)-1):
#             if A[i] <= A[i+1]:
#                 return False
#         return True876. 链表的中间结点
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def middleNode(self, head):""":type head: ListNode:rtype: ListNode"""
#         # 两次暴力遍历法
#         count = 0
#         p = head
#         while p.next:
#             count += 1
#             p = p.next#         i = 0
#         p = head
#         while i < count/2:
#             p = p.next
#             i += 1
#         return p# # 双指针法# p = head# q = head# # 只有两个节点的情况,返回第二个结点# if p.next:#     if p.next.next is None:#         return q.next# # 三个及以上节点的情况# while p.next and p.next.next:#     # 奇数节点的情况#     p = p.next.next#     q = q.next#     # 偶数节点的情况#     if p.next and p.next.next is None:#         q = q.next# return q# 双指针法(代码简化)p = headq = head# 只有两个节点的情况,返回第二个结点if p.next:if p.next.next is None:return q.next# 三个及以上节点的情况while p.next:# 奇数节点的情况p = p.next.nextq = q.next# 偶数节点的情况if p is None:breakreturn q234. 回文链表
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def isPalindrome(self, head):""":type head: ListNode:rtype: bool"""# # 脑残全部入栈法,看栈反转后是否变化# p = head# ls = []# while p:#     ls.append(p.val)#     p = p.next# return ls[::-1] == ls# 双指针法(p/q快慢指针遍历,反转前半部分链表,p/n双指针从中间遍历判断)# 链表长度为0,1,2,3的情况if head is None:return Trueelif head.next is None: return Trueelif head.next.next is None: return head.val == head.next.valelif head.next.next.next is None:return head.val == head.next.next.val# 快指针判断节点是奇数/偶数,慢指针记录中间节点位置,长度5则移动3步,长度6则移动3步p = headq = headwhile p.next:if p.next.next is None:breakp = p.next.nextq = q.nextdef reverse_prev_half(): # 反转前半部分c = headn = headp = Nonewhile p != q:n = c.nextc.next = pp = cc = nreturn p,n# 奇数的情况if p and p.next is None:p,n = reverse_prev_half()p = p.next # 最中间节点不用判断,先前移一下while p and n: # 这里0改成1,奇数的情况少移动一步再判断if p.val != n.val:return Falsep = p.nextn = n.nextreturn True# 偶数的情况else:p,n = reverse_prev_half()while p and n:if p.val != n.val:return Falsep = p.nextn = n.nextreturn True206. 反转链表
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def reverseList(self, head):""":type head: ListNode:rtype: ListNode"""p = Nonec = headn = headwhile c:n = c.nextc.next = pp = cc = nreturn p237. 删除链表中的节点
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def deleteNode(self, node):""":type node: ListNode:rtype: void Do not return anything, modify node in-place instead."""node.val = node.next.valnode.next = node.next.next232. 用栈实现队列
from collections import deque
class MyQueue(deque):def __init__(self):"""Initialize your data structure here."""def push(self, x):"""Push element x to the back of queue.:type x: int:rtype: void"""self.append(x)def pop(self):"""Removes the element from in front of queue and returns that element.:rtype: int"""return super(MyQueue, self).popleft()def peek(self):"""Get the front element.:rtype: int"""return self[0]def empty(self):"""Returns whether the queue is empty.:rtype: bool"""return len(self)==0# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()92. 反转链表 II
class Solution:def reverseBetween(self, head, m, n):""":type head: ListNode:type m: int:type n: int:rtype: ListNode"""# 不用改变的情况if m==n:return head# 几种边界条件暂未处理...# 找到反转子段前的节点beforeprev = headcur = headnxst = headbefore = headi = 1while i < m:i += 1before = curcur = cur.next# prev,cur指向子段第1,2个节点prev = curcur = cur.next# 反转子段while i < n:  # i=2...3<4i += 1nxst = cur.nextcur.next = prevprev = curcur = nxst# 找到反转子段后的节点after = cur# 连接子段和原链表before.next.next = afterbefore.next = prevreturn head93. 实现strStr()
class Solution:def strStr(self, haystack, needle):""":type haystack: str:type needle: str:rtype: int"""return haystack.find(needle)94. 旋转数组
class Solution:def rotate(self, nums, k):""":type nums: List[int]:type k: int:rtype: void Do not return anything, modify nums in-place instead."""# # 脑残单步移动法# while k > 0:#     a = nums[-1]#     i = len(nums) - 1#     while i > 0:#         nums[i] = nums[i - 1]#         i -= 1#     nums[0] = a#     k -= 1# 切片赋值法,n向左移,-n向右移n = k%len(nums)nums[:] = nums[-n:]+nums[:-n]  95. 岛屿的周长
class Solution:def islandPerimeter(self, grid):""":type grid: List[List[int]]:rtype: int"""# 将岛屿周围用0补齐,暴力判断for g in grid:g[:] = [0] + g[:] + [0]edge = [0 for i in range(len(grid[0]))]grid[:] = [edge] + grid[:] + [edge]length = 0for i in range(1, len(grid)-1):for j in range(1, len(g)-1):if grid[i][j] == 1:if grid[i-1][j] == 0:length += 1if grid[i+1][j] == 0:length += 1if grid[i][j-1] == 0:length += 1if grid[i][j+1] == 0:length += 1return length96. Fizz Buzz
class Solution:def fizzBuzz(self, n):""":type n: int:rtype: List[str]"""ls = []for i in range(1, n + 1):if i%15 == 0:ls.append('FizzBuzz')elif i%5 == 0:ls.append('Buzz')elif i%3 == 0:ls.append('Fizz')else:ls.append(str(i))return ls97. 交替位二进制数
class Solution:def hasAlternatingBits(self, n):""":type n: int:rtype: bool"""# 左移与原数的二进制位异或,则应该是全部位数都是1,而最后一位是0,再右移,再判断是否每一位都是1for i in bin(((n<<1)^n)>>1).split('b')[1]:if i == '0':return Falsereturn True98. 自除数
class Solution:def selfDividingNumbers(self, left, right):""":type left: int:type right: int:rtype: List[int]"""ls = []for n in range(left, right+1):for i in str(n):if i == '0':breakif n % (int(i)) != 0:breakelse:ls.append(n)return ls99. Nim游戏
class Solution:def canWinNim(self, n):""":type n: int:rtype: bool"""if n%4 == 0:return Falseelse:return True100. 重复 N 次的元素
class Solution:def repeatedNTimes(self, A):""":type A: List[int]:rtype: int"""for a in A:if A.count(a)==len(A)/2:return a101. 汉明距离
class Solution:def hammingDistance(self, x, y):""":type x: int:type y: int:rtype: int"""return bin(x^y).count('1')929. 独特的电子邮件地址
# 字符串切片做法
class Solution:def numUniqueEmails(self, emails):""":type emails: List[str]:rtype: int"""u = set()for e in emails:local = e[:e.index('@')]domain = e[e.index('@'):]if '.' in local:local = local.replace('.', '')if '+' in local:local = local[:local.index('+')]res = local + domainif res not in u:u.add(res)return len(u)# re做法
class Solution:def numUniqueEmails(self, emails):""":type emails: List[str]:rtype: int"""import reu = set()for e in emails:e = re.sub('[+].*?[@]', '@', e) # 替换'+'replace = re.search(re.compile('[.].*?[@]'), e) # 查找'.'if replace is not None:e = re.sub('[.].*?[@]', re.sub('[.]', '', replace.group()), e) # 如果有'.',则将含有'.'的部分,替换为该部分去掉点的干净子串if e not in u:u.add(e)return len(u)441. 排列硬币
class Solution(object):def arrangeCoins(self, n):""":type n: int:rtype: int"""# 直接判断# i = 1# while i <= n:#     if i*(i+1)/2 > n:#         return i-1#     i += 1# return n# 求根公式a = 1b = 1c = -2*nx1 = ((-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a))return int(x1)442. 汉明距离总和class Solution:def totalHammingDistance(self, nums):""":type nums: List[int]:rtype: int"""# 超出时间限制n = 0for i in range(len(nums)):for j in range(i+1, len(nums)):n += bin(nums[i]^nums[j]).count('1')return n# 对每一个数的相同位置的上的二进制位进行判断的思路if nums == []:return 0ln = len(nums)m_ln = len(bin(max(nums)).replace('0b',''))nums = [bin(i).replace('0b','').zfill(m_ln) for i in nums]return sum([[num[i] for num in nums].count('1') * (ln-[num[i] for num in nums].count('1')) for i in range(m_ln)]) 67. 二进制求和
class Solution:def addBinary(self, a, b):""":type a: str:type b: str:rtype: str"""return bin(int('0b'+a,2)+int('0b'+b,2)).split('b')[1]409. 最长回文串
class Solution:def longestPalindrome(self, s):""":type s: str:rtype: int"""n = 0odds = Nonefor i in set(s):c = s.count(i)if c%2 == 0:n += celse:n += c-1odds = cif odds is not None:n += 1return n697. 数组的度
class Solution:def findShortestSubArray(self, nums):""":type nums: List[int]:rtype: int"""rnums = nums[::-1]ln = len(nums)cs = []for i in set(nums):cs.append((i, nums.count(i), ln-nums.index(i)-rnums.index(i)))cs = sorted(cs, key=lambda x: x[1], reverse=True)n = 0p = Truemaxc = cs[0][1]for i in cs:if i[1] < maxc:breakt = i[2]if p:n = tp = Falseif n > t:n = treturn n796. 旋转字符串
class Solution:def rotateString(self, A, B):""":type A: str:type B: str:rtype: bool"""if len(A)!=len(B):return Falseif A=='':return Truei = 0while i<len(A):p = B.find(A[i:])if p==0:if A[i:]+A[:i]==B:return Truei += 1return False263. 丑数
class Solution:def isUgly(self, num):""":type num: int:rtype: bool"""if num <= 0:return Falsefor i in (2,3,5):while num%i == 0:num /= iif num == 1:return Truereturn num == 1242. 有效的字母异位词
class Solution:def isAnagram(self, s, t):""":type s: str:type t: str:rtype: bool"""s1 = set(s)t1 = set(t)if s1 != t1:return Falsefor i in s1:if s.count(i) != t.count(i):return Falsereturn True917. 仅仅反转字母
class Solution:def reverseOnlyLetters(self, S):""":type S: str:rtype: str"""s = []for i in S:if i.isalpha():s.append(i)s = ''.join(s)[::-1] # 反转后的纯字母ls = []j = 0for i in range(len(S)):if S[i].isalpha():ls.append(s[j])j += 1else:ls.append(S[i])return ''.join(ls)628. 三个数的最大乘积
class Solution:def maximumProduct(self, nums):""":type nums: List[int]:rtype: int"""nums.sort()a = nums[0]b = nums[1]c = nums[-3]d = nums[-2]e = nums[-1]return a*b*e if a<0 and b<0 and a*b > c*d and e>0 else c*d*e342. 4的幂
class Solution:def isPowerOfFour(self, num):""":type num: int:rtype: bool"""# 直接处理# while num%4==0 and num!=1 and num!=0:#     num /= 4# return num==1# 使用bin函数s = bin(num)return s[2] == '1' and s.count('0')%2==1 and s.count('1')==1# 或者 return s[2] == '1' and s.count('1')==1 and len(s)%2==1 383. 赎金信
class Solution:def canConstruct(self, ransomNote, magazine):""":type ransomNote: str:type magazine: str:rtype: bool"""for c in set(ransomNote):if ransomNote.count(c) > magazine.count(c):return Falsereturn True415. 字符串相加
class Solution:def addStrings(self, num1, num2):""":type num1: str:type num2: str:rtype: str"""if len(num1) < len(num2):b, s = num2, num1else:s, b = num2, num1ln = len(b)ls = [0]lb = [0]# 形成数组,用0补全短的字符串,以及在前面加上额外的一位0,防止进位for i in range(ln):lb.append(int(b[i]))if i < ln - len(s):ls.append(0)else:ls.append(int(s[i - ln + len(s)]))# 存储进位的数据,初始全置0sum = [0 for i in range(ln+1)]i = lnwhile i>0:# 每一位的总加和,两个数字的位+上次的进位s = ls[i]+lb[i]+sum[i]if s>=10: # 如果超过10则该位置除10的余数,该位的高一位加1sum[i] = s%10sum[i-1] += 1else:   # 否则,直接把总和给该位sum[i] = si -= 1# 直接暴力将列表转成字符串,如果有,去掉前面位的0sum = str(sum).replace(', ','')[1:-1]if sum[0]=='0':sum = sum[1:]return sum278. 第一个错误的版本
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):class Solution:def firstBadVersion(self, n):""":type n: int:rtype: int"""le = 0ri = nwhile le<ri:md = int((le+ri)/2)if isBadVersion(md): # 如果中间是错误,则去md前面找,否则去md的后面mid+1开始找ri = mdelse:le = md+1return le58. 最后一个单词的长度
class Solution:def lengthOfLastWord(self, s):""":type s: str:rtype: int"""import res = s.strip() # 先去掉首尾的' ',如果为空返回0if not s:  return 0if ' ' not in s: # 先判断,如果是单个单词,则直接返回单词长度,否则后面匹配的话,会拖慢速度return len(s)ss = re.search(re.compile(' \w+[ ]?$'),s)return len(ss.group().strip())622. 设计循环队列
class MyCircularQueue:def __init__(self, k):"""Initialize your data structure here. Set the size of the queue to be k.:type k: int"""k += 1 # 多出来一个额外位置None,队列为空时,tail回到head位置,队列为满时,tail被推到head前面一个位置,此位置为None不存数据self.items = [None for i in range(k)]self.head = 0self.tail = 0self.n = kdef enQueue(self, value):"""Insert an element into the circular queue. Return true if the operation is successful.:type value: int:rtype: bool"""if self.isFull():return Falseelse:self.items[self.tail] = valueself.tail = (self.tail+1)%self.nreturn Truedef deQueue(self):"""Delete an element from the circular queue. Return true if the operation is successful.:rtype: bool"""if self.isEmpty():return Falseself.items[self.head] = Noneself.head = (self.head + 1) % self.nreturn Truedef Front(self):"""Get the front item from the queue.:rtype: int"""if self.isEmpty():return -1return self.items[self.head]def Rear(self):"""Get the last item from the queue.:rtype: int"""if self.isEmpty():return -1if self.tail == 0:i = self.n-1else:i = self.tail-1return self.items[i]def isEmpty(self):"""Checks whether the circular queue is empty or not.:rtype: bool"""if self.head == self.tail:return Truereturn Falsedef isFull(self):"""Checks whether the circular queue is full or not.:rtype: bool"""if (self.tail+1)%self.n == self.head:return Truereturn False# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()485. 最大连续1的个数
class Solution:def findMaxConsecutiveOnes(self, nums):""":type nums: List[int]:rtype: int"""s = str(nums).replace('[','').replace(']','').replace(', ','').split('0') # 得到原始二进制,按0切为只有1的连续子串return len(max(s))  # 最大的子串即是最长的,返回其长度即可500. 键盘行
class Solution:def findWords(self, words):""":type words: List[str]:rtype: List[str]"""tabs = 'qwertyuiop'caps = 'asdfghjkl'shift = 'zxcvbnm'ls = []for word in words:w = word.lower()  # 使用小写来减少判断for c in w: if c not in tabs:breakelse:   # 如果没有break,则进入else,那么就在同一行ls.append(word) continue  # 如果在某一行,则继续下一个单词判断for c in w:if c not in caps:breakelse:ls.append(word)continuefor c in w:if c not in shift:breakelse:ls.append(word)return ls509. 斐波那契数
class Solution:def fib(self, N):""":type N: int:rtype: int"""a = 0b = 1ls =[0,1]for i in range(N):a,b = b,a+bls.append(b)return ls[N]541. 反转字符串 II
class Solution:def reverseStr(self, s, k):""":type s: str:type k: int:rtype: str"""ls = []n = 0for i in range(0,len(s),k):if n == 1: # 如果是偶数位,则反转,否则不反转ls.append(s[i:i+k])n = 0else:ls.append(s[i:i+k][::-1])n = 1return ''.join(ls)551. 学生出勤记录 I
class Solution:def checkRecord(self, s):""":type s: str:rtype: bool"""return s.count('A')<2 and s.count('LLL')<1557. 反转字符串中的单词 III
class Solution:def reverseWords(self, s):""":type s: str:rtype: str"""return ' '.join(ss[::-1] for ss in s.split(' '))566. 重塑矩阵
class Solution:def matrixReshape(self, nums, r, c):""":type nums: List[List[int]]:type r: int:type c: int:rtype: List[List[int]]"""nums2=[]for i in nums:nums2+=i # 先转换为一维矩阵if r*c != len(nums2): # 元素个数必须相等return numsreturn [nums2[i:i+c] for i in range(0,r*c,c)] # 返回生成的矩阵905. 按奇偶排序数组
class Solution:def sortArrayByParity(self, A):""":type A: List[int]:rtype: List[int]"""return [i for i in A if i%2==0] + [i for i in A if i%2!=0]922. 按奇偶排序数组 II
class Solution:def sortArrayByParityII(self, A):""":type A: List[int]:rtype: List[int]"""odds =  (i for i in A if i%2==0)evens = (i for i in A if i%2!=0)ls = []for i in range(int(len(A)/2)):ls.append(next(odds))ls.append(next(evens))return ls258. 各位相加
class Solution:def addDigits(self, num):""":type num: int:rtype: int"""while len(str(num))>1:num = sum(int(i) for i in str(num))return num973. 最接近原点的 K 个点
class Solution:def kClosest(self, points, K):""":type points: List[List[int]]:type K: int:rtype: List[List[int]]"""points = sorted(points,key=lambda p:p[0]**2+p[1]**2)  # 速度不稳定,善用lambda函数return points[:K]387. 字符串中的第一个唯一字符
class Solution:def firstUniqChar(self, s):""":type s: str:rtype: int"""t = set() # 使用集合存储已检查过的字符,利用散列表加速for c in s:if c not in t:  # 如果没有判断过,则判断,否则跳过t.add(c)i = s.find(c) j = s.rfind(c)  # 如果左查和右查索引一样,则就是唯一的if i==j:return ireturn -1804. 唯一摩尔斯密码词
class Solution(object):def uniqueMorseRepresentations(self, words):""":type words: List[str]:rtype: int"""d = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]s = set()for w in words:temp = []for c in w:temp.append(d[ord(c)-97])temp = ''.join(temp)if temp not in s:s.add(temp)return len(s)824. 山羊拉丁文
class Solution(object):def toGoatLatin(self, S):""":type S: str:rtype: str"""d = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}S = S.split(' ')rS = []for i in range(len(S)):s = S[i]if s[0] in d:rS.append(s+'ma'+'a'*(i+1))else:rS.append(s[1:]+s[0]+'ma'+'a'*(i+1))return ' '.join(rS)645. 错误的集合
class Solution(object):def findErrorNums(self, nums):""":type nums: List[int]:rtype: List[int]"""s = set()r = []for n in nums:if n not in s:s.add(n)else:r.append(n)s = list(s)s.sort()for i in range(len(s)):if s[i]!=i+1:r.append(i+1)breakelse:r.append(i+2)return r69. x 的平方根
class Solution(object):def mySqrt(self, x):""":type x: int:rtype: int"""if x==0:return 0# n = 10**(len(str(x))/2) # 对于很大的数,迅速找到根的位数n = x/2+1while abs(n*n-x)>1:n = n-(n-x/n)/2return int(n)819. 最常见的单词
class Solution:def mostCommonWord(self, paragraph, banned):""":type paragraph: str:type banned: List[str]:rtype: str"""paragraph = paragraph.replace('!',' ').replace('?',' ').replace(',',' ').replace('.',' ').replace(';',' ').replace("'",' ')paragraph = paragraph.lower().split(' ')s = set(paragraph)if ' ' in s:s.remove(' ')if '' in s:s.remove('')s = list(s)s = sorted(s,key=lambda x:paragraph.count(x),reverse=True)for w in s:if w not in banned:return w724. 寻找数组的中心索引
class Solution:def pivotIndex(self, nums):""":type nums: List[int]:rtype: int"""s = sum(nums)  # 总和,这个很重要a = 0  # 遍历中累加的和for i in range(len(nums)):if a*2 + nums[i]== s:return ia += nums[i]return -1844. 比较含退格的字符串
class Solution:def backspaceCompare(self, S, T):""":type S: str:type T: str:rtype: bool"""ss = []tt = []for s in S:if s!='#':ss.append(s)elif len(ss)!=0:ss.pop()for t in T:if t!='#':tt.append(t)elif len(tt)!=0:tt.pop()return ss==tt496. 下一个更大元素 I
class Solution:def nextGreaterElement(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]"""nums3= []for i in nums1:j = nums2.index(i)for k in range(j+1,len(nums2)):if nums2[k]>i:nums3.append(nums2[k])breakelse:nums3.append(-1)return nums3704. 二分查找  #比较简洁的代码,自己写的太繁琐了
class Solution:def search(self, nums, target):""":type nums: List[int]:type target: int:rtype: int"""i = 0j = len(nums) - 1while i<=j:k = (i+j)//2if nums[k]==target:return k  # 如果找到,直接返回kelif nums[k]<target:i = k+1  # i,j基于k的移动作为循环趋向结束的条件else:j = k-1return -1 # 如果没有查到,即完成循环,返回-1896. 单调数列
class Solution:def isMonotonic(self, A):""":type A: List[int]:rtype: bool"""if A[0]>A[-1]:  # 如果递减,则将数列反转,当做是递增来判断A=A[::-1]i = 0j = len(A)-1Ai = A[i]Aj = A[j]while i<=j:  # 需要加上=,否则可能在i,j中间位置的数未经过与i,j位置的数进行对比就退出if A[i]>A[j]:  # 如果前面的数大于后面,Falsereturn Falseif Ai > A[i]:  # 如果前指针的数比它的前一个数小(或后指针的数比它的后一个数大), Falsereturn Falseelse:          # 否则继续循环,趋向于结束进行判断Ai = A[i]i += 1if Aj < A[j]:return Falseelse:Aj = A[j]j -= 1return True  # 如果判断了所有数,True448. 找到所有数组中消失的数字
class Solution:def findDisappearedNumbers(self, nums):""":type nums: List[int]:rtype: List[int]"""# return list(set(range(1,len(nums)+1)) - set(nums))# ls = [i for i in nums] # 复制副本# for i in nums:#     ls[i-1] = 0  # 原数组中的元素本应按顺序排列在索引-1的位置上,如果副本中哪个对应位置有元素,则标为0# return [i+1 for i in range(len(ls)) if ls[i]>0]for i in nums:if nums[abs(i)-1] >0:nums[abs(i)-1] *=-1  # 用abs绝对值保护元素,用转为负数标记元素的占位return [i+1 for i in range(len(nums)) if nums[i]>0]35. 搜索插入位置
class Solution:def searchInsert(self, nums, target):""":type nums: List[int]:type target: int:rtype: int"""for i in range(len(nums)):if nums[i]>=target:  # 找到索引,则返回return ielse:return i+1  # 找不到则返回数组长度599. 两个列表的最小索引总和
class Solution:def findRestaurant(self, list1, list2):""":type list1: List[str]:type list2: List[str]:rtype: List[str]"""ls=[]s = set(list1)&set(list2)for i in s:t = [list1.index(i)+list2.index(i),i]ls.append(t)ls = sorted(ls,key=lambda x:x[0])t = ls[0][0]rls = []for i in ls:if i[0]==t:rls.append(i[1])else:breakreturn rls268. 缺失数字
class Solution:def missingNumber(self, nums):""":type nums: List[int]:rtype: int"""# 利用相加和sumNums = (0+len(nums)+1)*len(nums)/2return int(sumNums - sum(nums))# 利用异或排除索引未出现的n = len(nums)  for i in range(len(nums)):n = n^nums[i]^ireturn n# 同448. 找到所有数组中消失的数字flag = Trueln = len(nums)for i in nums:if abs(i)<ln:nums[abs(i)] *= -1  if nums[abs(i)]==0:flag = Falseif flag:if 0 not in nums:return 0else:return nums.index(0)for i in range(ln):if nums[i]>0:return ireturn ln290. 单词模式
class Solution:def wordPattern(self, pattern, str):""":type pattern: str:type str: str:rtype: bool"""str = str.split(" ")if len(str) != len(pattern):  # 如果键值对长度相等,则继续判断return Falsed = dict(zip(pattern, str))str_set = set(str)# 如果映射长度等于字符串集合的总长度,也等于字典值集合的总长度,则就是唯一对应的if len(d) == len(str_set)==len(set(i for i in d.values())):return Truereturn False367. 有效的完全平方数
class Solution:def isPerfectSquare(self, num: int) -> bool:count = len(bin(num)) - 2a = 2 ** (int(count / 2))if num > a ** 2:a *= 2r = awhile r * r > num:r = (r + num / r) // 2return r * r == num747. 至少是其他数字两倍的最大数
class Solution:def dominantIndex(self, nums: List[int]) -> int:if len(nums)==1:return 0m = nums[0]index = 0i = 0# 两次遍历,取最大值和次最大值,以及对应索引while i<len(nums):if m<nums[i]:m = nums[i]index = ii+=1if m == nums[0]:m2 = nums[1]index2 = 1else:m2 = nums[0]index2 = 0i = 0while i<len(nums):if m2<nums[i] and  i != index:m2 = nums[i]index2 = ii+=1return index if m>=2*m2 else -1

sql部分

595. 大的国家
# Write your MySQL query statement below
select name,population,area from World where area>3000000 or population>25000000;620. 有趣的电影
# Write your MySQL query statement below
-- 先选id比description快
select * from cinema where id%2!=0 and description!='boring' order by rating desc;596. 超过5名学生的课
# Write your MySQL query statement below
select class from courses group by class having count(distinct student)>=5;196. 删除重复的电子邮箱
# Write your MySQL query statement below
delete from Person where Id not in(                     # 找出最终留下的那些Id,把其他Id对应的记录删除select Id from (select Id,Email from (select Id,Email from Person group by Id,Email # 先按Id排序,再按Email排序分组,这样能保证留下的Email一定是最小的Id) as e                                        # 每个派生出的表都必须取别名,否则报错group by Email) as f                              # 然后按Email分组,自然会留下最小的Id
);183. 从不订购的客户
# Write your MySQL query statement below
select Name as Customers from Customers where(Customers.Id not in(select CustomerId from Orders)
);181. 超过经理收入的员工
# Write your MySQL query statement below
select e1.Name as Employee from Employee e1,Employee e2  # 自连接
where e1.ManagerId is not Null      # 员工是一定有经理,经理可以没有经理
and e1.ManagerId = e2.Id            # 将两个别名表根据条件连接起来
and (e1.Salary > e2.Salary)         # 进行判断
;197. 上升的温度
# Write your MySQL query statement below
select w1.Id as Id from Weather w1,Weather w2
where DATEDIFF(w1.RecordDate,w2.RecordDate)=1 # 使用DATEDIFF比较日期,使用减法'-'报错
and w1.Temperature > w2.Temperature
;182. 查找重复的电子邮箱
# Write your MySQL query statement below
select Email from Person group by (Email) having count(Email)>1
; # 先分组group by,再根据条件having count筛选176. 第二高的薪水
# Write your MySQL query statement below
select max(Salary) as SecondHighestSalary from Employee # 然后max得到第二大值
where Salary not in (select max(Salary) as HighestSalary from Employee)
;# 首先not in去掉最大值

给定一个数组 strs,其中的数据都是字符串,给定两个字符串 str1,str2。如果这两个字符串都在 strs数组中,就返回它们之间的最小距离;如果其中任何一个不在里面,则返回 -1;如果两个字符串相等,则返回 0。
例如:给定[‘’,’3’,’’,’5’,’10’,’9’,’7’,’1’,’’],再给定两个字符串’ ‘和’9’,通过函数求得返回值 3。

def min_distance(ss, s1, s2):if s1 not in ss or s2 not in ss:return -1if s1 == s2:return 0index1 = []for i in range(len(ss)):if ss[i] == s1:index1.append(i)index2 = []for i in range(len(ss)):if ss[i] == s2:index2.append(i)# 获取两个元素的索引,存入索引列表,并将其合并为一个索引总列表,并排序index3 = sorted(index1+index2)# 存储索引差,即字符串距离step = []for i in range(len(index3)-1):# 如果索引总列表中相邻两个元素索引分别为两个元素的索引,则将其添加到索引差列表中if index3[i] in index1 and index3[i+1] in index2 or \index3[i] in index2 and index3[i+1] in index1:step.append(index3[i+1] - index3[i])# 找出索引差最小,即字符串最小距离print(min(step))

测试用例:

s = ['*', '3', '*', '5', '10', '9', '7', '3', '*']
s11 = '3'
s22 = '9'
min_distance(s, s11, s22)

100 0000次运行,时间约为2.70s,原文代码为3.67s,使用标记的办法改进,时间1.78s

def min_distance2(ss, s1, s2):if s1 not in ss or s2 not in ss:return -1if s1 == s2:return 0# 双标记id1 = -1id2 = -1step = []for i in range(len(ss)):if ss[i] == s1:id1 = ielif ss[i] == s2:id2 = iif id1 == -1 or id2 == -1:continueelse:# 双标记的差的绝对值即为距离step.append(abs(id1-id2))# print(min(step))

最大公约数

# 递归版
def gcd(a, b):return a if b == 0 else gcd(b, a % b)# 循环版
def gcd(a, b):while b != 0:a, b = b, a % breturn a

生成随机字符串
查询字符串出现次数最多字符

import string
import random# 获取长度为1000的随机字符串
pattern = string.ascii_letters + string.digits + string.punctuation
s = "".join((random.choice(pattern) for i in range(1000)))# 获取次数最多字符和个数
s = ''''''
d = {}
for c in s:d[c] = d.get(c, 0) + 1
ls = list(d)
ls.sort(key=d.get, reverse=True)
print(ls[0], d.get(ls[0]))
s = '''https://www.sogo.com/ale.html
https://www.qq.com/3asd.html
https://www.sogo.com/teoans.html
https://www.bilibili.com/2
https://www.sogo.com/asd_sa.html
https://y.qq.com/
https://www.bilibili.com/1
https://dig.chouti.com/
https://www.bilibili.com/imd.html
https://www.bilibili.com/'''
d = {}
# 拿到域名url
ls = [url.split("/")[2] for url in s.split("\n")]
# 字典计数
for url in ls:d[url] = d.get(url, 0) + 1
# 安装计数排序输出
for k, v in sorted(d.items(), key=lambda x: x[1], reverse=True):print(v, k)

【代码】LeetCode刷题Python版相关推荐

  1. LeetCode刷题Python实录

    使用Python的LeetCode刷题 前言 题目 1408. 数组中的字符串匹配 508. 出现次数最多的子树元素和 1089. 复写零 剑指 Offer 14- I. 剪绳子 1175. 质数排列 ...

  2. 【Leetcode刷题Python】生词本单词整理

    1 题目 小A最近在努力学习英语.小A有一本生词本,专门用来记录见到的生词.每次小A看到一个自己不认识的单词时,就会把这个生词抄写到生词本上.经过几个月的学习之后,小A想对这个生词本上的单词进行整理. ...

  3. 【Leetcode刷题Python】40. 组合总和 II

    1 题目 给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合. candidates 中的每个数字在每 ...

  4. 【Leetcode刷题Python】494. 目标和

    1 题目 给你一个整数数组 nums 和一个整数 target . 向数组中的每个整数前添加 '+' 或 '-' ,然后串联起所有整数,可以构造一个 表达式 : 例如,nums = [2, 1] ,可 ...

  5. 【Leetcode刷题Python】516. 最长回文子序列

    1 题目 给你一个字符串 s ,找出其中最长的回文子序列,并返回该序列的长度. 子序列定义为:不改变剩余字符顺序的情况下,删除某些字符或者不删除任何字符形成的一个序列. 示例 1: 输入:s = &q ...

  6. 【Leetcode刷题Python】714. 买卖股票的最佳时机含手续费

    1 题目 给定一个整数数组 prices,其中 prices[i]表示第 i 天的股票价格 :整数 fee 代表了交易股票的手续费用. 你可以无限次地完成交易,但是你每笔交易都需要付手续费.如果你已经 ...

  7. 【Leetcode刷题Python】55. 跳跃游戏

    1 题目 给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 . 数组中的每个元素代表你在该位置可以跳跃的最大长度. 判断你是否能够到达最后一个下标. 示例 1: 输入:nums = [2 ...

  8. 【Leetcode刷题Python】416. 分割等和子集

    1 题目 给你一个 只包含正整数 的 非空 数组 nums .请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等. 示例 1: 输入:nums = [1,5,11,5] 输出:true ...

  9. 【Leetcode刷题Python】174. 地下城游戏

    1 题目 一些恶魔抓住了公主(P)并将她关在了地下城的右下角.地下城是由 M x N 个房间组成的二维网格.我们英勇的骑士(K)最初被安置在左上角的房间里,他必须穿过地下城并通过对抗恶魔来拯救公主. ...

最新文章

  1. 服务器开机只显示cdm,电脑开机黑屏出现cdm.exe对话框怎么处理?!我的扣扣
  2. thankpad p15改善大风扇的转动
  3. vivado VIO (virtual input output)虚拟IO的使用
  4. 关于Plos one 和 SR
  5. 最简单的docker教程:在docker里运行nginx服务器
  6. !!!!Linux系统开发 系列 4 进程资源 环境 fork()子进程 wait() waitpid()僵尸 孤儿进程...
  7. Python中的字符串与字符编码:编码和转换问题
  8. 文字穿插在海报设计中的不同用法
  9. mysql集群搭建.pdf,内容太过真实
  10. 批处理使用完文件后释放_windows 下使用批处理执行 postgresql 命令行操作
  11. 大数据分析平台在企业运营中的作用
  12. UE4+Cesium
  13. 遥感原理与应用_专家报告 | 叶绿素荧光卫星遥感—原理与应用
  14. 捏着鼻子也要吃? 吃蔬菜几大误区盘点
  15. 数学建模国赛编程手必备工具
  16. METIS 安装过程
  17. c语言感叹号放最后用法,感叹号的用法和注意事项
  18. 考博英语题型及难度分析
  19. php 读取指定路径照片,必应每日图片合集程序之php读取指定目录图片
  20. SEO常用MATE整理

热门文章

  1. 从数据手册看产品更新换代后的相关情况
  2. 贪心算法最短路径java_贪心算法-单源最短路径
  3. 学计算机房空调功率是多少为好,空调功率是多少—空调功率一般有多少呢
  4. 表格锁定头和列中间内容展示
  5. AI一般是用来制作什么的
  6. mybatis引入依赖包
  7. Linux安装pillow
  8. MacBook Air 2014 os x 10.9.5无法升级的问题
  9. Python3--->使用通配符删除文件
  10. 关于goole浏览器无法访问网页问题