my solution in java


  • 0
    W
    import java.util.*;
    
    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            Arrays.sort(nums);
            HashSet<Triple> set = new HashSet<Triple>();
            for (int i = 0; i < nums.length - 2; i++) {
                for (int j = nums.length - 1; j > i + 1; j--) {
                    for (int k = i + 1; k < j; k++) {
                        if (nums[i] + nums[k] + nums[j] == 0) {
                            set.add(new Triple(nums[i], nums[k], nums[j]));
                        }
                    }
                }
            }
            for (Triple t : set) {
                res.add(Arrays.asList(t.x, t.y, t.z));
            }
            return res;
        }
        
        static class Triple {
            int x,y,z;
            public Triple(int x, int y, int z) {
                this.x = x;
                this.y = y;
                this.z = z;
            }
            
            @Override
            public int hashCode() {
                return 13 * x + 7 * y + 3 * z;
            }
            @Override
            public boolean equals(Object o) {
                return (o instanceof Triple) &&
                     (((Triple)o).x == x && ((Triple)o).y == y && ((Triple)o).z == z);
            }
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.