[英]Find the heights between the distances of a walking trail
我們有一個高度數組,表示沿着步行道的高度。 給定數組的start
/ end
索引,返回從start
索引開始到end
索引結束的遍歷的總和。 例如,對於高度{5, 3, 6, 7, 2}
和start=2
, end=4
產生1 + 5 = 6
的總和。 開始結束結束索引都將是數組的有效索引start <= end
。
sumHeights({5, 3, 6, 7, 2}, 2, 4) => 6
sumHeights({5, 3, 6, 7, 2}, 0, 1) => 2
sumHeights({5, 3, 6, 7, 2}, 0, 4) => 11
我正在努力做到這一點,我已經嘗試了其中的一部分,但我很困惑並且我得到了ArrayIndexOutOfBoundsException
。
public int sumHeights(int[] heights, int start, int end) {
int total =0;
int difference =0;
for(int i=start;i<=end;i++){
if(heights[i] > heights[i++]){
difference =heights[i] - heights[i++];
}else if(heights[i++] > heights[i]){
difference =heights[i++] - heights[i];
}
total+=difference;
}
return total;
}
您在循環中增加 i ,因此可能超出范圍:
for(int i=start;i<=end;i++){ // here i might be last valid index, i.e. 4 in your example
if(heights[i] > heights[i++]){ //here i might be 5 (because of i++), i.e. you'd get the ArrayIndexOutOfBoundsException
difference =heights[i] - heights[i++]; //here i might be 6 (because of another i++), i.e. you'd get the ArrayIndexOutOfBoundsException
}else if(heights[i++] > heights[i]){ //here i might be 5, i.e. you'd get the ArrayIndexOutOfBoundsException
difference =heights[i++] - heights[i];
}
total+=difference;
}
要修復它,請使用:
for(int i=start;i<end;i++){
int next = i + 1;
if(heights[i] > heights[next]){
difference =heights[i] - heights[next]; //assuming you mean next = i + 1 here and not next = i + 2 like in your code
}else if(heights[next] > heights[i]){
difference =heights[next] - heights[i];
}
else {
difference = 0; //due to public demand I'll help you with this, too
}
total+=difference;
}
編輯:您還可以使循環更簡單:
for(int i=start;i<end;i++){
total += Math.abs(heights[i] - heights[i+1]);
}
這是因為
i
。 在循環內使用i+1
而不是i++
。 ++
運算符不返回i+1
而是返回i
並分配i=i+1
。for
循環對i
的值的定義錯誤。 如果你想返回sumHeights({11, 12}, 0, 1)
你想只運行一次循環,對嗎? 如果你運行這個循環兩次i+1
在第二次運行中將等於2
並且它會拋出索引超出范圍異常。heights[i] == heights[i+1]
- 在這種情況下,差異不會重新計算,並且可以在之前的循環運行中分配。 您可以通過在循環內移動difference
變量聲明來解決它。試試這個代碼:
public int sumHeights(int[] heights, int start, int end) {
int total =0;
for(int i=start;i<end;i++){
int difference =0;
if(heights[i] > heights[i+1]){
difference =heights[i] - heights[i+1];
}else if(heights[i+1] > heights[i]){
difference =heights[i+1] - heights[i];
}
total+=difference;
}
return total;
}
我是這樣做的:
public int sumHeights(int[] heights, int start, int end) {
int sum=0;
while(start<end)
{
sum+=Math.abs(heights[start+1]-heights[start]);
start++;
}
return sum;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.