LeetCode解题报告--3 Sum

题目: 3 个数和问题

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)

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)

原题链接地址:https://leetcode.com/problems/3sum/

分析:题意是从给定的整型数组,找出三个数和为0的所有可能的组合,该题有两种方法解决:

1. 暴力法: 通过三个for循环找出给定数组所有triplet和的情况,并通过if语句判断,将和为0的triplet记录,并打印出来!时间复杂度为0(N^3),必然TLE,无法accepted。

2. 首尾指针移位法: 先将原数组排序,再设left(l),right(r)(指针)变量分别指向给定数组的首末元素,将3个数和问题转为2个数和2sum问题。时间复杂度O(NlogN)。

以上方法要注意最后的除重操作!

暴力法 java代码(超时无法accepted)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;

public class ThreeSum {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] s = new int[] { 0,2,1,-3 };
        System.out.println(" A solution set is: ");
        ArrayList<ArrayList<Integer>> listArray = new ArrayList<ArrayList<Integer>>();
        listArray = threeSum(s);
        for (int i = 0; i < listArray.size(); i++) {
            System.out.println(listArray.get(i));
        }
    }

    public static ArrayList<ArrayList<Integer>> threeSum(int[] nums) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
        String string = "";
        ArrayList<String> string1 =new ArrayList<String>();
        int[] b = new int[3];
        for(int i = 0;i < nums.length;i ++){
            for(int j = i + 1;j < nums.length;j ++){
                for(int k = j + 1;k < nums.length;k ++){
                    ArrayList<Integer> element = new ArrayList<Integer>();
                    if(nums[k] + nums[j] + nums[i] == 0){
                        string  = "";
                        element.add(nums[i]);
                        element.add(nums[j]);
                        element.add(nums[k]);

                        b[0] = nums[i];
                        b[1] = nums[j];
                        b[2] = nums[k];
                        //Avoid reduplicated result
                        Arrays.sort(b);
                        for(int n = 0;n < b.length;n ++){
                            string = string + b[n];
                        }
                        if(!string1.contains(string)){
                            list.add(element);
                            string1.add(string);
                        }
                    }
                }
            }
        }
        return list;
    }
}

首尾指针移位法 java代码(accepted)

    public static ArrayList<ArrayList<Integer>> threeSum(int[] nums) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
        HashSet<ArrayList<Integer>> elementSet = new HashSet<ArrayList<Integer>>();
        int sum = 0;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            //Directly avoid reduplicated result
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                sum = nums[i] + nums[left] + nums[right];
                if(sum == 0){
                    ArrayList<Integer> element = new ArrayList<Integer>();
                    element.add(nums[i]);
                    element.add(nums[left]);
                    element.add(nums[right]);
                    if(!elementSet.contains(element)){
                        list.add(element);
                        elementSet.add(element);
                    }
                    left ++;
                    right --;
                }else if(sum < 0){
                    left ++;
                }else{
                    right --;
                }
            }
        }
        return list;
    }
}

测试结果:

 A solution set is:
