Leetcode_42_接雨水

Leetcode_42_接雨水_第1张图片
Leetcode_42_接雨水_第2张图片

#include 

// add necessary includes here
#include 

#include 
#include 
#include 
#include 
using namespace std;
class Solution {
 public:
  int trap(vector<int>& height);
};

class LeetCode : public QObject {
  Q_OBJECT

 public:
  LeetCode(){};
  ~LeetCode(){};

 private slots:
  void test_case1();
  void test_case2();
  void test_case3();
  void test_case4();
};

QTEST_APPLESS_MAIN(LeetCode)

#include "tst_leetcode.moc"

//____________________________________________________________________________
void LeetCode::test_case1() {
  vector<int> height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
  int expected = 6;
  Solution sl;
  int actual = sl.trap(height);
  printf("[%d %d] \n", actual, expected);
  QCOMPARE(actual, expected);
}
void LeetCode::test_case2() {
  vector<int> height = {4, 2, 0, 3, 2, 5};
  int expected = 9;
  Solution sl;
  int actual = sl.trap(height);
  printf("[%d %d] \n", actual, expected);
  QCOMPARE(actual, expected);
}
void LeetCode::test_case3() {}
void LeetCode::test_case4() {}

int Solution::trap(vector<int>& height) {
  int lp = 0;
  int rp = height.size() - 1;
  int lmax = 0;
  int rmax = 0;
  int water = 0;

  while (lp < rp) {
    if (height.at(lp) < height.at(rp)) {
      if (height.at(lp) >= lmax) {
        lmax = height.at(lp);
      } else {
        water += lmax - height.at(lp);
      }
      lp++;
      printf("Left: %d \n", water);
    } else {
      if (height.at(rp) >= rmax) {
        rmax = height.at(rp);
      } else {
        water += rmax - height.at(rp);
      }
      rp--;
      printf("Right: %d \n", water);
    }
  }

  return water;
}

Leetcode_42_接雨水_第3张图片

你可能感兴趣的:(算法,汽车,leetcode,算法)