15.go 1.2 KB

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