Question 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.
The idea was to use deep search to solve the problem. Later, it was found that it was difficult to ensure that the results were not repeatedly combined with deep search. Therefore, the sorting + dual-pointer fixed solution was adopted, and a duplicate judgment mechanism was added at the same time.
AC code
public class Solution { public List
> threeSum(int[] num) { List
> res = new ArrayList
>(); if (num.length < 3) { return res; } Arrays.sort(num); for (int i = 0; i < num.length - 2; i++) { // avoid duplicate if (i == 0 || num[i] > num[i - 1]) { int start = i + 1; int end = num.length - 1; while (start < end) { int stand = num[i] + num[start] + num[end]; if (stand == 0) { ArrayList
tmp = new ArrayList
(); tmp.add(num[i]); tmp.add(num[start]); tmp.add(num[end]); res.add(tmp); start++; end--; //avoid duplicate while (start < end && num[start] == num[start - 1]) { start ++; } while (start < end && num[end] == num[end + 1]) { end --; } } else if (stand > 0) { end--; } else { start++; } } } } return res; }}
I remember that I had to go back to didu to work in ALI five days at home. I am not willing to give up my parents, work hard, and strive for financial freedom! Spend more time with your family.