博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
*15. 3Sum (three pointers to two pointers), hashset
阅读量:5039 次
发布时间:2019-06-12

本文共 2291 字,大约阅读时间需要 7 分钟。

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
> threeSum(int[] nums) { Arrays.sort(nums); List
> res = new ArrayList
>(); //two pointers //set i and move j and k (if sum <0 j++ else k--) for(int i = 0; i
temp = new ArrayList
(); 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
> threeSum(int[] nums) { List
> res = new ArrayList
>(); Arrays.sort(nums); for(int i = 0; i < nums.length; i++){ if(i!=0 && nums[i-1] == nums[i]) continue; Set
set = new HashSet<>(); // no duplicate elements for(int j = i+1; j
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

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.

转载于:https://www.cnblogs.com/stiles/p/leetcode15.html

你可能感兴趣的文章
【ASP.NET开发】菜鸟时期的ADO.NET使用笔记
查看>>
android圆角View实现及不同版本号这间的兼容
查看>>
OA项目设计的能力③
查看>>
Cocos2d-x3.0 文件处理
查看>>
全面整理的C++面试题
查看>>
Web前端从入门到精通-9 css简介——盒模型1
查看>>
Activity和Fragment生命周期对比
查看>>
OAuth和OpenID的区别
查看>>
android 分辨率自适应
查看>>
查找 EXC_BAD_ACCESS 问题根源的方法
查看>>
国外媒体推荐的5款当地Passbook通行证制作工具
查看>>
日常报错
查看>>
list-style-type -- 定义列表样式
查看>>
hibernate生成表时,有的表可以生成,有的却不可以 2014-03-21 21:28 244人阅读 ...
查看>>
mysql-1045(28000)错误
查看>>
Ubuntu 编译出现 ISO C++ 2011 不支持的解决办法
查看>>
1.jstl c 标签实现判断功能
查看>>
Linux 常用命令——cat, tac, nl, more, less, head, tail, od
查看>>
超详细的Guava RateLimiter限流原理解析
查看>>
VueJS ElementUI el-table 的 formatter 和 scope template 不能同时存在
查看>>