#穷举 classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) for i inrange(n): for j inrange(i+1,n): if nums[i] + nums[j] == target: return [i,j]
1 2 3 4 5 6 7
#哈希表 classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: mp = {} for i,num inenumerate(nums): if num in mp: return [mp[num],i] else: mp[target-num] = i
classSolution: defgroupAnagrams(self, strs: List[str]) -> List[List[str]]: mp = {} for s in strs: tmp = ''.join(sorted(s)) if tmp in mp: mp[tmp] += [s] else: mp[tmp] = [s] returnlist(mp.values())
1 2 3 4 5 6
classSolution: defgroupAnagrams(self, strs: List[str]) -> List[List[str]]: d = defaultdict(list) #使用defaultdict给没有定义的key一个默认value:None for s in strs: d[''.join(sorted(s))].append(s) # sorted(s) 相同的字符串分到同一组 returnlist(d.values())
#集合作哈希表 classSolution: deflongestConsecutive(self, nums: List[int]) -> int: res = 0 nums_set = set(nums) #set集合也是哈希表 for n in nums_set: if n-1notin nums_set: cur_num = n cur_res = 1 while cur_num+1in nums_set: cur_num += 1 cur_res += 1 res = max(res,cur_res) return res
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
**说明:**你不能倾斜容器。
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defmaxArea(self, height: List[int]) -> int: n = len(height) l, r = 0, n-1 res = 0 while l < r: if height[l] <= height[r]: res = max(res, (r-l)*height[l]) l += 1 else: res = max(res, (r-l)*height[r]) r -= 1 return res
classSolution: defthreeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) res = [] nums.sort() for k inrange(n-2): if nums[k] > 0: break if k > 0and nums[k] == nums[k-1]: continue i, j = k+1, n-1 while i < j: s = nums[k] + nums[i] + nums[j] if s > 0: j -= 1 while i < j and nums[j] == nums[j+1]: j -= 1 elif s < 0: i += 1 while i < j and nums[i] == nums[i-1]: i += 1 else: res.append([nums[k], nums[i], nums[j]]) i += 1 j -= 1 while i < j and nums[j] == nums[j+1]: j -= 1 while i < j and nums[i] == nums[i-1]: i += 1 return res
#动态规划 classSolution: deftrap(self, height: List[int]) -> int: n = len(height) leftmax = [0] * n rightmax = [0] * n leftmax[0], rightmax[-1] = height[0], height[-1] for i inrange(1,n): j = -i -1 leftmax[i] = max(leftmax[i-1], height[i]) rightmax[j] = max(rightmax[j+1], height[j]) res = 0 for i inrange(n): res += min(leftmax[i],rightmax[i]) - height[i] return res
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#双指针dp classSolution: deftrap(self, height: List[int]) -> int: res = 0 n = len(height) l, r = 0, n-1 lm = rm = 0 while l < r: lm = max(lm, height[l]) rm = max(rm, height[r]) if lm < rm: res += lm - height[l] l += 1 else: res += rm - height[r] r -= 1 return res
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#单调栈 classSolution: deftrap(self, height: List[int]) -> int: n = len(height) stk = [] res = 0 for i,h inenumerate(height): while stk and h > height[stk[-1]]: d = stk.pop() ifnot stk: break l = stk[-1] res += (i-l-1)*(min(height[l],h) - height[d]) stk.append(i) return res