标签:
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:
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
排序后,遍历途中使用初始值分别为当前遍历点后一点和数组最后一点的指针,如果三值之和大于0,则后指针向左移动使后三值之和减小;反之前指针向右移动。
def three_sum(nums) ans = [] return ans if nums.length < 3 a = nums.sort (a.length-2).times do |i| j, k = i+1, a.length-1 while j < k if a[i] + a[j] + a[k] == 0 ans << [a[i],a[j],a[k]] j += 1 k -= 1 elsif a[i] + a[j] + a[k] > 0 k -= 1 elsif a[i] + a[j] + a[k] < 0 j += 1 end end end ans.uniq end
标签:
原文地址:http://www.cnblogs.com/lilixu/p/4575528.html