2sum问题
这道题在剑指 offer 上面有,具体的链接为https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&tqId=11195&tPage=3&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
不会太难,所以此处不再赘述3-sum问题
这道题在 Leetcode 上面有,链接为:https://leetcode.com/problems/3sum/description/
题目描述:
Given an array nums of n integers, are there elements a, b, c 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]]
解题思路:
1)先将数组排序
2)从最后一个数字开始,把他的指针设为i, j = 0, k = i -1;
然后若 j+k = -i,则表示找到了一个三元组
若 j + k < -i, 则 j 往右移动
若 j + k > -i, 则k往左移动
复杂度分析:由于 j 和 k 是相向运动的,所以第二层的循环会在n次之内结束,时间复杂度为O(n^2)
代码实现:
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> a = new ArrayList<List<Integer>>();
HashSet<String> hs = new HashSet<String>();