1.有效的字母异位词: 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。题目链接:https://leetcode-cn.com/problems/valid-anagram/
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):return False
se = set(s)
for i in se:
if s.count(i) != t.count(i):return False
return True
2.两个数组的交集: 给定两个数组,编写一个函数来计算它们的交集。https://leetcode-cn.com/problems/intersection-of-two-arrays/
解法:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
s1 = set(nums1)
s2 = set(nums2)
return s1&s2 #&:集合求交集
3.两个数组的交集II: 给定两个数组,编写一个函数来计算它们的交集。题目链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
解法1:遍历比对:
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
for i in nums1:
if (i in nums2):
nums2.remove(i)
res.append(i)
return res
解法2:先将两个数组排序,使用双指针法,比较元素大小,数值相同时,将列表中共同元素抠下来,不同时数值小的数组指针向前移动。参考链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/solution/1-xing-python-jin-jie-jie-fa-by-qqqun902025048/
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
nums1.sort()
nums2.sort()
i = j = 0
while i<len(nums1) and j<len(nums2):
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return res
4.三角形的最大周长:给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。如果不能形成任何面积不为零的三角形,返回 0。题目链接:https://leetcode-cn.com/problems/largest-perimeter-triangle/
解法1:
def largestPerimeter(A):
A.sort()
if len(A) < 3:return 0
i = 2
res = []
while i <= len(A)-1:
if A[i] < A[i-1]+A[i-2]:
res.append(A[i]+A[i-1]+A[i-2])
i +=1
if len(res) == 0:return 0
return max(res)
解法2:倒着取,参考链接:https://leetcode-cn.com/problems/largest-perimeter-triangle/solution/san-jiao-xing-de-zui-da-zhou-chang-by-leetcode/
class Solution(object):
def largestPerimeter(self, A):
A.sort()
for i in range(len(A) - 3, -1, -1):
if A[i] + A[i+1] > A[i+2]:
return A[i] + A[i+1] + A[i+2]
return 0