My code gets correct result on VS2012, but it gets an RE here...test case is {4,2,3} {5,2,1,2,1,5}


  • 0
    B

    Another test case is .

    I tested my code on VS2012, and each time I get a correct answer. But here I always get a RE.

    Anyone konws why?
    Maybe this problem may have a strict memory limit, that it refuse to alloc memory to the class "Array2D"?

    template<class T> class Array2D{
    private:
    	T* pData;
    	int dim1;
    	int dim2;
    	int dim1Index;
    	class Array1D{
    	private:
    		int length;
    		T* start;
    	public:
    		Array1D(T* start, int length) :length(length), start(start){}
    		T& operator[](int index){
    			if (index > length){
    				throw out_of_range("");
    			}
    			else{
    				return *(start + index);
    			}
    		}
    	};
    	
    public:
    	Array2D(int dim1, int dim2){
    		this->dim1 = dim1;
    		this->dim2 = dim2;
    		int size = dim1*dim2;
    		pData = new T[size];
    		memset(pData, 0, size*sizeof(T));
    	}
    	Array1D operator[](int index){
    		return Array1D(pData + index*dim1, dim2);
    	}
    };
    bool lowerbound(Array2D<int> & ar,int i,int k)
    {
    	for (int j = i; j >= 0;j--)
    	{
    		if (ar[j][k]==2)
    		{
    			return true;
    		}
    	}
    	return false;
    }
    bool upperbound(Array2D<int> & ar, int i, int k,int len)
    {
    	for (int j = i; j < len; j++)
    	{
    		if (ar[j][k] == 2)
    		{
    			return true;
    		}
    	}
    	return false;
    }
    int trap(vector<int>& height) {
    	const int len = height.size();
    	int maxHeight = 0;
    	for (int i = 0; i < height.size();i++	)
    	{
    		if (height[i]>maxHeight)
    		{
    			maxHeight = height[i];
    		}
    	}
    	if (maxHeight==0)
    	{
    		return 0;
    	}
    	else if (len<3)
    	{
    		return 0;
    	}
    	Array2D<int> ar(len, maxHeight);
        for (int i = 0; i < len; i++)
    {
    	for (int k = 0; k < maxHeight; k++)
    	{
    		ar[i][k] = 0;
    	}
    }
    	for (int j = 0, i = 0; i < height.size();i++)
    	{
    		for (j = 0; j < height[i];j++)
    		{
    			ar[i][j] = 2;
    		}
    	}
    	for (int k = 0; k < maxHeight;k++)
    	{
    		for (int i = 1; i < (len-1);i++)
    		{
    			if (ar[i][k]==0 && lowerbound(ar,i,k) && upperbound(ar,i,k,len))
    			{
    				ar[i][k] = 1;
    			}
    		}
    	}
    	int res = 0;
    	for (int i = 0; i < len;i++)
    	{
    		for (int k = 0; k < maxHeight;k++)
    		{
    			if (ar[i][k]==1)
    			{
    				res++;
    			}
    		}
    	}
    	return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.