LeetCode15 Sum of three numbers (Java implementation)

Title description:

Given an array nums containing n integers, determine if there are three elements a, B, and c in nums such that a + b + c = 0. Please find all the triples that sum to 0 and are not repeated. Note: Repeated triples cannot be included in the answer. Example 1: input: nums = [1, 2, 1, 4] output: [[1, 1, 2], [1, 1]]Copy the code

Code:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        // Sort the array first
        Arrays.sort(nums);
        int len = nums.length;
        // To avoid repetition, use HashSet
        HashSet<List<Integer>> res = new HashSet<>();
        for(int i = 0; i < len; i++) {// Use left and right Pointers
            int L = i + 1;
            int R = len - 1;
            while(L < R) {
                if(nums[i]+nums[L]+nums[R] == 0) {
                    // Add the set that meets the criteria
                    res.add(Arrays.asList(nums[i],nums[L],nums[R])); 
                    L++;
                    R--;
                } else if (nums[i]+nums[L]+nums[R] < 0) { 
                    L++;
                } else {
                    R--;
                }
            } 
        }
        List<List<Integer>> list = new ArrayList<>();
        // Add the result to the list, return
        list.addAll(res);
        returnlist; }}Copy the code