LeetCode 2000
题目描述
代码实现
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
index = word.find(ch)
if index == -1:
return word
else:
reverse = word[:index+1]
return reverse[::-1] + word[index+1:]
LeetCode 2001
2001. 可互换矩形的组数 - 力扣(LeetCode) (leetcode-cn.com)
题目描述
代码实现
方法一:暴力破解(超时)
class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
"""方法一:暴力解题"""
n = len(rectangles)
ans = 0
for i in range(n-1):
for j in range(i+1, n):
w1,h1,w2,h2 = rectangles[i][0], rectangles[i][1],rectangles[j][0],rectangles[j][1]
if w1/h1 == w2/h2:
ans += 1
return ans
class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
n = len(rectangles)
ans = 0
for i in range(n-1):
for j in range(i+1, n):
w1,h1,w2,h2 = rectangles[i][0], rectangles[i][1],rectangles[j][0],rectangles[j][1]
if w1*h2 == w2*h1:
ans += 1
return ans
方法二:defaultdict()字典
class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
"""方法二:defaultdict()"""
from collections import defaultdict
dic = defaultdict(int)
n = len(rectangles)
ans = 0
for i in range(n):
w1,h1= rectangles[i][0], rectangles[i][1]
# 小trick:累加+1+2+3+4...
ans += dic[h1/w1]
dic[h1/w1] += 1
return ans
方法三:defaultdict()字典 + 最大公约数
class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
"""方法三:defaultdict() + 最大公约数"""
def gcd(a, b):
'''辗转相除法'''
if a < b:
b,a = a,b
r = a % b
while r!=0:
a = b
b = r
r = a % b
return b
dic = defaultdict(int)
n = len(rectangles)
ans = 0
for i in range(n):
w1,h1= rectangles[i][0], rectangles[i][1]
big = gcd(w1,h1)
# 小trick:累加+1+2+3+4...
ans += dic[(w1//big,h1//big)]
dic[(w1//big,h1//big)] += 1
return ans
LeetCode 162
162. 寻找峰值 - 力扣(LeetCode) (leetcode-cn.com)
题目描述
代码实现
方法一:暴力破解
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
# nums[-1] = nums[n] = -∞ 一定存在峰值,因为两端较小
if len(nums) == 1: return 0
n = len(nums)
for i in range(n-1):
if nums[i] > nums[i+1]:
return i
return n-1
方法二:爬坡法(官方解释)
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
'''方法二:爬坡'''
def check(i):
if i==-1 or i==n:
return float('-inf')
return nums[i]
n = len(nums)
rand = random.randint(0, n-1)
while not (check(rand-1) < check(rand) > check(rand+1)):
if check(rand) < check(rand+1):
rand += 1
else:
rand -= 1
return rand
方法三:二分查找
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
'''方法三:二分查找'''
left=0
right=len(nums)-1
while left < right: # 不能等于
mid = left + (right-left)//2
if nums[mid] < nums[mid+1]:
left = mid+1
else:
right = mid
return left