classSolution: deflongestConsecutive(self, nums: List[int]) -> int: res = 0 num_set = set(nums) for num in num_set: if num - 1notin num_set: i = 1 count = 1 while num + i in num_set: count += 1 i += 1 res = max(res, count) return res
classSolution{ publicintlongestConsecutive(int[] nums){ Set<Integer> num_set = new HashSet<>(); Arrays.stream(nums).forEach(num -> num_set.add(num)); int res = 0; for (int num : num_set) { if (!num_set.contains(num - 1)) { int i = 1; int count = 1; while (num_set.contains(num + i)) { count++; i++; } res = Math.max(count, res); } } return res; } }
双指针
283、移动零
本题的思路是有两个指针,right指针进行遍历,left指针指向的是非0数字的当前末尾
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defmoveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ # 双指针 left, right = 0, 0 while right < len(nums): if nums[right] != 0: nums[left], nums[right] = nums[right], nums[left] left += 1 right += 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ publicvoidmoveZeroes(int[] nums){ int left = 0; int right = 0; while (right < nums.length) { if (nums[right] != 0) { int tmp = nums[right]; nums[right] = nums[left]; nums[left] = tmp; left++; } right++; } } }
11、盛水最多的容器
1 2 3 4 5 6 7 8 9 10 11
classSolution: defmaxArea(self, height: List[int]) -> int: left, right = 0, len(height) - 1 res = min(height[left], height[right]) * (right - left) while left < right: if height[left] < height[right]: left += 1 else: right -= 1 res = max(res, min(height[left], height[right]) * (right - left)) return res
Java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution{ publicintmaxArea(int[] height){ int left = 0; int right = height.length - 1; int res = Math.min(height[left], height[right]) * (right - left); while (left < right) { if (height[right] < height[left]) { right--; } else { left++; } res = Math.max(res, Math.min(height[left], height[right]) * (right - left)); } return res; } }
15、三数之和
暴力解法 时间复杂度是o(n²)
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defthreeSum(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() for i inrange(len(nums)): myhash = {} for j inrange(i + 1, len(nums)): if -nums[i] - nums[j] in myhash: tmp = [nums[i], nums[j], -nums[i] - nums[j]] if tmp notin res: res.append(tmp) myhash[nums[j]] = nums[j] return res
classSolution: defthreeSum(self, nums: List[int]) -> List[List[int]]: # 双指针 nums.sort() res = [] for i inrange(len(nums) - 2): if i > 0and nums[i] == nums[i - 1]: continue left, right = i + 1, len(nums) - 1 while left < right: sum_ = nums[i] + nums[left] + nums[right] if sum_ == 0: res.append([nums[i], nums[left], nums[right]]) while left < right and nums[left] == nums[left + 1]: left += 1 while left < right and nums[right] == nums[right - 1]: right -= 1 left += 1 right -= 1 elif sum_ < 0: left += 1 else: right -= 1 return res