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的三个元素的集合,且不能重复。
func threeSum(nums []int) [][]int { var results [][]int if len(nums) < 3 { return results } sort.Ints(nums) for i := 0; i < len(nums) && nums[i] <= 0; i++ { if i > 0 && nums[i] == nums[i-1] { continue } j := i + 1 k := len(nums) - 1 for j < k { sum := nums[i] + nums[j] + nums[k] if sum == 0 { results = append(results,[]int{nums[i],nums[j],nums[k]}) for j < len(nums) - 1 && nums[j] == nums[j+1] { j++ } for k > 0 && nums[k] == nums[k-1] { k-- } j++ k-- } else if sum < 0 { j++ } else if sum > 0 { k-- } } } return results}总结
以上是内存溢出为你收集整理的15. 3Sum全部内容,希望文章能够帮你解决15. 3Sum所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)