From c29a56bc1fcbd26c9c22d892d7bade0d3e53445d Mon Sep 17 00:00:00 2001 From: madingx <476100112@qq.com> Date: Mon, 6 Mar 2017 20:02:00 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=89=E4=B8=AA=E6=95=B0=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3Sum.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/3Sum.java b/3Sum.java index f31c11d..d900bb3 100644 --- a/3Sum.java +++ b/3Sum.java @@ -5,7 +5,7 @@ Difficulty: Medium Source: https://oj.leetcode.com/problems/3sum/ Notes: - Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? + 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) @@ -21,6 +21,7 @@ public class Solution { public List> threeSum(int[] num) { List> res = new ArrayList>(); Arrays.sort(num); + //S = {-4 -1 -1 0 1 2 } int N = num.length; for (int i = 0; i < N-2 && num[i] <= 0; ++i) { @@ -30,9 +31,15 @@ public List> threeSum(int[] num) { int l = i + 1, r = N - 1; while (l < r) { - int sum = num[l] + num[r]; + //S = {-4 -1 -1 0 1 2 } + // i l r + int sum = num[l] + num[r]; //左右开弓 if (sum < twosum) ++l; + //S = {-4 -1 -1 0 1 2 } + // i l r //向右调 else if (sum > twosum) --r; + //S = {-4 -1 -1 0 1 2 } + // i l r //向左调 else { ArrayList tmp = new ArrayList(); tmp.add(num[i]); tmp.add(num[l]); tmp.add(num[r]); @@ -45,4 +52,4 @@ public List> threeSum(int[] num) { } return res; } -} \ No newline at end of file +}