Leetcode 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:
- 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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步