Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@st0le
Created June 30, 2013 01:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save st0le/5893445 to your computer and use it in GitHub Desktop.
Save st0le/5893445 to your computer and use it in GitHub Desktop.
3SUM Solution : O(n^2) algorithm with Hash Table
// Complexity - O(n^2), Space Complexity - O(n^2)
private int[] findTriple_3(int[] A) {
Map<Integer, int[]> map = new HashMap<Integer, int[]>();
for (int i = 0, l = A.length; i < l; i++) {
map.clear();
for (int j = i + 1; j < l; j++) {
if (map.containsKey(A[j])) {
int[] pair = map.get(A[j]);
return new int[]{pair[0], pair[1], A[j]};
} else
map.put(-A[i] - A[j], new int[]{A[i], A[j]});
}
}
return null;
}
@bahbahamini
Copy link

I have used the same method but it has error
class Solution {
public List<List> threeSum(int[] nums) {
List<List> result = new ArrayList<List>();
if( nums==null || nums.length<3) return result;
//Arrays.sort(nums);
Map<Integer,Integer> map= new HashMap<>();
for (int i = 0;i < nums.length; i++) {
map.clear();
//for(int i=0; i<nums.length-2;i++){
for(int j=i+1; j<nums.length; j++){
int comp=-(nums[i]+nums[j]);
ArrayList returnList = new ArrayList<>();
if(map.containsKey(comp) && (map.get(comp)!=i) && (map.get(comp)!=j)){
returnList.add((Integer)nums[i]);
returnList.add((Integer)nums[j]);
returnList.add((Integer)comp);
Collections.sort(returnList);
if(!result.contains(returnList)) {
result.add(returnList);
}
}
else
map.put(nums[i],i);
map.put(nums[j],j);
}

    }
    return result;

}
//throw new IllegalArgumentException("No 3sum solution");

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment