【LeetCode】015.3Sum

来源:互联网 发布:db2执行sql脚本有换行 编辑:程序博客网 时间:2024/06/01 09:50

题目:

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)
解答:

首先将nums按照升序排序,第一层循环中确定第一个数字,在第二层循环里,第二个和第三个数从两边向中间扫描,计算每次的结果sum

(1)sum为0,得到一组解

(2)sum > 0 ,过大,需要将第三个数往左移动

(3)sum < 0,过小,需要将第二数往右移动

为了避免重复的结果,每次移动时跳过重复的值;


代码:

import java.util.*;public class Solution {    public List<List<Integer>> threeSum(int[] nums) {Arrays.sort(nums); // non-descending order is ensuredList<List<Integer>> ret = new ArrayList<List<Integer>>();for (int i = 0; i < nums.length; i++) {// skip duplicatewhile (i > 0 && i < nums.length && nums[i] == nums[i - 1])i++;int j = i + 1, k = nums.length - 1;while (j < k) {int sum = nums[i] + nums[j] + nums[k];// find one tripletif (sum == 0) {List<Integer> triplet = new ArrayList<Integer>(3);triplet.add(nums[i]);triplet.add(nums[j]);triplet.add(nums[k]);ret.add(triplet);j++;// skip duplicatewhile (j < k && nums[j] == nums[j - 1])j++;k--;// skip duplicatewhile (k > j && nums[k] == nums[k + 1])k--;} else if (sum > 0) {k--;while (k > j && nums[k] == nums[k + 1])k--;} else {j++;// skip duplicatewhile (j < k && nums[j] == nums[j - 1])j++;}}}return ret;}}


0 0
原创粉丝点击