I am writing the code as shown at the bottom of this question.
For the while loop part, I thought the following two codes are just the same
first one
while (lIndex < rIndex && height[++lIndex] <= left) {
ans += (left - height[lIndex]);
}
second one
while (lIndex < rIndex && height[lIndex + 1] <= left) {
ans += (left - height[lIndex + 1]);
lIndex++;
}
However, when I run the second one on system, There is an error of Time Limit Exceeding. Could someone explain the reason of this problem? Thanks for reading my question.
Original code:
public int trap(int[] height) {
if (height.length < 3) return 0;
int ans = 0;
int lIndex = 0;
int rIndex = height.length - 1;
// Find the first wall on each side
while (lIndex < rIndex && height[lIndex] <= height[lIndex + 1]) lIndex++;
while (lIndex < rIndex && height[rIndex] <= height[rIndex - 1]) rIndex--;
while (lIndex < rIndex) {
int left = height[lIndex];
int right = height[rIndex];
if (left <= right) {
while (lIndex < rIndex && height[++lIndex] <= left) {
ans += (left - height[lIndex]);
}
}
else {
while (lIndex < rIndex && height[--rIndex] <= right) {
ans += right - height[rIndex];
}
}
}
return ans;
}