leetcode 3sum
来源:互联网 发布:万方数据库论文官网 编辑:程序博客网 时间:2024/06/16 12:25
原题: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.
题意:给定一个数组num,求数组中三个数字相加为0的所有组合
思路:和上一篇twoSum类似,注意不同的地方。twoSum解是唯一的,而3sum不一定是唯一的
基本的想法还是暴力搜索,时间复杂度O(n^3),不是理想的答案
由于3sum是建立在twoSum的基础上的,可以选择固定一个数字,让余下的数字进行twoSum的操作。
和twoSum不一样的地方是,twoSum使用了hashMap,在3sum中当然也可以使用HashMap,但是用hashMap有一个重复解的问题(twoSum只有一个解,所以不考虑重复解问题)。这里使用一种更好的方法,头尾指针法,前提是要进行排序,排序后让两个指针分别指向数组的头和尾,不断往中间移动两个指针,获取到所有的解,代码如下:
import java.util.ArrayList;import java.util.Arrays;public class Solution { private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); public ArrayList<ArrayList<Integer>> threeSum(int[] num) { Arrays.sort(num); for(int i = 0;i<num.length-2;i++) { if(i>0 && num[i] == num[i-1]) continue; threeSumHelp(num[i],num,i+1); } return result; } public void threeSumHelp(int value,int[] num,int low) { int target = 0 - value; int high = num.length-1; while(low<high) { if(num[low] + num[high] == target)//获得了一个解 { ArrayList<Integer> ans = new ArrayList<Integer>(); ans.add(value); ans.add(num[low]); ans.add(num[high]); result.add(ans); low++; high--; while(num[low] == num[low-1] && low<=high) low++; while(num[high] == num[high+1] && low<=high) high--; } else if(num[low] + num[high]>target){high--;} else { low++;} } }}
时间复杂度为 排序O(nlogn) + O(n^2) = O(n ^ 2 )
由于排序的时间复杂度低于 O(n^2),因此先进行排序再作处理。这样在不耗费空间的前提下,完成程序。
阅读全文
0 0
- 【Leetcode】3Sum (Sum)
- Leetcode:2Sum,3Sum
- 【Leetcode】3Sum Closest (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 3Sum
- LeetCode: 3 Sum Closest
- leetcode - 3 Sum
- leetcode - 3 sum closest
- leetcode 3Sum
- leetcode 3Sum Closest
- LeetCode: 3Sum
- 过程中遇见的错误
- STM32输出PWM时,PWM1和PWM2的区别
- mysql 索引 优化 面试
- TCP数据段格式
- self与self class有什么用法上的区别
- leetcode 3sum
- codeigniter【day 1】
- Windows下安装python3.5+tensorflow
- windows7如何批量关闭系统的运行程序
- MySQL数据库(30)
- 英文停用词(转载)
- 基于随机采样获取训练、测试数据示例(Python)
- jeecg中的查询实体CriteriaQuery的多字段排序的实现
- JavaScript块级作用域, let, const介绍