首页 > 移动平台 > 详细

LeetCode_41trap [Trapping Rain Water]

时间:2014-07-21 23:29:51      阅读:615      评论:0      收藏:0      [点我收藏+]
#pragma warning(disable:4996)

#include <cstdio>
#include <tchar.h>
#include <Windows.h>

/*
	submit time : 3
		1.Time Limit Exceeded
			Last executed input:	[]		
		2.Cant‘s remember
	request :
		Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

		For example,
		Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
*/

int helpMin(int i, int j) {
	return i < j ? i : j;
}

void helpTrap(int& water, int* data, int length, int l, int r) {
	if (r - l <= 1) return;		// do not calculate one or two numbers

	// find two biggest numbers
	int big1value = 0, big2value = 0;
	int big1index = 0, big2index = 0;
	int vernier = l;
	while (vernier <= r) {
		if (data[vernier] >= big1value) {
			if (data[vernier] >= big2value) {
				big1index = big2index;
				big1value = big2value;
				big2index = vernier;
				big2value = data[vernier];
			}
			else {
				big1index = vernier;
				big1value = data[vernier];
			}
		}
		++vernier;
	}

	// calculate current trap
	int lr = helpMin(big1index, big2index), rl = big1index + big2index - lr;
	int currWater = 0;
	vernier = lr;
	while (++vernier < rl)
		water += (big1value - data[vernier]);

	// calculate other two sides
	helpTrap(water, data, length, l, lr);
	helpTrap(water, data, length, rl, r);
}

int trap(int A[], int n) {
	if (A == NULL || n <= 2) return 0;

	int water = 0;
	helpTrap(water, A, n, 0, n - 1);

	return water;
}

//============Test==================
void Test(const char* testName, int* data, int length) {
	printf("%s begins:\n", testName);

	int result = trap(data, length);
	printf("%d\n", result);
}

void Test1() {
	int data[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
	Test("Test1", data, sizeof(data) / sizeof(int));
}

void Test2() {
	int data[] = { 0, 1, 2, 3, 3, 3, 3, 3, 2, 1 };
	Test("Test2", data, sizeof(data) / sizeof(int));
}

void Test3() {
	int data[] = { 0, 1, 2, 3, 4, 5, 1, 2 };
	Test("Test3", data, sizeof(data) / sizeof(int));
}

void Test4() {
	int data[] = { 100, 0,0,1,0,0, 1000 };
	Test("Test4", data, sizeof(data) / sizeof(int));
}

void Test5() {
	int data[] = { 5,2,1,2,1,5 };
	Test("Test5", data, sizeof(data) / sizeof(int));
}

int _tmain(int argc, _TCHAR* argv[]) {
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();

	system("pause");
	return 0;
}



LeetCode_41trap [Trapping Rain Water],布布扣,bubuko.com

LeetCode_41trap [Trapping Rain Water]

原文:http://my.oschina.net/ITHaozi/blog/293312

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!