3ms c++ understandable


  • 0
    Y
    vector<int> constructRectangle(int area) 
        {
            int diff=10000000;//the difference between two factors
            int width, length;
            vector <int>result;
            if(area==0||area==1)
            {
                result.push_back(area);
                result.push_back(area);
                return result;
            }
            for(int i=1,temp;i<=sqrt(area);i++)
            {
                if(!(area%i))//if i is one of the factor
                {
                    temp=area/i;
                    int tempDiff=abs(i-temp);
                    if(diff>tempDiff)
                    {
                        diff=tempDiff;//update difference
                        width=i;
                        length=temp;
                    }
                }
            }
            if(width>length)
            {
                int temp=width;
                width=length;
                length=width;
            }
            result.push_back(length);
            result.push_back(width);
            return result;
        }
    

Log in to reply
 

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