- 搜索插入位置
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target < nums[0]or (len(nums) == 1 and target == nums[0]): return 0
if target > nums[-1]: return len(nums)
for i in range(len(nums) - 1):
if nums[i] == target:
return i
elif nums[i] < target <= nums[i + 1]:
return i + 1
- 快乐数
def isHappy(self, n: int) -> bool:
def get_next(n):
total_sum = 0
while n > 0:
n, digit = divmod(n, 10)
total_sum += digit ** 2
return total_sum
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = get_next(n)
return n == 1
- 同构字符串
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
for i in range(len(s)):
if s.index(s[i]) != t.index(t[i]):
return False
return True
4.单词规律
def wordPattern(self, pattern: str, str: str) -> bool:
res=str.split()
return list(map(pattern.index, pattern))==list(map(res.index,res))
- 两个数组的交集
class Solution:
def set_intersection(self, set1, set2):
return [x for x in set1 if x in set2]
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
set2 = set(nums2)
if len(set1) < len(set2):
return self.set_intersection(set1, set2)
else:
return self.set_intersection(set2, set1)
1万+

被折叠的 条评论
为什么被折叠?



