2017-02-11 17 views
1

私はちょうどjavaを学び始めました。私は、a + b + c = sumのような3つの異なる配列から3つの要素を見つけるプログラムを書こうとしています。 (ループを3つ使用して効率を上げるのは避けています)一度に1つの値をハッシュテーブルに格納する方法。

次のエラーが表示されます。

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)); 
     } 
    } 
+1

また、プログラムに必要なインポートがありますか? – opensam

+1

値のリスト(配列のように、ただし制限なし)のリストについては、正しいCollection:http://www.sergiy.ca/img/doc/java-map-collection-cheat-sheet.gifを参照してください。List - > ArrayList ...、Map - > HashMap ..対の場合 azro

答えて

0

HashMapのは、単一のディメンションコレクションではなく、@Pshemoはコメントで述べたように、それは「int型」のようなプリミティブ型を保持することはできません。キーと、そのキーにマップされた値を指定する必要があります。 詳細については、this tutorialを参照してください。 HashMapの値を挿入するには

s.findための代替として

HashMap<Integer, Integer> s = new HashMap<Integer, Integer>(); 
for (int i=0; i<n1; i++) 
     s.put(i, a1[i]); 

、あなたは

s.containsValue 

を使用することができますしかし、あなたはSを書かれているようあなたはHashMapのの最後にジャンプすることはできません。終わり。あなたはhereと言われているいくつかの微調整に従う必要があります。

3

HashSetを使用し、(あなたがコレクションでジェネリック型としてプリミティブを使用して、インターフェイスを好むことができないので)それはIntegerする必要があります。

Set<Integer> s = new HashSet<>(); 
+2

"コレクションでプリミティブを使用することはできません"ということは、*ジェネリック型*としてプリミティブを使用できないことを意味します。コレクションでプリミティブを使うことができます: 's.add(1)'は自動バイナリのおかげでとてもうまくフォークします:) – Pshemo

+0

@Pshemoはい。はい、私はそれを意味します。 :) –

関連する問題