2017-01-02 43 views
-2

一直試圖找到一種方法來解決this CodeWars challenge,但無法找到一種方法來檢查是否存在例如。連續4個數字。如果我得到2我可以這樣做:if (s.get(i) == s.get(i + 1) 但我怎麼實際檢查是否有可能連續10個數字?我不能只是做s.get(i) == ... == s.get(i + 10) 因爲可能有11,所以肯定這不是我尋找的答案。到目前爲止,我得到了這個,因爲林肯定我必須迭代所有的對象,但不知道如何做比較和添加到我的結果ArrayList,所以它取代了這些連續的數字。在列表中找到相同和連續的數字

public static List<Integer> sumConsecutives(List<Integer> s) { 
    List<Integer> result = new ArrayList<Integer>(s); 
    for (int i : s) { 
     if() // checking if there are consecutive same numbers 
    } 
} 
+0

跟蹤上一個號碼,並檢查該號碼。 – marstran

+1

[在Java中查找連續數字]可能的副本(http://stackoverflow.com/questions/28419113/finding-consecutive-numbers-in-java) – smoggers

+0

並且在您更改值後重置增量。 – AxelH

回答

1

這是最簡單的解決方案,我能想到的:

public static List<Integer> sumConsecutives(List<Integer> s) { 
    ArrayList<Integer> returnList = new ArrayList<>(); 
    int currentRepeating = 0; 
    for (int i : s) { 
     if (returnList.isEmpty() || currentRepeating != i) { 
      currentRepeating = i; 
      returnList.add(i); 
     } else { 
      returnList.set(returnList.size() - 1, returnList.get(returnList.size() - 1) + i); 
     } 
    } 
    return returnList; 
} 

對於輸入每個號碼i,如果當前的重複數不等於i,添加i到返回列表並將當前重複號碼設置爲i。如果它等於當前重複數字,將它添加到列表中的最後一個元素。

相關問題