Leetcode-15: 3Sum

来源:互联网 发布:b2c商城网站源码下载 编辑:程序博客网 时间:2024/06/08 05:37

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]]

思路:

1. 朴素遍历所有的3元素子集,复杂度:O(n^3),然后筛除重复元素,由于solution需要升序排列,所以可以先对数组S进行排序。

2. 对朴素遍历法进行精简:1) 可转化为2Sum问题,即解决n个target为-num[i]的2Sum问题,复杂度降至O(n^2)。2)重复元素的筛除:可通过set去除重复元素,也可以在遍历的时候跳过元素。


public class Solution {    public List<List<Integer>> threeSum(int[] nums) {        List<List<Integer>> res = new LinkedList<>();        Arrays.sort(nums);        for (int targetInd = 0; targetInd < nums.length - 2; ++targetInd) {            if (nums[targetInd] > 0) break;            if (targetInd > 0 && nums[targetInd] == nums[targetInd - 1]) continue;            int target = -nums[targetInd];            int head = targetInd + 1, tail = nums.length - 1;            while (head < tail) {                if (target == nums[head] + nums[tail]) {                    res.add(Arrays.asList(nums[targetInd], nums[head], nums[tail]));                    while (head < tail && nums[head + 1] == nums[head]) ++head;                    while (head < tail && nums[tail - 1] == nums[tail]) --tail;                    ++head; --tail;                }                else if (target > nums[head] + nums[tail])                    ++head;                else                    --tail;            }        }        return res;    }}



原创粉丝点击