我刚刚开始学习java。我试图编写一个程序来从三个不同的数组中找到三个元素,即a + b + c = sum。 (我避免使用三个for循环来提高效率)
我收到以下错误。
10: error: cannot find symbol
HashMap<int> s = new HashMap<int>();
^
class HashMap
class YesorNo
这是我的代码:
class YesorNo
{
// Function to check if there is an element from
// each array such that sum of the three elements
// is equal to given sum.
boolean findTriplet(int a1[], int a2[], int a3[],
int n1, int n2, int n3, int sum)
{
// Store elements of first array in hash table
HashMap<int> s = new HashMap<int>();
//unordered_set <int> s;
for (int i=0; i<n1; i++)
s.add(a1[i]);
// sum last two arrays element one by one
for (int i=0; i<n2; i++)
{
for (int j=0; j<n3; j++)
{
// Consider current pair and find if there
// is an element in a1[] such that these
// three form a required triplet
if (s.find(sum - a2[i] - a3[j]) != s.end())
return true;
}
}
return false;
}
// Driver Code
public static void main(String[] args)
{
YesorNo check = new YesorNo();
int a1[] = { 1 , 2 , 3 , 4 , 5 };
int n1 = a1.length;
int a2[] = { 2 , 3 , 6 , 1 , 2 };
int n2 = a2.length;
int a3[] = { 3 , 2 , 4 , 5 , 6 };
int n3 = a3.length;
int sum=9;
System.out.println(check.findTriplet(a1, a2, a3, n1, n2, n3, sum));
}
}
答案 0 :(得分:4)
使用HashSet
,它应该是Integer
(因为您不能将基元用作带有集合的通用类型并且更喜欢该接口)。
Set<Integer> s = new HashSet<>();
答案 1 :(得分:0)
HashMap不是单维集合,它不能像注释中提到的@Pshemo那样保存原始类型,如'int'。您必须指定键和映射到该键的值。 有关详细信息,请参阅this tutorial。
要将值插入HashMap,
HashMap<Integer, Integer> s = new HashMap<Integer, Integer>();
for (int i=0; i<n1; i++)
s.put(i, a1[i]);
作为s.find
的替代方案,您可以使用
s.containsValue
但是你不能像写s.end那样跳到HashMap的末尾。您需要按照here提到的一些调整。