Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

Idea: Simplify this problem from O(n^3) to n square by using two pointers

iterate i and j = i+1 and k = n-1 (j and k are two pointers we would use)

class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<List<Integer>>();
//two pointers
//set i and move j and k (if sum <0 j++ else k--)
for(int i = 0; i<nums.length; i++){
if (i != 0 && nums[i] == nums[i - 1]) continue; //*****
int j = i+1;
int k = nums.length-1;
while(j<k){
if(nums[i] + nums[j] + nums[k] == 0){
List<Integer> temp = new ArrayList<Integer>();
temp.add(nums[i]); temp.add(nums[j]);temp.add(nums[k]);
//if(!res.contains(temp)) //why add this make TLE ****
res.add(temp);
++j;
//System.out.println("wei");
while (j < k && nums[j] == nums[j-1]) ++j; ****
}else if(nums[i] + nums[j] + nums[k] < 0){
j++;
}else {
k--;
}
}
}
return res;
}
}

1.avoid the duplicate elements -1 -1 (for the same values, there are same results)

2. avoid using contains because of O(n), that is the reason why we need check the duplicate elements manually instead of using contains

Solution 2: using hashmap: n^2*lgn

class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
if(i!=0 && nums[i-1] == nums[i]) continue;
Set<Integer> set = new HashSet<>(); // no duplicate elements
for(int j = i+1; j<nums.length; j++){// nums[j] : b and c means: count all nums[i] as c
if(set.contains(-nums[i]-nums[j])){ // c
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);temp.add(nums[j]);temp.add(-nums[i]-nums[j]);
res.add(temp);
//avoid the duplicate elemnts
++j;
while(j < nums.length && nums[j-1]==nums[j]) j++;
--j;
}
if(j<nums.length)
set.add(nums[j]);
}
}
return res;
}
}

hashset

how to using two loop to represent three numbers.

1. treat all nums[j] as c(the third elemnts)

2. As a+b+c = 0, c = -a-b, we need find a and b to satisfy the requirement

Great reference: https://fizzbuzzed.com/top-interview-questions-1/#twopointer -- speak human language nice.

*15. 3Sum (three pointers to two pointers), hashset的更多相关文章

  1. leetcode 15. 3Sum 二维vector

    传送门 15. 3Sum My Submissions Question Total Accepted: 108534 Total Submissions: 584814 Difficulty: Me ...

  2. LeetCode 15 3Sum [sort] <c++>

    LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...

  3. 1. Two Sum&&15. 3Sum&&18. 4Sum

    题目: 1. Two Sum Given an array of integers, return indices of the two numbers such that they add up t ...

  4. leetcode 1.Two Sum 、167. Two Sum II - Input array is sorted 、15. 3Sum 、16. 3Sum Closest 、 18. 4Sum 、653. Two Sum IV - Input is a BST

    1.two sum 用hash来存储数值和对应的位置索引,通过target-当前值来获得需要的值,然后再hash中寻找 错误代码1: Input:[3,2,4]6Output:[0,0]Expecte ...

  5. 15. 3Sum、16. 3Sum Closest和18. 4Sum

    15 3sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = ...

  6. 刷题15. 3Sum

    一.题目说明 题目非常简洁15. 3Sum,读懂题目后,理解不难. 但 实话说,我们提交代码后,Time Limit Exceeded,最主要的是给了非常长的测试用例,我本地运行后87秒,确实时间非常 ...

  7. LeetCode 15. 3Sum(三数之和)

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  8. [leetcode]15. 3Sum三数之和

    Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find ...

  9. 蜗牛慢慢爬 LeetCode 15. 3Sum [Difficulty: Medium]

    题目 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all ...

随机推荐

  1. Photoshop入门教程(三):图层

    学习心得:图层可以说是Photoshop的核心,看似简单,但是对于图像的各种编辑都是基于图层.他就像一层透明的.没有厚度的玻璃纸,每张玻璃纸设置不同的效果,层层叠加,最后显现出绚烂的效果. 在进行图像 ...

  2. 6-----selenuim和phantonJs处理网页动态加载数据的爬取

    动态数据加载处理 一.图片懒加载 什么是图片懒加载? 案例分析:抓取站长素材http://sc.chinaz.com/中的图片数据 #!/usr/bin/env python # -*- coding ...

  3. android window(二)从getSystemService到WindowManagerGlobal

    在Activity调用getSystemService(WINDOW_SERVICE) 调用的是父类ContextThemeWrapper package android.view; public c ...

  4. cpp 学习笔记

    1.C++中模仿gets是  getline(cin, string object) #include <bits/stdc++.h> #define IOS ios::sync_with ...

  5. bootstrap3-dialog:更强大、更灵活的模态框(封装好的模态框)

    用过bootstrap框架的同学们都知道,bootstrap自带的模态框用起来很不灵活,可谓鸡肋的很.但nakupanda开源作者封装了一个更强大.更灵活的模态框——bootstrap3-dialog ...

  6. python文件操作和集合(三)

    对文件的操作分三步: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句柄操作文件 3.关闭文件. 文件基本操作:         f = open('file.txt','r') #以 ...

  7. MATLAB矩阵操作和算术运算符

    矩阵的表示 矩阵之间用空格或者是逗号间隔 矩阵可以拼接(可以用矩阵拼接) 实部矩阵和虚部矩阵构成复数矩阵,一一对应. 冒号表达式: 格式: e1:e2:e3 e1表示初始值    e2表示步长   e ...

  8. 工作采坑札记:3. Spark中es-hadoop插件异常解决

    1. Es-Hadoop异常: org.elasticsearch.hadoop.EsHadoopException: Could not write all entries [615/300864] ...

  9. mysql java 通用AES加密

    最近有个需求,需要对数据库某些字段加密,调研发现采用AES加密的方式较多,而且反向解密速度快,符合需求,于是采用:下面是遇到的问题及相关代码 首先第一个问题,AES的秘钥是16位,mysql的密码长度 ...

  10. ASP.NET那点不为人知的事(一)

    http://www.cnblogs.com/OceanEyes/archive/2012/08/13/aspnetEssential-1.html#_label0 我们上网时,在浏览器地址输入网址: ...