242. 有效的字母异位词 - 力扣(LeetCode)
# map
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
hash = {}
for i in s:
hash[i] = hash.get(i,0) + 1
for i in t:
hash[i] = hash.get(i,0) - 1
for key,value in hash.items():
if value != 0:
return False
return True
数组
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
hash = [0] * 26
for i in s:
hash[ord(i) - ord('a')] += 1
for i in t:
hash[ord(i) - ord('a')] -= 1
for i in hash:
if i !=0 :
return False
return True
349. 两个数组的交集 - 力扣(LeetCode)
# 字典和集合
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
hash = {}
for i in nums1:
hash[i] = hash.get(i,0)
result = []
for i in nums2:
if i in hash.keys():
result.append(i)
del hash[i]
return result
# 数组
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
hash1 = [0] * 1001
hash2 = [0] * 1001
for i in nums1:
hash1[i] += 1
for i in nums2:
hash2[i] += 1
result = []
for i in range(1001):
if hash1[i] * hash2[i] != 0:
result.append(i)
return result
# 集合
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
1. 两数之和 - 力扣(LeetCode)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashd = {}
for i in range(len(nums)):
if target - nums[i] in hashd:
return [i,hashd[target - nums[i]]]
hashd[nums[i]] = i
454. 四数相加 II - 力扣(LeetCode)
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashd = {}
for i in nums1:
for j in nums2:
hashd[i + j] = hashd.get(i+j,0) + 1
result = 0
for i in nums3:
for j in nums4:
if -(i + j) in hashd:
result += hashd[-(i+j)]
return result
15. 三数之和 - 力扣(LeetCode)
# 双指针
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
lenth = len(nums)
result = []
if nums[0] > 0:
return result
for a in range(lenth -1):
if a != 0 and nums[a] == nums[a-1]:
continue
left = a + 1
right = lenth - 1
while left < right:
_sum = nums[left] + nums[right] + nums[a]
if _sum == 0:
result.append([nums[a],nums[left],nums[right]])
while left < lenth-2 and nums[left] == nums[left+1]:
left += 1
while right > a+2 and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif _sum > 0:
right -= 1
else:
left += 1
return result