我们有一系列高度,代表沿着步道的高度。给定数组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;
}
答案 0 :(得分:2)
你在循环中增加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]);
}
答案 1 :(得分: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;
}
答案 2 :(得分:0)
我是这样做的:
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;
}