LeetCode 15 3Sum 找出数组里面3个数的和等于指定值。
来源:互联网 发布:北京折叠知乎 编辑:程序博客网 时间:2024/06/05 07:11
题目: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)翻译: 给一个数组。找出其中3个数字等于0的组合。 按升序排列。
思路:这道题和前些天刷的Two Sum 原理差不多。只不过是Two Sum的和是前一个数字的相反数。还有一个问题就是,如果当前数字和下一个数字重复,应该排除这些重复,不遍历,减少复杂度。
代码:
public static ArrayList<ArrayList<Integer>> threeSum(int[] num){ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();if(num == null||num.length<3)//如果只有2个数字 或者为空 返回空return res;Arrays.sort(num);for(int i = 0; i<num.length -2;i++)// 保证最后得有num.length-1 和num.length-2两个数,才可以进循环{if(i > 0 && num[i] == num[i-1])//如果要是有重复的直接跳过。continue;ArrayList<ArrayList<Integer>> cur = twoSum(num,i+1,-num[i]); //得到当前数字可以组合出来的数字序列的子集。res.addAll(cur);}return res; } public static ArrayList<ArrayList<Integer>>twoSum (int []num,int start,int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(num == null||num.length < 2) return res; int l = start;//起始位置 int pri = start-1;//当前数字 int r = num.length-1;//终止位置 while(l < r)//采用夹逼,逼近target { if(num[l]+num[r] == target)// { ArrayList<Integer> te = new ArrayList<Integer>();//符合的话 把三个数放入到list中 te.add(num[pri]); te.add(num[l]); te.add(num[r]); res.add(te); int k = l + 1;//从l的下一个开始 去除重复。 while(k < r&& num[k] == num[l]) k++; l = k; k = r - 1;//去除R的重复 while(k > l &&num[k] == num[r]) k--; r = k; } else if(num[l] + num[r] > target)//夹逼 r--; else l++; } return res; }如果要是求4 sum的话 直接可以在写个函数求出3 sum的 然后在整合到4sum中。原理其实差不多。
更好的办法,还有待考虑。
0 0
- LeetCode 15 3Sum 找出数组里面3个数的和等于指定值。
- LeetCode 18 4sum 找出4个数,使得他们的和等于target
- Two Sum(找出数组中两个和等于指定数字的元素)
- 在数组中找出四个数字的和等于指定数字(4Sum)
- LeetCode 16 3Sum Closest 找出最接近指定target的三个数的和
- LeetCode | 3Sum(三个数的和等于0)
- LeetCode 15 3Sum(3个数的和)
- 从数组中找出两个元素的和等于指定数值,并输出位置。
- 找出有序数组中和等于指定数的两个数
- leetcode-java.T001_TwoSum 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字
- [Leetcode #1]Two Sum 从数组中找出和为特定值的两个数
- 找出数组中左加和等于右加和的数字
- 数组中找到2,3,n个数等于一个值
- 找出和值等于指定值的元素,如有序数组{1,2,6,23,43,64},求和等于25的两个和数则将是元素2和23,时间复杂度是0(n)。
- LeetCode刷题记录7-从数组中找出指定条件的3个数字
- 指定数组的下标,如果数组元素等于指定值
- 找出一个有序数组中任意2数之和等于给出的第三个数
- 阿里——给一个整形数组,找出其中和等于给定值的组合
- js字符串方法replace()的第二个参数为函数讲解
- 判断是否是手机等移动端访问
- PinnedSectionListView使用
- 我的Linux问题小记录(随时更新)
- MFC并列显示多个工具栏(Toolbar)
- LeetCode 15 3Sum 找出数组里面3个数的和等于指定值。
- 写在前面的话
- Caused by: java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z解决方案
- 搜索算法总结
- AndroidSDK requires Android Developer和android sdk更新失败的问题
- 解题报告 之 SGU242 Student's Morning
- smarty 调用php内置函数
- 【tcp-ip学习总结】一些常用的winsock API函数
- WIN7 Wireshark: There are no interfaces on which a capture can be done