funcmaxArea(height []int)int { var maxArea int for i := 0; i < len(height); i++ { for j := i + 1; j < len(height); j++ { area := (j - i) * min(height[i], height[j]) maxArea = max(maxArea, area) } } return maxArea } funcmax(a, b int)int { if a < b { return b } return a } funcmin(a, b int)int { if a < b { return a } return b }
funcmaxArea(height []int)int { maxArea, i, j := 0, 0, len(height)-1 for i < j { area := (j - i) * min(height[i], height[j]) if height[i] < height[j] { i++ } else { j-- } maxArea = max(area, maxArea) } return maxArea } funcmax(a, b int)int { if a < b { return b } return a } funcmin(a, b int)int { if a < b { return a } return b }
functwoSum(nums []int, target int) []int { for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { if nums[i]+nums[j] == target { return []int{i,j} } } } return []int{} }
两遍循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functwoSum(nums []int, target int) []int { indexMap := make(map[int]int) for i, v := range nums { indexMap[v] = i } for i, v := range nums { value := target - v index, ok := indexMap[value] if ok && index != i { return []int{i, index} } } return []int{} }
一遍循环
1 2 3 4 5 6 7 8 9 10
functwoSum(nums []int, target int) []int { indexMap := make(map[int]int) for i, v := range nums { if index, ok := indexMap[target-v]; ok { return []int{index, i} } indexMap[v] = i } return []int{} }
三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
1 2 3 4 5 6 7
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
解法
三数之和可以转化为两数之和,要求解的其实是 a + b = -c
暴力求解:三重循环 $O(n^3)$
哈希表 $O(n^2)$
双指针法
暴力求解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
functhreeSum(nums []int) [][]int { var ( result [][]int ) for i, n := range nums { for j := i + 1; j < len(nums); j++ { for k := j + 1; k < len(nums); k++ { if nums[j]+nums[k]+n == 0 { result = append(result, []int{n, nums[j], nums[k]}) } } } } return result }
存在的问题:去重比较麻烦
暴力+哈希表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functhreeSum(nums []int) [][]int { var ( result [][]int ) for i, n := range nums { indexMap := make(map[int]int) for j := i + 1; j < len(nums); j++ { if k, ok := indexMap[-n-nums[j]]; ok { result = append(result, []int{n, nums[j], nums[k]}) } else { indexMap[nums[j]] = j } } } return result }
functhreeSum(nums []int) [][]int { var ( i, j int result [][]int ) sort.Ints(nums) for k := 0; k < len(nums)-2; k++ { if nums[k] > 0 { break } if k > 0 && nums[k] == nums[k-1] { continue } i, j = k+1, len(nums)-1 for i < j { s := nums[k] + nums[i] + nums[j] if s < 0 { i++ } elseif s > 0 { j-- } else { result = append(result, []int{nums[k], nums[i], nums[j]}) i++ j-- for i < j && nums[i] == nums[i-1] { i++ } for i < j && nums[j] == nums[j+1] { j-- } } }