leetcode 15. 3Sum

来源:互联网 发布:大数据相关课程 编辑:程序博客网 时间:2024/06/05 16:32

题目

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: 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]]
代码

public class Solution {public List<List<Integer>> threeSum(int[] nums) {        List<List<Integer>> res = new ArrayList<List<Integer>>();        HashSet<String> repeat = new HashSet<String>();        Arrays.sort(nums);        for (int i = 0 ; i <= nums.length - 2 ; i++) {        int ans = 0 - nums[i];        int forw = i + 1;        int back = nums.length - 1;        while (forw < back) {        if ((nums[forw] + nums[back]) == ans) {        if (!repeat.contains(nums[i] + "&" + nums[forw])) {        List<Integer> l = new ArrayList<Integer>();        l.add(nums[i]);        l.add(nums[forw]);        l.add(nums[back]);        res.add(l);        repeat.add(nums[i] + "&" + nums[forw]);        }        forw++;        back--;        }else if ((nums[forw] + nums[back]) < ans) {        forw++;        }else {        back--;        }        }        }        return res;    }}


0 0
原创粉丝点击