Leetcode 15 3Sum

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

 

    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

排序后,遍历途中使用初始值分别为当前遍历点后一点和数组最后一点的指针,如果三值之和大于0,则后指针向左移动使后2值之和减小;反之前指针向右移动。

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

 

posted @ 2015-06-14 19:07  lilixu  阅读(187)  评论(0编辑  收藏  举报