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]] = 0
seconddomain['.'.join(domain.split('.')[:])] = 0
if len(domain.split('.')) == 3:
topdomain[domain.split('.')[2]] = 0
seconddomain['.'.join(domain.split('.')[1:])] = 0
thirddomain['.'.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] += count
for second in seconddomain:
if domain.endswith(second):
seconddomain[second] += count
for third in thirddomain:
if domain.endswith(third):
thirddomain[third] += count
return [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_nums
second = min_nums
third = min_nums
for n in nums:
if first < n:
first = n
for n in nums:
if n < first and second < n:
second = n
for n in nums:
if n < second and third < n:
third = n
if second == third:
return first
else:
return third
344. 反转字符串
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') == 1
217. 存在重复元素
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 i
136. 只出现一次的数字
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num = 0
for i in nums:
num = num ^ i
return num
88. 合并两个有序数组
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 += 1
nums1.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 = 0
b = 0
for i in range(len(nums)):
# 如果快慢不同,则慢指针后移,再赋快指针的值
if nums[a] != nums[b]:
a += 1
nums[a] = nums[b]
# 快指针从头移动到尾
b += 1
# 如果数组为[]返回0
return a+1 if nums else 0
20. 有效的括号
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 True
14. 最长公共前缀
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
# 切片位置初置为-1
n = -1
for 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)
# 去掉结尾的0
while 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 0
return x
771. 宝石与石头
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
n = 0
for j in J:
n += S.count(j)
return n
657. 机器人能否返回原点
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 True
832. 翻转图像
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 A
476. 数字的补数
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 = 0
r = len(s) - 1
while l < r:
if s[l] != s[r]:
# 尝试跳过一个字符,直接调用判断接口,去判断剩下的即可
def judge(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
return judge(s, l+1, r) or judge(s, l, r-1)
l += 1
r -= 1
return True
836. 矩形重叠
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/16
while 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 True
j += prec*x
i += prec*y
prec /= 2
return False
389. 找不同
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
un = s + t
dif = 0
for 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 False
else:
d[s[i]] = t[i]
# 字典的值必须不同,否则是虚假的映射
if len(set(i for i in d.values())) != len(d):
return False
return True
225. 用队列实现栈
from collections import deque
class MyStack(deque):
def __init__(self):
"""
Initialize your data structure here.
"""
pass
def 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 count
9. 回文数
# 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) != -1
941. 有效的山脉数组
# 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 True
876. 链表的中间结点
# 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 = None
class 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 = head
q = head
# 只有两个节点的情况,返回第二个结点
if p.next:
if p.next.next is None:
return q.next
# 三个及以上节点的情况
while p.next:
# 奇数节点的情况
p = p.next.next
q = q.next
# 偶数节点的情况
if p is None:
break
return q
234. 回文链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class 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 True
elif head.next is None:
return True
elif head.next.next is None:
return head.val == head.next.val
elif head.next.next.next is None:
return head.val == head.next.next.val
# 快指针判断节点是奇数/偶数,慢指针记录中间节点位置,长度5则移动3步,长度6则移动3步
p = head
q = head
while p.next:
if p.next.next is None:
break
p = p.next.next
q = q.next
def reverse_prev_half(): # 反转前半部分
c = head
n = head
p = None
while p != q:
n = c.next
c.next = p
p = c
c = n
return 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 False
p = p.next
n = n.next
return True
# 偶数的情况
else:
p,n = reverse_prev_half()
while p and n:
if p.val != n.val:
return False
p = p.next
n = n.next
return True
206. 反转链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = None
c = head
n = head
while c:
n = c.next
c.next = p
p = c
c = n
return p
237. 删除链表中的节点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
232. 用栈实现队列
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
# 几种边界条件暂未处理...
# 找到反转子段前的节点before
prev = head
cur = head
nxst = head
before = head
i = 1
while i < m:
i += 1
before = cur
cur = cur.next
# prev,cur指向子段第1,2个节点
prev = cur
cur = cur.next
# 反转子段
while i < n: # i=2...3<4
i += 1
nxst = cur.next
cur.next = prev
prev = cur
cur = nxst
# 找到反转子段后的节点
after = cur
# 连接子段和原链表
before.next.next = after
before.next = prev
return head
93. 实现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 = 0
for 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 += 1
if grid[i+1][j] == 0:
length += 1
if grid[i][j-1] == 0:
length += 1
if grid[i][j+1] == 0:
length += 1
return length
96. 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 ls
97. 交替位二进制数
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
# 左移与原数的二进制位异或,则应该是全部位数都是1,而最后一位是0,再右移,再判断是否每一位都是1
for i in bin(((n<<1)^n)>>1).split('b')[1]:
if i == '0':
return False
return True
98. 自除数
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':
break
if n % (int(i)) != 0:
break
else:
ls.append(n)
return ls
99. Nim游戏
class Solution:
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
if n%4 == 0:
return False
else:
return True
100. 重复 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 a
101. 汉明距离
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 + domain
if res not in u:
u.add(res)
return len(u)
# re做法
class Solution:
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
import re
u = 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 = 1
b = 1
c = -2*n
x1 = ((-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 = 0
for 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 0
ln = 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 = 0
odds = None
for i in set(s):
c = s.count(i)
if c%2 == 0:
n += c
else:
n += c-1
odds = c
if odds is not None:
n += 1
return n
697. 数组的度
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 = 0
p = True
maxc = cs[0][1]
for i in cs:
if i[1] < maxc:
break
t = i[2]
if p:
n = t
p = False
if n > t:
n = t
return n
796. 旋转字符串
class Solution:
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A)!=len(B):
return False
if A=='':
return True
i = 0
while i<len(A):
p = B.find(A[i:])
if p==0:
if A[i:]+A[:i]==B:
return True
i += 1
return False
263. 丑数
class Solution:
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for i in (2,3,5):
while num%i == 0:
num /= i
if num == 1:
return True
return num == 1
242. 有效的字母异位词
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 False
for i in s1:
if s.count(i) != t.count(i):
return False
return True
917. 仅仅反转字母
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 = 0
for i in range(len(S)):
if S[i].isalpha():
ls.append(s[j])
j += 1
else:
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*e
342. 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 False
return True
415. 字符串相加
class Solution:
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if len(num1) < len(num2):
b, s = num2, num1
else:
s, b = num2, num1
ln = 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)]))
# 存储进位的数据,初始全置0
sum = [0 for i in range(ln+1)]
i = ln
while i>0:
# 每一位的总加和,两个数字的位+上次的进位
s = ls[i]+lb[i]+sum[i]
if s>=10: # 如果超过10则该位置除10的余数,该位的高一位加1
sum[i] = s%10
sum[i-1] += 1
else: # 否则,直接把总和给该位
sum[i] = s
i -= 1
# 直接暴力将列表转成字符串,如果有,去掉前面位的0
sum = str(sum).replace(', ','')[1:-1]
if sum[0]=='0':
sum = sum[1:]
return sum
278. 第一个错误的版本
# 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 = 0
ri = n
while le<ri:
md = int((le+ri)/2)
if isBadVersion(md): # 如果中间是错误,则去md前面找,否则去md的后面mid+1开始找
ri = md
else:
le = md+1
return le
58. 最后一个单词的长度
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
import re
s = s.strip() # 先去掉首尾的' ',如果为空返回0
if not s:
return 0
if ' ' 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 = 0
self.tail = 0
self.n = k
def 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 False
else:
self.items[self.tail] = value
self.tail = (self.tail+1)%self.n
return True
def deQueue(self):
"""
Delete an element from the circular queue. Return true if the operation is successful.
:rtype: bool
"""
if self.isEmpty():
return False
self.items[self.head] = None
self.head = (self.head + 1) % self.n
return True
def Front(self):
"""
Get the front item from the queue.
:rtype: int
"""
if self.isEmpty():
return -1
return self.items[self.head]
def Rear(self):
"""
Get the last item from the queue.
:rtype: int
"""
if self.isEmpty():
return -1
if self.tail == 0:
i = self.n-1
else:
i = self.tail-1
return self.items[i]
def isEmpty(self):
"""
Checks whether the circular queue is empty or not.
:rtype: bool
"""
if self.head == self.tail:
return True
return False
def isFull(self):
"""
Checks whether the circular queue is full or not.
:rtype: bool
"""
if (self.tail+1)%self.n == self.head:
return True
return 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:
break
else: # 如果没有break,则进入else,那么就在同一行
ls.append(word)
continue # 如果在某一行,则继续下一个单词判断
for c in w:
if c not in caps:
break
else:
ls.append(word)
continue
for c in w:
if c not in shift:
break
else:
ls.append(word)
return ls
509. 斐波那契数
class Solution:
def fib(self, N):
"""
:type N: int
:rtype: int
"""
a = 0
b = 1
ls =[0,1]
for i in range(N):
a,b = b,a+b
ls.append(b)
return ls[N]
541. 反转字符串 II
class Solution:
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
ls = []
n = 0
for i in range(0,len(s),k):
if n == 1: # 如果是偶数位,则反转,否则不反转
ls.append(s[i:i+k])
n = 0
else:
ls.append(s[i:i+k][::-1])
n = 1
return ''.join(ls)
551. 学生出勤记录 I
class Solution:
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
return s.count('A')<2 and s.count('LLL')<1
557. 反转字符串中的单词 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 nums
return [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 ls
258. 各位相加
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 num
973. 最接近原点的 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 i
return -1
804. 唯一摩尔斯密码词
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)
break
else:
r.append(i+2)
return r
69. 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+1
while abs(n*n-x)>1:
n = n-(n-x/n)/2
return 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 w
724. 寻找数组的中心索引
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 i
a += nums[i]
return -1
844. 比较含退格的字符串
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==tt
496. 下一个更大元素 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])
break
else:
nums3.append(-1)
return nums3
704. 二分查找 #比较简洁的代码,自己写的太繁琐了
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
i = 0
j = len(nums) - 1
while i<=j:
k = (i+j)//2
if nums[k]==target:
return k # 如果找到,直接返回k
elif nums[k]<target:
i = k+1 # i,j基于k的移动作为循环趋向结束的条件
else:
j = k-1
return -1 # 如果没有查到,即完成循环,返回-1
896. 单调数列
class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if A[0]>A[-1]: # 如果递减,则将数列反转,当做是递增来判断
A=A[::-1]
i = 0
j = len(A)-1
Ai = A[i]
Aj = A[j]
while i<=j: # 需要加上=,否则可能在i,j中间位置的数未经过与i,j位置的数进行对比就退出
if A[i]>A[j]: # 如果前面的数大于后面,False
return False
if Ai > A[i]: # 如果前指针的数比它的前一个数小(或后指针的数比它的后一个数大), False
return False
else: # 否则继续循环,趋向于结束进行判断
Ai = A[i]
i += 1
if Aj < A[j]:
return False
else:
Aj = A[j]
j -= 1
return True # 如果判断了所有数,True
448. 找到所有数组中消失的数字
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 i
else:
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:
break
return rls
268. 缺失数字
class Solution:
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 利用相加和
sumNums = (0+len(nums)+1)*len(nums)/2
return int(sumNums - sum(nums))
# 利用异或排除索引未出现的
n = len(nums)
for i in range(len(nums)):
n = n^nums[i]^i
return n
# 同448. 找到所有数组中消失的数字
flag = True
ln = len(nums)
for i in nums:
if abs(i)<ln:
nums[abs(i)] *= -1
if nums[abs(i)]==0:
flag = False
if flag:
if 0 not in nums:
return 0
else:
return nums.index(0)
for i in range(ln):
if nums[i]>0:
return i
return ln
290. 单词模式
class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
str = str.split(" ")
if len(str) != len(pattern): # 如果键值对长度相等,则继续判断
return False
d = dict(zip(pattern, str))
str_set = set(str)
# 如果映射长度等于字符串集合的总长度,也等于字典值集合的总长度,则就是唯一对应的
if len(d) == len(str_set)==len(set(i for i in d.values())):
return True
return False
367. 有效的完全平方数
class Solution:
def isPerfectSquare(self, num: int) -> bool:
count = len(bin(num)) - 2
a = 2 ** (int(count / 2))
if num > a ** 2:
a *= 2
r = a
while r * r > num:
r = (r + num / r) // 2
return r * r == num
747. 至少是其他数字两倍的最大数
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
if len(nums)==1:
return 0
m = nums[0]
index = 0
i = 0
# 两次遍历,取最大值和次最大值,以及对应索引
while i<len(nums):
if m<nums[i]:
m = nums[i]
index = i
i+=1
if m == nums[0]:
m2 = nums[1]
index2 = 1
else:
m2 = nums[0]
index2 = 0
i = 0
while i<len(nums):
if m2<nums[i] and i != index:
m2 = nums[i]
index2 = i
i+=1
return 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 -1
if s1 == s2:
return 0
index1 = []
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 -1
if s1 == s2:
return 0
# 双标记
id1 = -1
id2 = -1
step = []
for i in range(len(ss)):
if ss[i] == s1:
id1 = i
elif ss[i] == s2:
id2 = i
if id1 == -1 or id2 == -1:
continue
else:
# 双标记的差的绝对值即为距离
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 % b
return 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)