r/javahelp • u/Air-Alert • Jul 11 '22
LeetCode 3 sum help!!
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
Set<List<Integer>> fin = new HashSet<>();
for(int i = 0; i < nums.length; i++){
Map<Integer, Integer> map = new HashMap<>();
int target = -nums[i];
for(int j = 0; j < nums.length; j++){
if(i == j)
continue;
if(map.containsKey(nums[j])){
List<Integer> tmp = new ArrayList<>();
tmp.add(nums[j]);
tmp.add(map.get(nums[j]));
tmp.add(nums[i]);
Collections.sort(tmp);
fin.add(tmp);
}
else{
map.put(target-nums[j], nums[j]);
}
}
}
//System.out.println(fin);
Iterator<List<Integer>> itr = fin.iterator();
while(itr.hasNext()) {
ans.add(itr.next());
}
return ans;
}
}
0
Upvotes
0
u/Air-Alert Jul 11 '22
This is my code. I failed the last two test cases with time limit exceeded error every time. I thought my code is O(n^2) which should be fast enough for this problem. Can anyone tell me why my code failed>3?