Created
June 30, 2013 01:47
-
-
Save st0le/5893445 to your computer and use it in GitHub Desktop.
3SUM Solution : O(n^2) algorithm with Hash Table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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);
}
}