暴力破解——解题代码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
result = []
for i in range(0,n):
for j in range(i + 1,n):
#print(i,j)
sum = nums[i] + nums[j]
if sum == target:
result.append(i)
result.append(j)
return result
分析:暴力破解的时间复杂度是O(n2)空间复杂度是O(1)
哈希表
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []
使用哈希表分析:时间复杂度是O(n)空间复杂度是O(n)
由于互为字母异位词的两个字符串包含的字母相同,因此对两个字符串分别进行排序之后得到的字符串一定是相同的。故可以将排序之后的字符串作为哈希表的键值。
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
mp = collections.defaultdict(list)
# 创建一个名为mp的变量,它是一个字典,其默认值为列表类型
#print(mp)
for st in strs:
key = "".join(sorted(st))
mp[key].append(st)
return list(mp.values())
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = sorted(nums)
mp = collections.defaultdict(int)
for i in nums:
if i - 1 in mp:
mp[i] = mp[i-1] + 1
mp.pop(i-1)
elif i not in mp:
mp[i] = 1
if not mp:
return 0
return max(mp.values())