15.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func twoSum(nums []int, target int) [][]int {
  7. n := len(nums)
  8. l, r := 0, n-1
  9. res := make([][]int, 0)
  10. for l < r {
  11. ln, rn := nums[l], nums[r]
  12. sum := ln + rn
  13. if sum < target {
  14. for ; l < r && nums[l] == ln; l++ {
  15. }
  16. } else if sum > target {
  17. for ; l < r && nums[r] == rn; r-- {
  18. }
  19. } else {
  20. res = append(res, []int{ln, rn})
  21. for ; l < r && nums[l] == ln; l++ {
  22. }
  23. }
  24. }
  25. return res
  26. }
  27. func threeSum(nums []int) [][]int {
  28. if len(nums) < 3 {
  29. return [][]int{}
  30. }
  31. sort.Ints(nums)
  32. res := make([][]int, 0)
  33. for a := 0; a < len(nums)-2; a++ {
  34. if a > 0 && nums[a] == nums[a-1] {
  35. continue
  36. }
  37. // the same as twoSum: target -> -nums[a], nums -> nums[a+1:]
  38. // one or more or none solutions
  39. b, c := a+1, len(nums)-1
  40. for b < c {
  41. nb, nc := nums[b], nums[c]
  42. sum := nums[a] + nb + nc
  43. if sum < 0 {
  44. b++
  45. } else if sum > 0 {
  46. c--
  47. } else {
  48. res = append(res, []int{nums[a], nb, nc})
  49. for ; b < c && nums[b] == nb; b++ {
  50. }
  51. for ; b < c && nums[c] == nc; c-- {
  52. }
  53. }
  54. }
  55. }
  56. return res
  57. }
  58. func main() {
  59. a1 := []int{-1, 0, 1, 2, -1, -4}
  60. fmt.Println(threeSum(a1))
  61. a2 := []int{-1, 0, -4}
  62. fmt.Println(threeSum(a2))
  63. a3 := []int{0, 0, 0}
  64. fmt.Println(threeSum(a3))
  65. }