查找步行道距离之间的高度
我们有一系列高度,代表步行道沿线的高度。给定数组中的 start
/end
索引,返回从 start
索引开始到 结束的遍历的变化总和>结束
索引。例如,对于高度 {5, 3, 6, 7, 2}
和 start=2
,end=4
的总和为1 + 5 = 6
。 start end end 索引都是带有 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;
}
We have an array of heights, representing the altitude along a walking trail. Given start
/end
indexes into the array, return the sum of the changes for a walk beginning at the start
index and ending at the end
index. For example, with the heights {5, 3, 6, 7, 2}
and start=2
, end=4
yields a sum of 1 + 5 = 6
. The start end end index will both be valid indexes into the array with 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
i'm struggling to get this right, i have tried a part of this but im confused and im getting 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在循环中增加 i ,因此可能会超出范围:
要修复它,请使用:
编辑:您还可以使循环更简单:
You increment i in your loop thus possibly going out of bounds:
To fix it, use:
Edit: you could also make the loop much simpler:
这是因为
i
。在循环内使用i+1
而不是i++
。++
运算符不返回i+1
,而是返回i
并赋值i=i+1
。for
循环对i
的值有错误的定义。如果您想返回sumHeights({11, 12}, 0, 1)
您只想运行循环一次,对吗?如果运行此循环两次,第二次运行时i+1
将等于2
,并且会抛出索引越界异常。difference
变量声明来解决它。试试这个代码:
This is because
i
inside the loop. Usei+1
instead ofi++
inside the loop. The++
operator does not returni+1
but rather returnsi
and assignsi=i+1
.for
loop has a wrong definition for the values ofi
. If you want to returnsumHeights({11, 12}, 0, 1)
you want to run the loop just once right? If you run this loop twicei+1
will be equal to2
in the second run and it will throw the index out of bound exception.heights[i] == heights[i+1]
- in that case difference is not re-calculated and may be assigned in a previous loop run. You can solve it by movingdifference
variable declaration inside the loop.Try this code:
我是这样做的:
I did it like this: