2017-09-04 89 views
-5

我正在嘗試糾正我在採訪中遇到的特定問題(問題是找到頻率恰恰爲f的最小元素)。我認爲我已經在很大程度上設計瞭解決方案,但是問題是關於一些故障,而這又會產生一些錯誤的輸出。我試過了所有的東西,檢查並重新檢查了代碼,但問題仍然存在。由於我在java編程中是初學者,所以請不要太在意,所以請幫助我。以下是我的嘗試:不生成預期輸出的代碼

public static int smallestKFreq(int a[], int n, int f) 
    { 
     HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 

     // Map is used to store the count of 
     // elements present in the array 
     for (int i = 0; i < n; i ++) 

      if (map.containsKey(a[i])) 
       map.put(a[i], m.get(a[i]) + 1); 

      else map.put(a[i], 1); 

     // Traverse the map and find minimum 
     // element with frequency f. 
     int res = Integer.MAX_VALUE; 
     Set<Integer> s = map.keySet(); 

     for (int temp : s) 
      if (map.get(temp) == f) 
       res = Math.min(res, temp); 

     return (res != Integer.MAX_VALUE)? res : 1; 
    } 
+2

*「守則產生編譯時錯誤」 * *** ***什麼編譯錯誤? –

+0

先生它產生不同的輸出!!!'{1,2,3,2,2,1,3}'然後輸出是'3' – BaijNR

+1

所以...... **不**編譯時錯誤。 –

回答

1

好吧所以看看你的問題,好像你有錯了return聲明!

應該

return (res !=Integer.MAX_VALUE)?res : -1;

試試這個我想應該解決這個問題...

+0

謝謝@ mandy8055,它的工作,但請你會告訴我爲什麼替換'-1'的作品? – BaijNR

+0

@BaijNR如果你已經理解了你寫的邏輯,那麼它清楚地表明,返回結果的最小值和最大頻率,所以結果必須返回該元素或根本沒有任何東西...... – Mandy8055