gpt4 book ai didi

java - 查找步行道距离之间的高度

转载 作者:行者123 更新时间:2023-12-02 00:42:51 25 4
gpt4 key购买 nike

我们有一系列高度,代表步行道上的高度。鉴于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]);
}

关于java - 查找步行道距离之间的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5848390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com