【发布时间】:2021-05-24 15:38:33
【问题描述】:
我正在尝试解决这个问题https://practice.geeksforgeeks.org/problems/triplet-sum-in-array-1587115621/1# 我使用 HashMap 来存储所有可能的总和以及我已存储总和的索引数组。这是我的代码
class Solution
{
//Function to find if there exists a triplet in the array A[] which sums up to X.
public static boolean find3Numbers(int arr[], int n, int X){ `
HashMap<Integer,ArrayList<Pair>> hm=new HashMap<>();
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(!hm.containsKey(arr[i]+arr[j])){hm.put(arr[i]+arr[j],new ArrayList<>());}
Pair pair=new Pair(i,j);
ArrayList<Pair> list=hm.get(arr[i]+arr[j]);
list.add(pair);
hm.put(arr[i]+arr[j],list);
}
}
for(int i=0;i<n;i++){
if(hm.containsKey(X-arr[i])){
ArrayList<Pair> p=hm.get(X-arr[i]);
for(int k=0;k<p.size();k++){
if(p.get(k).ind1!=i && p.get(k).ind2!=i)return true;
}
}
}
return false;
}
public static class Pair{
int ind1;
int ind2;
Pair(int i,int j){
ind1=i;
ind2=j;
}
}
}
请告诉我为什么我会得到 TLE?
【问题讨论】:
-
什么是 TLE?另外,你能在这里描述任务而不是链接到它吗?链接可能会中断,从而使问题对其他人毫无用处。另请参阅How to Ask。
标签: java arrays data-structures hashmap sum