2014-01-08 51 views
0

我正在處理相同的任務。我正在粘貼mycode。它顯示運行時錯誤,當我試圖運行大量輸入像10億(即k = 10^9)。你能幫我解決這個問題嗎?大輸入運行時錯誤

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.util.Hashtable; 
import java.util.StringTokenizer; 

/* Name of the class has to be "Main" only if the class is public. */ 
class Ideone 
{ 
    static Long counter = (long)0; 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     BufferedReader ob1= new BufferedReader(new InputStreamReader(System.in)); 
     int user_choice= Integer.parseInt(ob1.readLine()); 

     int flag=0; 
     while(user_choice!=0) 
     { 
      user_choice--; 
      StringTokenizer obj; 
      Long n,k; 
      obj=new StringTokenizer(ob1.readLine()); 
      n=Long.parseLong(obj.nextToken()); 
      k=Long.parseLong(obj.nextToken()); 
      Hashtable<Long, Long> hash= new Hashtable<Long, Long>(); 
      while(n!=0) 
      { 
       StringTokenizer obj1; 
       Long start,comp; 
       Long finish; 
       obj1=new StringTokenizer(ob1.readLine()); 
       start=Long.parseLong(obj1.nextToken()); 
       finish=Long.parseLong(obj1.nextToken()); 
       comp=Long.parseLong(obj1.nextToken()); 
       if(flag==0) 
       { 
        for(int i=1;i<=k;i++) 
        { 
         hash.put((long)i,(long)0); 
        } 

       } 
       Long finish1; 
       finish1=hash.get(comp); 
       if(finish1==0) 
       { 
        hash.put(comp,finish); 
        counter++; 
       } 
       else if(finish1<=start) 
       { 
        counter++; 
        hash.put(comp,finish); 
       } 
       n--; 
       flag=1; 
      } 
      flag=0; 
      System.out.println(counter); 
      counter=(long)0; 
      /* for(int i=1;i<=k;i++) 
     System.out.println(hash.get((long)i) +" "+i);*/ 

     } 
    } 
} 

輸入:

2 
3 300000 
1 3 1 
4 6 2 
7 10 3 
3 10000000 
1 3 1 
4 6 2 
7 10 3 

輸出:

Runtime error time: 0.09 memory: 380160 signal:-1 

3 
+4

縮進。我想你。 – Maroun

+0

添加一些調試println()將大大有助於自我解決此問題。 – robnick

+0

沒有關於錯誤的詳細信息?可能是OOM – basiljames

回答

2

下面是捕獲錯誤的Ideone源代碼:http://ideone.com/w2Ub6Y

而不是僅僅throws Exception我這樣做:

System.out.println(Runtime.getRuntime().freeMemory()/1000000.0 + "MB free"); 

try { 

    // the whole program 

} catch(Throwable t) { 
    System.out.println(t.getClass().getName() + " " + t.getMessage()); 
    System.out.println(); 
    for(StackTraceElement elem : t.getStackTrace()) { 
     System.out.println(elem); 
    } 
} 

這確實是一個OutOfMemoryError。輸出是:

 
15.87436MB free 
3 
java.lang.OutOfMemoryError Java heap space 

java.util.Hashtable.rehash(Hashtable.java:496) 
java.util.Hashtable.put(Hashtable.java:560) 
Ideone.main(Main.java:42) 

線42 hash.put:

hash.put((long)i,(long)0); 

〜16MB似乎是一個共同的 「默認」 堆在我的經驗大小。我很驚訝Ideone不會讓它變小。如果你想讓你的Hashtable更大,你需要在本地IDE和increase the heap上運行它。如果你願意,你可以手動使堆非常大。

Java堆應該本身自動成長爲必要的,但:

  • A)Ideone將是明智的禁用和好像你正在使用Ideone(由你的代碼模板的外觀判斷)和
  • B)如果堆增長得太快,你仍然可以得到一個OutOfMemoryError。