2012-03-31 63 views
-2

給定數組,我需要找出在該數組中有多少個單調遞增的子數組?例如,[0,1,3,1,2]具有2個單調子數組:[0,1,3]和[1,2]。查找單調遞增的子數組的數量

public class SUB_ARRAY { 
    public static void main(String a[]){ 
     int[] x = new int[6]; 
     x[0]=1; 
     x[1]=2; 
     x[2]=3; 
     x[3]=6; 
     x[4]=9; 
     x[5]=10; 
     ArrayList<Object> arraylist = new ArrayList<Object>(); 
     HashSet list = new HashSet(); 
     for (int i=0; i< (x.length -1); i++){ 
      if (x[i+1]> x[i]){ 
       list.add(x[i]); 
       list.add(x[i+1]); 

      } else if (x[i+1] < x[i] || x[i+1]==x[i]) { 
       arraylist.add(list.clone());  
       list.clear();  
      } 
     }  
     System.out.println(arraylist.size()); 

    }  
} 

輸出爲:0(而不是1)。

那麼,我錯了?

+2

你爲什麼要使用一個HashSet(爲什麼給它取名爲 「清單」?)?爲什麼ArrayList?爲什麼不使用簡單的計數器變量?爲什麼在這裏有108個帖子是你的代碼格式化的所有左對齊? – 2012-03-31 13:46:16

+1

投票結束:要求陌生人通過檢查發現代碼中的錯誤並不是富有成效的。您應該通過使用調試器或打印語句來識別(或至少隔離)問題,然後返回一個更具體的問題。 – 2012-03-31 13:47:59

+0

@ Hovercraft Full Of Eels:HashSet - 導致重複的整數不被允許,只是錯誤的名字。ArrayList來計算HashSet的數量。對不起格式.. – 2012-03-31 13:52:20

回答

1

看看這個解決方案。它現在只顯示計數器但打印你的子陣列。如果您只需要繼續子數組,您可以輕鬆修改它。
正如你所看到的,我既沒有使用HashSet也沒有使用ArrayList來存儲臨時數據,只是一個計數器。

import java.util.ArrayList; 
public class SUB_ARRAY{ 
    public static int SUBARRAY_MINIMUM_LENGTH = 2; 
    public static void main(String a[]){ 
     ArrayList<Integer> x = new ArrayList<Integer>(); 
     x.add(5); 
     x.add(0); 
     x.add(1); 
     x.add(3); 
     x.add(4); 
     x.add(2); 
     x.add(3); 
     x.add(6); 
     x.add(1); 
     x.add(0); 
     x.add(4); 
     int monoton = 0; 
     int changed = -1; 
     System.out.println("Initial array: " + x.toString()); 
     for (int i=0; i< x.size() -1; ++i){ 
      if (x.get(i+1) > x.get(i)){ 
       if (changed > -1){ 
        for (int j = changed; j <i+2; ++j){ 
         monoton += checkSubArray(x, j, i+2);; 
        } 
       } 
       else{ 
        System.out.println("New monoton subarray start index: " + i + " value: " + x.get(i)); 
        changed = i; 
        monoton += checkSubArray(x, changed, i+2); 
       } 
      } 
      else if (changed > -1){ 
       changed = -1; 
      } 
     }  
     System.out.println("Monoton count: " + monoton); 
    }  

    private static int checkSubArray(ArrayList<Integer> x, int start, int end) 
    { 
     if (end-start < SUBARRAY_MINIMUM_LENGTH){ 
      return 0; 
     } 
     for (int subi = start; subi < end; ++subi){ 
      System.out.print(" " + x.get(subi)); 
     } 
     System.out.println(); 
     return 1; 
    } 
} 

輸出將是以下

 
Initial array: [5, 0, 1, 3, 4, 2, 3, 6, 1, 0, 4] 
New monoton subarray start index: 1 value: 0 
0 1 
0 1 3 
1 3 
0 1 3 4 
1 3 4 
3 4 
New monoton subarray start index: 5 value: 2 
2 3 
2 3 6 
3 6 
New monoton subarray start index: 9 value: 0 
0 4 
Monoton count: 10 
+1

請嘗試理解代碼,而不是僅僅複製+使用它,如果它適合你。 – dexametason 2012-04-08 10:27:27