这题不太好想。可以先扫描找到最高的柱子,然后分别处理两边。
int trapWater(int A[], int n) { int peak = 0; int max = 0; int water = 0; for (int i = 1; i < n; i++) { if (A[i]>A[max])max = i; } for (int i = 0; i < max; i++) { if (A[i]>peak) peak = A[i]; else water += peak - A[i]; } for (int j = n - 1; j > max; j--) { if (A[j]>peak) peak = A[j]; else water += peak - A[j]; } return water; }
时间: 2024-10-02 14:56:27