Three Sum

  • 描述

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:
• Elementsinatriplet(a,b,c)mustbeinnon-descendingorder.(ie,a≤b≤c)
• Thesolutionsetmustnotcontainduplicatetriplets.

For example, given array S={-1 0 1 2 -1 4}

A solution set is:
(-1 0 1)
(-1 -1 2)

  • 分析

有序Two Sum的衍生版,那么可以沿用Two Sum,使Three Sum变成Two Sum,在外层套一个循环即可,时间复杂度为O(n^2)

package leet.ThreeSum;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Solution {
    public static List<Integer> getThreeSum(int[] arr, int target) {
        List<Integer> res = new ArrayList<Integer>(6);
        if(arr == null || arr.length < 3)
            return res;
        // 为保证结果集有序,要先排序
        Arrays.sort(arr);
        for(int i = 0; i < arr.length-2; ++i) {
            int low = i + 1;
            int high = arr.length - 1;
            // 确保结果不会重复
            if(i>0 && arr[i] == arr[i-1]) continue;
            int sum = target - arr[i];
            // Two Sum的解决方法,不同的是要排除重复的,如果重复,则跳过
            while(low < high) {
                if(arr[low] + arr[high] > sum) {
                    -- high;
                    while(arr[high] == arr[high+1] && low < high)
                        -- high;
                }
                else if(arr[low] + arr[high] < sum) {
                    ++low;
                    while (arr[low] == arr[low - 1] && low < high)
                        ++low;
                }
                else {
                    res.add(arr[i]);
                    res.add(arr[low]);
                    res.add(arr[high]);
                    ++ low;
                    -- high;
                    while (arr[low] == arr[low - 1] && arr[high] == arr[high+1] && low < high)
                        ++low;
                }
            }
        }
        return res;

    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,083评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 每一个刚降不久的孩子,都是一块未经雕饰的璞玉。通透、清澈、夺目,浑身散发着一种纯粹的生命之美。让人爱不释手,又小心...
    火山House阅读 299评论 3 1
  • 曾经,丢弃了文字好多年,而今拾起,没有因为把它丢在一个安静的角落而冰凉,拾起,还是满满的暖… 喜欢文字的人,注定了...
    鸣菁姐姐阅读 481评论 3 0
  • 缘聚缘散,冥冥之中自有安排。 这些天遇到了很多很奇妙的事情,感受万千,却无法说个所以然!小蜜和他另一半和好如初,毅...
    倾心悠然阅读 418评论 0 0