3Sum & 4Sum

3 Sum

Given an array S of n integers, are there elements abc in Ssuch that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Notice

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.

Example

For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:

(-1, 0, 1)
(-1, -1, 2)

分析:

这题还是很简单的,使用3个指针即可解决问题。关键是里面重复数字的处理需要当心。

 1 public class Solution {
 2     /**
 3      * @param numbers : Give an array numbers of n integer
 4      * @return : Find all unique triplets in the array which gives the sum of zero.
 5      */
 6     public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
 7         ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
 8         if(num == null || num.length < 3) {
 9             return rst;
10         }
11         Arrays.sort(num);
12         for (int i = 0; i < num.length - 2; i++) {
13             if (i != 0 && num[i] == num[i - 1]) {
14                 continue; // to skip duplicate numbers; e.g [0,0,0,0]
15             }
16
17             int left = i + 1;
18             int right = num.length - 1;
19             while (left < right) {
20                 int sum = num[left] + num[right] + num[i];
21                 if (sum == 0) {
22                     ArrayList<Integer> tmp = new ArrayList<Integer>();
23                     tmp.add(num[i]);
24                     tmp.add(num[left]);
25                     tmp.add(num[right]);
26                     rst.add(tmp);
27                     left++;
28                     right--;
29                     while (left < right && num[left] == num[left - 1]) { // to skip duplicates
30                         left++;
31                     }
32                     while (left < right && num[right] == num[right + 1]) { // to skip duplicates
33                         right--;
34                     }
35                 } else if (sum < 0) {
36                     left++;
37                 } else {
38                     right--;
39                 }
40             }
41         }
42         return rst;
43     }
44 }

4Sum

Given an array S of n integers, are there elements abc, andd in S such that a + b + c + d = target?

Find all unique quadruplets in the array which gives the sum of target.

Notice

Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.

Example

Given array S = {1 0 -1 0 -2 2}, and target = 0. A solution set is:

(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
分析:原理同上

 1 public class Solution {
 2     /**
 3      * @param numbers : Give an array numbersbers of n integer
 4      * @param target : you need to find four elements that‘s sum of target
 5      * @return : Find all unique quadruplets in the array which gives the sum of
 6      *           zero.
 7      */
 8     public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
 9         ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
10         if(num == null || num.length < 4) {
11             return rst;
12         }
13         Arrays.sort(num);
14         for (int i = 0; i <= num.length - 4; i++) {
15             if (i != 0 && num[i] == num[i - 1]) {
16                 continue; // to skip duplicate numbers; e.g [0,0,0,0]
17             }
18             for (int j = i + 1; j <= num.length - 3; j++) {
19                 if (j != i + 1 && num[j] == num[j - 1]) {
20                     continue; // to skip duplicate numbers; e.g [0,0,0,0]
21                 }
22                 int left = j + 1;
23                 int right = num.length - 1;
24                 while (left < right) {
25                     int sum = num[left] + num[right] + num[i] + num[j] - target;
26                     if (sum == 0) {
27                         ArrayList<Integer> tmp = new ArrayList<Integer>();
28                         tmp.add(num[i]);
29                         tmp.add(num[j]);
30                         tmp.add(num[left]);
31                         tmp.add(num[right]);
32                         rst.add(tmp);
33                         left++;
34                         right--;
35                         while (left < right && num[left] == num[left - 1]) { // to skip duplicates
36                             left++;
37                         }
38                         while (left < right && num[right] == num[right + 1]) { // to skip duplicates
39                             right--;
40                         }
41                     } else if (sum < 0) {
42                         left++;
43                     } else {
44                         right--;
45                     }
46                 }
47             }
48
49         }
50         return rst;
51     }
52 }
转载请注明出处: cnblogs.com/beiyeqingteng/
时间: 2024-09-29 17:04:04

3Sum & 4Sum的相关文章

2Sum,3Sum,4Sum,kSum,3Sum Closest系列

1).2sum 1.题意:找出数组中和为target的所有数对 2.思路:排序数组,然后用两个指针i.j,一前一后,计算两个指针所指内容的和与target的关系,如果小于target,i右移,如果大于,j左移,否则为其中一个解 3.时间复杂度:O(nlgn)+O(n) 4.空间:O(1) 5.代码: void twoSum(vector<int>& nums,int numsSize,int target,vector<vector<int>>& two

LeetCode——4Sum &amp; 总结

LeetCode--4Sum & 总结 前言 有人对 Leetcode 上 2Sum,3Sum,4Sum,K Sum问题作了总结: http://blog.csdn.net/nanjunxiao/article/details/12524405 对于同类问题做了代码模型: int i = starting; //头指针 int j = num.size() - 1; //尾指针 while(i < j) { int sum = num[i] + num[j]; if(sum == targe

LeetCode——4Sum &amp;amp; 总结

LeetCode--4Sum & 总结 前言 有人对 Leetcode 上 2Sum,3Sum,4Sum,K Sum问题作了总结: http://blog.csdn.net/nanjunxiao/article/details/12524405 对于同类问题做了代码模型: int i = starting; //头指针 int j = num.size() - 1; //尾指针 while(i < j) { int sum = num[i] + num[j]; if(sum == targe

leetcode--ksum问题--3sum

[题目]:点击打开链接 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: The solution set must not contain duplicate triplets. For example, given arr

【4Sum】cpp

题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending or

算法题丨3Sum Closest

描述 Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 示例 Given array S = {-1 2 1 -4},

代码面试最常用的10大算法

摘要:面试也是一门学问,在面试之前做好充分的准备则是成功的必须条件,而程序员在代码面试时,常会遇到编写算法的相关问题,比如排序.二叉树遍历等等. 在程序员的职业生涯中,算法亦算是一门基础课程,尤其是在面试的时候,很多公司都会让程序员编写一些算法实例,例如快速排序.二叉树查找等等. 本文总结了程序员在代码面试中最常遇到的10大算法类型,想要真正了解这些算法的原理,还需程序员们花些功夫. 1.String/Array/Matrix 在Java中,String是一个包含char数组和其它字段.方法的类

LeedCde题解目录

1. Longest Palindromic Substring ( 最长回文子串 ) 2.Median of Two Sorted Arrays (两个排序数组的中位数) 3.Sqrt(x) 4.Single Number && Single Number (II) 5.Integer to Roman && Roman to Integer 6.3Sum && 4Sum [ && K sum ] && 3Sum Close

最常用的10大算法

1.String/Array/Matrix 在Java中,String是一个包含char数组和其它字段.方法的类.如果没有IDE自动完成代码,下面这个方法大家应该记住: toCharArray() //get char array of a String Arrays.sort() //sort an array Arrays.toString(char[] a) //convert to string charAt(int x) //get a char at the specific ind