[-15, 1, 14]
[-15, 2, 13]
[-15, 3, 12]
[-15, 4, 11]
[-15, 5, 10]
[-15, 6, 9]
[-15, 7, 8]
[-14, 0, 14]
[-14, 1, 13]
[-14, 2, 12]
[-14, 3, 11]
[-14, 4, 10]
[-14, 5, 9]
[-14, 6, 8]
[-14, 7, 7]
[-13, -1, 14]
[-13, 0, 13]
[-13, 1, 12]
[-13, 2, 11]
[-13, 3, 10]
[-13, 4, 9]
[-13, 5, 8]
[-13, 6, 7]
[-12, -2, 14]
[-12, -1, 13]
[-12, 0, 12]
[-12, 1, 11]
[-12, 2, 10]
[-12, 3, 9]
[-12, 4, 8]
[-12, 5, 7]
[-12, 6, 6]
[-11, -3, 14]
[-11, -2, 13]
[-11, -1, 12]
[-11, 0, 11]
[-11, 1, 10]
[-11, 2, 9]
[-11, 3, 8]
[-11, 4, 7]
[-11, 5, 6]
[-10, -4, 14]
[-10, -3, 13]
[-10, -2, 12]
[-10, -1, 11]
[-10, 0, 10]
[-10, 1, 9]
[-10, 2, 8]
[-10, 3, 7]
[-10, 4, 6]
[-10, 5, 5]
[-9, -5, 14]
[-9, -4, 13]
[-9, -3, 12]
[-9, -2, 11]
[-9, -1, 10]
[-9, 0, 9]
[-9, 1, 8]
[-9, 2, 7]
[-9, 3, 6]
[-9, 4, 5]
[-8, -6, 14]
[-8, -5, 13]
[-8, -4, 12]
[-8, -3, 11]
[-8, -2, 10]
[-8, -1, 9]
[-8, 0, 8]
[-8, 1, 7]
[-8, 2, 6]
[-8, 3, 5]
[-8, 4, 4]
[-7, -7, 14]
[-7, -6, 13]
[-7, -5, 12]
[-7, -4, 11]
[-7, -3, 10]
[-7, -2, 9]
[-7, -1, 8]
[-7, 0, 7]
[-7, 1, 6]
[-7, 2, 5]
[-7, 3, 4]
[-6, -6, 12]
[-6, -5, 11]
[-6, -4, 10]
[-6, -3, 9]
[-6, -2, 8]
[-6, -1, 7]
[-6, 0, 6]
[-6, 1, 5]
[-6, 2, 4]
[-6, 3, 3]
[-5, -5, 10]
[-5, -4, 9]
[-5, -3, 8]
[-5, -2, 7]
[-5, -1, 6]
[-5, 0, 5]
[-5, 1, 4]
[-5, 2, 3]
[-4, -4, 8]
[-4, -3, 7]
[-4, -2, 6]
[-4, -1, 5]
[-4, 0, 4]
[-4, 1, 3]
[-4, 2, 2]
[-3, -2, 5]
[-3, -1, 4]
[-3, 0, 3]
[-3, 1, 2]
[-2, -2, 4]
[-2, -1, 3]
[-2, 0, 2]
[-2, 1, 1]
[-1, -1, 2]
[-1, 0, 1]
[0, 0, 0]

相关代码放在个人github:https://github.com/gannyee/LeetCode/tree/master/src

版权声明:本文为博主原创文章,未经博主允许不得转载。个人github代码空间:https://github.com/gannyee

时间: 2024-07-30 13:44:16

LeetCode解题报告--3 Sum的相关文章

leetCode解题报告5道题(十)

Disk Schedule Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2368    Accepted Submission(s): 333 Problem Description 有很多从磁盘读取数据的需求,包括顺序读取.随机读取.为了提高效率,需要人为安排磁盘读取.然而,在现实中,这种做法很复杂.我们考虑一个相对简单的场景.磁

leetCode解题报告5道题(十一)

题目一:Subsets Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2]

leetCode解题报告5道题(八)

题目一: Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the

leetCode解题报告5道题(九)

题目一:Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example,If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] 分析: 题意给我们一个数字n, 和一个数字k,让我们求出从 1~~n中取出k个数所能得到的组合数 所

LeetCode解题报告:LRU Cache

LRU Cache Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise retu

leetCode解题报告5道题(六)

题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the

leetCode解题报告5道题(七)

先送上亚马逊传送门:<黑客与画家>:硅谷创业之父 Paul Graham 文集 再送上一个思维导图: 最好的办法就是自己创业或者加入创业公司 一个命题 命题 创业是一个压缩的过程,所有工作压缩成短短几年. 你不再是低强度的工作四十年,而是以极限强度工作四年 举例解释 一个优秀的黑客去除各种障碍,工作效率可以是在公司时的36倍. 假设他年薪8万美元,那么一个勤奋工作,摆脱杂事干扰的聪明黑客, 他的工作相当于年薪200万美元的价值 这里说的是极限情况,休闲时间为0,工作强度足以危害到健康. 守恒定

LeetCode解题报告:Reorder List

Reorder List Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values. For example,Given {1,2,3,4}, reorder it to {1,4,2,3}. 思路: 1.利用快慢两个指针将链表一分为二: 2.针对第二个子链表求倒序

LeetCode解题报告:Linked List Cycle &amp;&amp; Linked List Cycle II

Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using extra space? Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follo