15. 3Sum

前端之家收集整理的这篇文章主要介绍了15. 3Sum前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Given an array S of n integers,are there elements a,b,c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example,given array S = [-1,1,2,-1,-4],

A solution set is:
[
[-1,1],
[-1,2]
]

找出一个数组中,和为0的三个元素的集合,且不能重复。

  1. func threeSum(nums []int) [][]int {
  2. var results [][]int
  3. if len(nums) < 3 {
  4. return results
  5. }
  6. sort.Ints(nums)
  7. for i := 0; i < len(nums) && nums[i] <= 0; i++ {
  8. if i > 0 && nums[i] == nums[i-1] {
  9. continue
  10. }
  11. j := i + 1
  12. k := len(nums) - 1
  13. for j < k {
  14. sum := nums[i] + nums[j] + nums[k]
  15. if sum == 0 {
  16. results = append(results,[]int{nums[i],nums[j],nums[k]})
  17. for j < len(nums) - 1 && nums[j] == nums[j+1] {
  18. j++
  19. }
  20. for k > 0 && nums[k] == nums[k-1] {
  21. k--
  22. }
  23. j++
  24. k--
  25. } else if sum < 0 {
  26. j++
  27. } else if sum > 0 {
  28. k--
  29. }
  30. }
  31. }
  32. return results
  33. }

猜你在找的Go相关文章