2017-02-11 189 views
1

我剛開始學習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)); 
     } 
    } 
+1

您是否還有必要在您的程序中導入? – opensam

+1

使用它來查找正確的集合:http://www.sergiy.ca/img/doc/java-map-collection-cheat-sheet.gif獲取值的列表(如數組,但沒有限制):列表 - > ArrayList ...,Map - > HashMap ..如果對 azro

回答

0

HashMap的不是一個單一的維度集合和@Pshemo在評論中提到它不能容納原始類型,比如「詮釋」。您必須指定鍵和映射到該鍵的值。 有關更多信息,請參閱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 

但是怎麼寫,是你不能妄下HashMap的結束。結束。你需要遵循一些調整here

3

使用HashSet,它應該是一個Integer(因爲你不能使用原語作爲泛型類型具有收藏和使用的界面)。

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

「你不能使用基元與集合」你的意思是我們不能使用基元作爲*泛型*。我們可以使用基元與集合:'s.add(1)'將自動複製:)將叉罰款 – Pshemo

+0

@Pshemo是的。是的,我的意思是。 :) –

相關問題