3Sum solution Java with hashmap + list 3 pass


  • 0
    W
        public List<List<Integer>> returnList(int[] nums){
            List<List<Integer>> returnList = new ArrayList<List<Integer>>();
            List<Integer> list = new ArrayList<Integer>();
            Set<String> duplicateMaster = new HashSet<>();
            Map<Integer, Integer> myMap = new HashMap<>();
    
            for(int i = 0; i< nums.length; i++){
                list.add(nums[i]);
                myMap.put(nums[i], i);
            }
    
           for(int i = 0; i< list.size(); i++){
                Integer val1 = list.get(i);
               for(int j = i+1; j< list.size(); j++){
                    Integer val2 = list.get(j);
                    Integer result = val1+val2;
                    if(((result == 0 && myMap.containsKey(0)) || myMap.containsKey(-result)) && (myMap.get(-result) != i && myMap.get(-result) != j)){
                        Integer val3 = list.get(myMap.get(-result));
                        ArrayList<Integer> solution = new ArrayList<Integer>();
                        solution.add(val1);
                        solution.add(val2);
                        solution.add(val3);
                        Collections.sort(solution);
                        String str = "";
                        for(Integer m: solution){
                            str = str + m;
                        }
                        if(!duplicateMaster.contains(str)){
                            duplicateMaster.add(str);
                            returnList.add(solution);
                        }
                    }
                }
            }
            return returnList;
        }
    

Log in to reply
 

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