class Solution(object): def triangularSum(self, nums): for n in range(len(nums) - 1, 0, -1): for i in range(n): nums[i] = (nums[i] + nums[i + 1]) % 10 return nums[0]
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = defaultdict(list) for s in strs: k = ''.join(sorted(s)) d[k].append(s) return list(d.values())
3
128 最长连续序列
集合的 O (1) 时间复杂度查找 特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Solution: def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) length = 0 for x in s: if x-1 not in s: y = x z = 1 while y + 1 in s: y += 1 z += 1 length = max(length, z) return length
还有是直接删掉元素,s.remove(y)也是实现了减小了时间复杂度
4
11 乘最多水的容器
双指针 移动短的
我只能想到用两个for循环,但是这样子的话时间复杂度就不满足了::>_<::
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Solution: def maxArea(self, height: List[int]) -> int: left, right = 0, len(height) - 1 area = 0 while left < right: width = right - left h = min(height[left], height[right]) a = width * h area = max(a, area) if height[left] < height[right]: left += 1 else: right -= 1 return area
5
15 三数之和
1 2 3 4 5 6 7 8 9 10
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: result=set() for i in range(len(nums)): for j in range(i+1,len(nums)): for k in range(j+1,len(nums)): if nums[i] + nums[j] + nums[k] == 0: triplet=tuple(sorted([nums[i], nums[j], nums[k]])) result.add(triplet) return [list(triplet) for triplet in result]
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() n, res = len(nums), [] if(not nums or n<3): return []
for i in range(n): if(nums[i]>0): return res if(i>0 and nums[i]==nums[i-1]): continue L=i+1 R=n-1 while(L<R): if(nums[i]+nums[L]+nums[R]==0): res.append([nums[i],nums[L],nums[R]]) while(L<R and nums[L]==nums[L+1]): L=L+1 while(L<R and nums[R]==nums[R-1]): R=R-1 L=L+1 R=R-1 elif(nums[i]+nums[L]+nums[R]>0): R=R-1 else: L=L+1 return res
6
42 接雨水
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
if not height:return 0 n = len(height) left,right = 0,n-1 # 定义左指针,右指针,分别是从最左和最右开始 maxleft,maxright = height[0],height[n-1] ans = 0 while left <= right: # 当左边指针<=右指针时 maxleft = max(height[left],maxleft) # 左边最长柱子 maxright = max(height[right],maxright) # 右边最长柱子 if maxleft < maxright: # 当左边最长柱子 < 右边最长柱子 ans = ans + maxleft - height[left] # 左边最长柱子减去当前指针所在的柱子的高度就是能接到多少雨水,不理解的看图比较 left += 1 # 因为右边柱子比较长,所以我们把左指针往右移动 else: # 如果左边最大柱子>=右边最大柱子 ans = ans + maxright - height[right] # 右边最长柱子减去当前柱子的高度就是能接到多少雨水 right -= 1 # 右指针往左移动 return ans