Leecode42_trap

思路:
为了减少遍历次数,采用左右向中间走的方式,同时维护一个左侧的最大值和右侧的最大值,当前值和最大值的差值则为当前块增加的水量。

int Leecode42_trap(std::vector<int>& height) {
     
	int left = 0, right = height.size() - 1;
	int ans = 0,left_max = 0, right_max = 0;
	while (left < right) {
     
		if (height[left] < height[right]) {
     
			height[left] >= left_max ? (left_max = height[left]) : ans += (left_max - height[left]);
			++left;
		}
		else {
     
			height[right] >= right_max ? (right_max = height[right]) : ans += (right_max - height[right]);
			--right;
		}
	}
	return ans;
}

和这个有点类似的一个题目是Lecode 11盛最多水的题目:
Leecode42_trap_第1张图片

你可能感兴趣的:(Leecode)